Skip to content

Commit

Permalink
refactor: esm
Browse files Browse the repository at this point in the history
  • Loading branch information
uetchy committed Jun 1, 2022
1 parent 0f1582a commit 60264a2
Show file tree
Hide file tree
Showing 10 changed files with 835 additions and 1,094 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ mc print WpjhEqjngRQ --filter 'message.includes("草")' # Only show chat contain
- `--type, -t <string>`: Chat type (`top` or `all`)
- `--author, -a`: Show author name
- `--filter, -f <string>`: Filter chat/superchat events
- `--mod, -m`: Print moderation events
- `--mod`: Print moderation events
- `--verbose, -v`: Print additional info
- `--collect, -c`: Save received actions as JSONLines (.jsonl)

Expand Down
4 changes: 2 additions & 2 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
module.exports = {
export default {
preset: "ts-jest/presets/default-esm",
globals: {
"ts-jest": {
useESM: true,
},
},
};
}
25 changes: 13 additions & 12 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"prepublishOnly": "npm run clean && npm run build",
"test": "npm run build && jest"
},
"type": "module",
"main": "dist/cli.js",
"bin": {
"masterchat": "dist/cli.js",
Expand All @@ -21,26 +22,26 @@
"dist"
],
"dependencies": {
"chalk": "^4.1.2",
"chalk": "^5.0.1",
"cross-fetch": "^3.1.4",
"epicfail": "^3.0.0",
"lru-cache": "^7.10.1",
"masterchat": "^0.14.0",
"masterchat": "^1.0.0",
"vm2": "^3.9.9",
"yargs": "^17.2.1"
"yargs": "^17.5.1"
},
"devDependencies": {
"@types/jest": "^27.4.1",
"@types/node": "^16.11.10",
"execa": "^5.1.1",
"husky": "^7.0.4",
"jest": "^27.3.1",
"prettier": "^2.4.1",
"@types/jest": "^27.5.1",
"@types/node": "^17.0.36",
"execa": "^6.1.0",
"husky": "^8.0.1",
"jest": "^28.1.0",
"prettier": "^2.6.2",
"pretty-quick": "^3.1.2",
"shx": "^0.3.3",
"ts-jest": "^27.0.7",
"ts-node": "^10.7.0",
"typescript": "^4.6.2"
"ts-jest": "^28.0.3",
"ts-node": "^10.8.0",
"typescript": "^4.7.2"
},
"homepage": "https://github.com/holodata/masterchat-cli",
"repository": {
Expand Down
8 changes: 4 additions & 4 deletions src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
#!/usr/bin/env node

import yargs from "yargs"
import print from "./commands/print"
import watch from "./commands/watch"
import pbd from "./commands/pbd"
import print from "./commands/print.js"
import watch from "./commands/watch.js"
import pbd from "./commands/pbd.js"
import { epicfail } from "epicfail"

epicfail(require.main?.filename!)
epicfail(import.meta.url)

yargs(process.argv.slice(2))
.scriptName("masterchat")
Expand Down
64 changes: 35 additions & 29 deletions src/commands/print.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import chalk from "chalk"
import fetch from "cross-fetch"
import { logAndExit } from "epicfail"
import LRU from "lru-cache"
import { Action, Masterchat, stringify, toVideoId, YTRun } from "masterchat"
import fs from "node:fs/promises"
import { VM, VMScript } from "vm2"
import { Arguments, CommandModule } from "yargs"
import LRU from "lru-cache"
import { chalkSc } from "../lib/printer.js"

const imageCache = new LRU({ max: 500 })

Expand All @@ -30,31 +31,30 @@ function toBuffer(ab: ArrayBuffer) {
return buf
}

async function toInlineImage(url: string, fallback: string = "") {
const isiTerm = process.env.TERM_PROGRAM === "iTerm.app"
if (!isiTerm) return fallback
function isiTerm() {
return process.env.TERM_PROGRAM === "iTerm.app"
}

async function toInlineImage(url: string) {
const cached = imageCache.get<string>(url)
if (cached) return cached
// console.log(chalk.red("no cache hit", imageCache.size))
try {
const buf = toBuffer(await fetch(url).then((res) => res.arrayBuffer()))
const content = buf.toString("base64")
const args = {
size: buf.byteLength,
inline: 1,
height: 1,
// width: "auto",
// preserveAspectRatio: 1,
}
const argsString = Object.entries(args)
.map(([k, v]) => `${k}=${v}`)
.join(";")
const ansiString = `\u001B]1337;File=${argsString}:${content}\u0007`
imageCache.set(url, ansiString)
return ansiString
} catch (err) {
return fallback

const buf = toBuffer(await fetch(url).then((res) => res.arrayBuffer()))
const content = buf.toString("base64")
const args = {
size: buf.byteLength,
inline: 1,
height: 1,
// width: "auto",
// preserveAspectRatio: 1,
}
const argsString = Object.entries(args)
.map(([k, v]) => `${k}=${v}`)
.join(";")
const ansiString = `\u001B]1337;File=${argsString}:${content}\u0007`
imageCache.set(url, ansiString)

return ansiString
}

async function termify(msg: YTRun[]): Promise<string> {
Expand All @@ -71,7 +71,7 @@ async function termify(msg: YTRun[]): Promise<string> {
const shortcut = emoji.shortcuts[emoji.shortcuts.length - 1]
const url =
emoji.image.thumbnails[emoji.image.thumbnails.length - 1].url
res += await toInlineImage(url, shortcut)
res += isiTerm() ? await toInlineImage(url) : shortcut
}
}
}
Expand All @@ -94,17 +94,21 @@ export async function stringifyActions(
let text = ""

if (showAuthor) {
if (isiTerm()) {
text += await toInlineImage(action.authorPhoto)
text += " "
}
text += chalk.gray(action.authorName)
text += ": "
}

text += action.message
? stringify(action.message, { spaces: true })
? await termify(action.message)
: "<empty message>"

text += ` (${action.amount} ${action.currency})`

simpleChat.push(text)
simpleChat.push(chalkSc(action.color)(text))
break
}
case "addChatItemAction": {
Expand All @@ -126,8 +130,11 @@ export async function stringifyActions(
badges.push("⚡️")
}

text += await toInlineImage(action.authorPhoto)
text += " "
if (isiTerm()) {
text += await toInlineImage(action.authorPhoto)
text += " "
}

text += colorize(action.authorName)

if (badges.length >= 1) {
Expand Down Expand Up @@ -285,7 +292,6 @@ async function handler(argv: Arguments<Args>) {
}
}

console.log("Live stream has ended")
process.exit(0)
}

Expand Down
4 changes: 2 additions & 2 deletions src/commands/watch.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import chalk from "chalk"
import { Masterchat, StreamPool } from "masterchat"
import { Arguments, CommandModule } from "yargs"
import { printData } from "../lib/printer"
import { ChatHistory } from "../lib/history"
import { printData } from "../lib/printer.js"
import { ChatHistory } from "../lib/history.js"
import fetch from "cross-fetch"

interface Args {
Expand Down
18 changes: 9 additions & 9 deletions src/lib/printer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
stringify,
SuperChat,
} from "masterchat"
import { ChatHistory } from "./history"
import { ChatHistory } from "./history.js"

export function printData({
data,
Expand Down Expand Up @@ -89,21 +89,21 @@ export function printData({
chalk.green(
`[membership joined] Welcome${
action.level ? ` ${action.level},` : ""
} ${action.authorName} !: ${action.membership.status} ${
action.membership.since ?? ""
}`
} ${action.authorName} !: ${
action.membership?.status ?? "No status"
} ${action.membership?.since ?? ""}`
)
)
break
}
case "addMembershipMilestoneItemAction": {
log(
chalk.green(
`[milestone ${action.authorName} (${action.membership.status} ${
action.membership.since ?? ""
})] Member${action.level ? ` of ${action.level}` : ""} for ${
action.durationText
} (${action.duration}): ${
`[milestone ${action.authorName} (${
action.membership?.status ?? "No status"
} ${action.membership?.since ?? ""})] Member${
action.level ? ` of ${action.level}` : ""
} for ${action.durationText} (${action.duration}): ${
action.message ? stringify(action.message) : "<empty message>"
}`
)
Expand Down
2 changes: 1 addition & 1 deletion tests/cli.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import execa from "execa"
import { execa } from "execa"

it("can run", async () => {
const res = await execa("node", ["./dist/cli.js", "--help"])
Expand Down
9 changes: 3 additions & 6 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,10 @@

/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es2019" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
// "moduleResolution": "node",
"target": "ESNext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
"moduleResolution": "node",
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
"declaration": true /* Generates corresponding '.d.ts' file. */,
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
Expand Down
Loading

0 comments on commit 60264a2

Please sign in to comment.