@kud/cli-shot 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +110 -12
- package/dist/chunk-ISLF4ISU.js +599 -0
- package/dist/cli.js +95 -5
- package/dist/index.d.ts +193 -4
- package/dist/index.js +1 -1
- package/package.json +16 -3
- package/player/chrome.css +273 -0
- package/player/fonts/LICENSE +21 -0
- package/player/fonts/README.md +21 -0
- package/player/fonts/SymbolsNerdFontMono-Regular.woff2 +0 -0
- package/player/index.html +37 -0
- package/player/player.js +267 -0
- package/dist/chunk-TKCXCDP2.js +0 -202
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync, mkdtempSync, rmSync, copyFileSync, readdirSync, existsSync, accessSync, constants } from 'fs';
|
|
2
|
+
import { tmpdir, cpus } from 'os';
|
|
3
|
+
import { dirname, join, relative, sep, extname, basename } from 'path';
|
|
4
|
+
import { createRequire } from 'module';
|
|
5
|
+
import { spawn } from 'node-pty';
|
|
6
|
+
import headless from '@xterm/headless';
|
|
7
|
+
import { SerializeAddon } from '@xterm/addon-serialize';
|
|
8
|
+
import { execFileSync, spawnSync } from 'child_process';
|
|
9
|
+
import { fileURLToPath } from 'url';
|
|
10
|
+
|
|
11
|
+
// src/index.ts
|
|
12
|
+
var { Terminal } = headless;
|
|
13
|
+
var TICK_MS = 60;
|
|
14
|
+
var HELPER_FAILURE = /execvp\(\d\) failed|posix_spawnp failed/;
|
|
15
|
+
var explainSpawnFailure = (error, command) => {
|
|
16
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
17
|
+
const helper = helperPath();
|
|
18
|
+
const notExecutable = message.includes("posix_spawnp") && helper !== void 0 && !isExecutable(helper);
|
|
19
|
+
return new Error(
|
|
20
|
+
`Could not open a pty for ${command}: ${message}
|
|
21
|
+
` + (notExecutable ? ` node-pty's helper is not executable. Fix with:
|
|
22
|
+
chmod +x ${helper}
|
|
23
|
+
It ships without the mode bit when install scripts are blocked;
|
|
24
|
+
npm approve-scripts node-pty makes it survive a reinstall.` : ` Check that the command exists and is executable.`),
|
|
25
|
+
{ cause: error }
|
|
26
|
+
);
|
|
27
|
+
};
|
|
28
|
+
var helperPath = () => {
|
|
29
|
+
const candidate = createRequire(import.meta.url).resolve("node-pty").replace(
|
|
30
|
+
/node-pty\/.*$/,
|
|
31
|
+
`node-pty/prebuilds/${process.platform}-${process.arch}/spawn-helper`
|
|
32
|
+
);
|
|
33
|
+
return existsSync(candidate) ? candidate : void 0;
|
|
34
|
+
};
|
|
35
|
+
var isExecutable = (path) => {
|
|
36
|
+
try {
|
|
37
|
+
accessSync(path, constants.X_OK);
|
|
38
|
+
return true;
|
|
39
|
+
} catch {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
var DEFAULT_COLS = 110;
|
|
44
|
+
var DEFAULT_ROWS = 32;
|
|
45
|
+
var capture = (command, args = [], {
|
|
46
|
+
cols = DEFAULT_COLS,
|
|
47
|
+
rows = DEFAULT_ROWS,
|
|
48
|
+
settle = 350,
|
|
49
|
+
timeout = 15e3,
|
|
50
|
+
env,
|
|
51
|
+
keys,
|
|
52
|
+
onOutput
|
|
53
|
+
} = {}) => new Promise((resolve, reject) => {
|
|
54
|
+
const term = new Terminal({ cols, rows, allowProposedApi: true });
|
|
55
|
+
const serializer = new SerializeAddon();
|
|
56
|
+
term.loadAddon(serializer);
|
|
57
|
+
let pty;
|
|
58
|
+
try {
|
|
59
|
+
pty = spawn(command, [...args], {
|
|
60
|
+
name: "xterm-256color",
|
|
61
|
+
cols,
|
|
62
|
+
rows,
|
|
63
|
+
env: { ...process.env, ...env }
|
|
64
|
+
});
|
|
65
|
+
} catch (error) {
|
|
66
|
+
reject(explainSpawnFailure(error, command));
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
let raw = 0;
|
|
70
|
+
let rawText = "";
|
|
71
|
+
let sentKeys = false;
|
|
72
|
+
let finished = false;
|
|
73
|
+
let previous = "";
|
|
74
|
+
const started = performance.now();
|
|
75
|
+
const finish = () => {
|
|
76
|
+
if (finished) return;
|
|
77
|
+
finished = true;
|
|
78
|
+
clearInterval(poll);
|
|
79
|
+
clearTimeout(hard);
|
|
80
|
+
try {
|
|
81
|
+
pty.kill();
|
|
82
|
+
} catch {
|
|
83
|
+
}
|
|
84
|
+
term.write("", () => resolve(serializer.serialize()));
|
|
85
|
+
};
|
|
86
|
+
const grid = () => {
|
|
87
|
+
const buffer = term.buffer.active;
|
|
88
|
+
const lines = [];
|
|
89
|
+
for (let y = 0; y < buffer.length; y++) {
|
|
90
|
+
lines.push(buffer.getLine(y)?.translateToString(true) ?? "");
|
|
91
|
+
}
|
|
92
|
+
return lines.join("\n");
|
|
93
|
+
};
|
|
94
|
+
let stableFor = 0;
|
|
95
|
+
const poll = setInterval(() => {
|
|
96
|
+
const current = grid();
|
|
97
|
+
if (current !== previous || !current.trim()) {
|
|
98
|
+
previous = current;
|
|
99
|
+
stableFor = 0;
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
stableFor += TICK_MS;
|
|
103
|
+
if (stableFor < settle) return;
|
|
104
|
+
if (keys && !sentKeys) {
|
|
105
|
+
sentKeys = true;
|
|
106
|
+
pty.write(keys);
|
|
107
|
+
previous = "";
|
|
108
|
+
stableFor = 0;
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
finish();
|
|
112
|
+
}, TICK_MS);
|
|
113
|
+
const hard = setTimeout(finish, timeout);
|
|
114
|
+
pty.onData((data) => {
|
|
115
|
+
if (!finished) onOutput?.(data, performance.now() - started);
|
|
116
|
+
raw += data.length;
|
|
117
|
+
if (rawText.length < 2048) rawText += data;
|
|
118
|
+
term.write(data);
|
|
119
|
+
});
|
|
120
|
+
pty.onExit(({ exitCode }) => {
|
|
121
|
+
if (exitCode !== 0 && (raw === 0 || HELPER_FAILURE.test(rawText))) {
|
|
122
|
+
finished = true;
|
|
123
|
+
clearInterval(poll);
|
|
124
|
+
clearTimeout(hard);
|
|
125
|
+
reject(
|
|
126
|
+
explainSpawnFailure(
|
|
127
|
+
new Error(`the command exited ${exitCode} without drawing a screen`),
|
|
128
|
+
command
|
|
129
|
+
)
|
|
130
|
+
);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
finish();
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
// src/cast.ts
|
|
138
|
+
var seconds = (value) => Math.round(value * 1e6) / 1e6;
|
|
139
|
+
var castHeader = ({
|
|
140
|
+
width,
|
|
141
|
+
height,
|
|
142
|
+
timestamp,
|
|
143
|
+
idleTimeLimit,
|
|
144
|
+
title,
|
|
145
|
+
env
|
|
146
|
+
}) => {
|
|
147
|
+
if (!Number.isInteger(width) || width < 1)
|
|
148
|
+
throw new Error(`cast width must be a positive integer, got ${width}`);
|
|
149
|
+
if (!Number.isInteger(height) || height < 1)
|
|
150
|
+
throw new Error(`cast height must be a positive integer, got ${height}`);
|
|
151
|
+
return JSON.stringify({
|
|
152
|
+
version: 2,
|
|
153
|
+
width,
|
|
154
|
+
height,
|
|
155
|
+
...timestamp !== void 0 && { timestamp: Math.floor(timestamp) },
|
|
156
|
+
...idleTimeLimit !== void 0 && { idle_time_limit: idleTimeLimit },
|
|
157
|
+
...title !== void 0 && { title },
|
|
158
|
+
...env !== void 0 && { env }
|
|
159
|
+
});
|
|
160
|
+
};
|
|
161
|
+
var castEvent = ([time, code, data]) => JSON.stringify([seconds(time), code, data]);
|
|
162
|
+
var toCast = (header, events) => {
|
|
163
|
+
let last = 0;
|
|
164
|
+
const lines = events.map(([time, code, data]) => {
|
|
165
|
+
last = Math.max(last, seconds(time));
|
|
166
|
+
return castEvent([last, code, data]);
|
|
167
|
+
});
|
|
168
|
+
return [castHeader(header), ...lines].join("\n") + "\n";
|
|
169
|
+
};
|
|
170
|
+
var parseCast = (text) => {
|
|
171
|
+
const [first, ...rest] = text.split("\n").filter((line) => line.trim());
|
|
172
|
+
if (!first) throw new Error("empty cast");
|
|
173
|
+
const header = JSON.parse(first);
|
|
174
|
+
if (header.version !== 2)
|
|
175
|
+
throw new Error(`unsupported asciicast version ${header.version}`);
|
|
176
|
+
return { header, events: rest.map((line) => JSON.parse(line)) };
|
|
177
|
+
};
|
|
178
|
+
var listScreens = (command, args = []) => {
|
|
179
|
+
const printed = execFileSync(command, [...args, "--screen", "list"], {
|
|
180
|
+
encoding: "utf8"
|
|
181
|
+
});
|
|
182
|
+
return printed.split("\n").map((line) => line.trim()).filter(Boolean);
|
|
183
|
+
};
|
|
184
|
+
var DEFAULT_FONT = "JetBrainsMono Nerd Font Mono";
|
|
185
|
+
var toImage = (ansi, output, { font = DEFAULT_FONT, freezeArgs = [] } = {}) => {
|
|
186
|
+
const args = [
|
|
187
|
+
"--language",
|
|
188
|
+
"ansi",
|
|
189
|
+
"--output",
|
|
190
|
+
output,
|
|
191
|
+
"--font.family",
|
|
192
|
+
font,
|
|
193
|
+
...freezeArgs
|
|
194
|
+
];
|
|
195
|
+
mkdirSync(dirname(output), { recursive: true });
|
|
196
|
+
try {
|
|
197
|
+
execFileSync("freeze", args, { input: ansi });
|
|
198
|
+
return output;
|
|
199
|
+
} catch (error) {
|
|
200
|
+
const detail = String(error.stdout ?? "").trim();
|
|
201
|
+
throw new Error(
|
|
202
|
+
`freeze failed for ${output}
|
|
203
|
+
command: freeze ${args.join(" ")}
|
|
204
|
+
input: ${ansi.length} chars over stdin
|
|
205
|
+
` + (detail ? ` said: ${detail.replace(/\s+/g, " ")}` : ""),
|
|
206
|
+
{ cause: error }
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
var PLAYER = fileURLToPath(new URL("../player/", import.meta.url));
|
|
211
|
+
var ASSETS = ["player.js", "chrome.css"];
|
|
212
|
+
var FONT_FILES = ["SymbolsNerdFontMono-Regular.woff2", "LICENSE", "README.md"];
|
|
213
|
+
var xterm = (file) => createRequire(import.meta.url).resolve(`@xterm/xterm/${file}`);
|
|
214
|
+
var escapeHtml = (text) => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
215
|
+
var ICONS = {
|
|
216
|
+
play: '<svg class="icon-play" viewBox="0 0 16 16" aria-hidden="true"><path d="M4.5 2.8v10.4L13 8z"/></svg>',
|
|
217
|
+
pause: '<svg class="icon-pause" viewBox="0 0 16 16" aria-hidden="true"><path d="M4 2.5h3v11H4zM9 2.5h3v11H9z"/></svg>',
|
|
218
|
+
restart: '<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M8 2.5a5.5 5.5 0 1 1-5.2 3.7l1.4.5A4 4 0 1 0 8 4v2L4.8 3.2 8 .5z"/></svg>'
|
|
219
|
+
};
|
|
220
|
+
var screenMarkup = (command, screen) => {
|
|
221
|
+
const name = escapeHtml(screen);
|
|
222
|
+
const label = escapeHtml(`${command} ${screen}`);
|
|
223
|
+
const cast = escapeHtml(encodeURIComponent(`${screen}.cast`));
|
|
224
|
+
return [
|
|
225
|
+
` <figure class="window" data-cast="${cast}" aria-label="Terminal recording: ${label}">`,
|
|
226
|
+
` <div class="window-bar" aria-hidden="true">`,
|
|
227
|
+
` <span class="window-dots"><i></i><i></i><i></i></span>`,
|
|
228
|
+
` <span class="window-title">${label} \u2014 zsh</span>`,
|
|
229
|
+
` </div>`,
|
|
230
|
+
` <div class="window-screen"><div class="window-term"></div></div>`,
|
|
231
|
+
` <div class="window-controls" role="group" aria-label="Playback: ${name}">`,
|
|
232
|
+
` <button type="button" class="control" data-action="toggle" aria-label="Play">${ICONS.play}${ICONS.pause}</button>`,
|
|
233
|
+
` <button type="button" class="control" data-action="restart" aria-label="Restart">${ICONS.restart}</button>`,
|
|
234
|
+
` <button type="button" class="control control-speed" data-action="speed" aria-label="Playback speed 1\xD7, switch to 2\xD7">1\xD7</button>`,
|
|
235
|
+
` </div>`,
|
|
236
|
+
` </figure>`
|
|
237
|
+
].join("\n");
|
|
238
|
+
};
|
|
239
|
+
var VERCEL_CONFIG = {
|
|
240
|
+
$schema: "https://openapi.vercel.sh/vercel.json",
|
|
241
|
+
framework: null,
|
|
242
|
+
buildCommand: null,
|
|
243
|
+
installCommand: null,
|
|
244
|
+
trailingSlash: true,
|
|
245
|
+
headers: [
|
|
246
|
+
{
|
|
247
|
+
source: "/(.*).cast",
|
|
248
|
+
headers: [
|
|
249
|
+
{ key: "Content-Type", value: "application/x-asciicast; charset=utf-8" },
|
|
250
|
+
{ key: "Cache-Control", value: "public, max-age=300" }
|
|
251
|
+
]
|
|
252
|
+
},
|
|
253
|
+
{
|
|
254
|
+
source: "/assets/(.*)",
|
|
255
|
+
headers: [{ key: "Cache-Control", value: "public, max-age=86400" }]
|
|
256
|
+
}
|
|
257
|
+
]
|
|
258
|
+
};
|
|
259
|
+
var castsIn = (out) => readdirSync(out).filter((file) => file.endsWith(".cast")).sort().map((file) => basename(file, ".cast"));
|
|
260
|
+
var buildPlayer = ({
|
|
261
|
+
out,
|
|
262
|
+
screens = castsIn(out),
|
|
263
|
+
title = "Terminal demo",
|
|
264
|
+
base
|
|
265
|
+
}) => {
|
|
266
|
+
if (screens.length === 0) {
|
|
267
|
+
throw new Error(`No recordings to play: ${out} holds no .cast files.`);
|
|
268
|
+
}
|
|
269
|
+
const assets = join(out, "assets");
|
|
270
|
+
mkdirSync(join(assets, "fonts"), { recursive: true });
|
|
271
|
+
const written = [];
|
|
272
|
+
const copy = (from, to) => {
|
|
273
|
+
copyFileSync(from, to);
|
|
274
|
+
written.push(to);
|
|
275
|
+
};
|
|
276
|
+
for (const file of ASSETS) copy(join(PLAYER, file), join(assets, file));
|
|
277
|
+
for (const file of FONT_FILES) {
|
|
278
|
+
copy(join(PLAYER, "fonts", file), join(assets, "fonts", file));
|
|
279
|
+
}
|
|
280
|
+
copy(xterm("lib/xterm.mjs"), join(assets, "xterm.mjs"));
|
|
281
|
+
copy(xterm("css/xterm.css"), join(assets, "xterm.css"));
|
|
282
|
+
copy(
|
|
283
|
+
join(dirname(xterm("package.json")), "LICENSE"),
|
|
284
|
+
join(assets, "xterm.LICENSE")
|
|
285
|
+
);
|
|
286
|
+
const fill = (template, values) => Object.entries(values).reduce(
|
|
287
|
+
(html2, [key, value]) => html2.split(`{{${key}}}`).join(value),
|
|
288
|
+
template
|
|
289
|
+
);
|
|
290
|
+
const html = fill(readFileSync(join(PLAYER, "index.html"), "utf8"), {
|
|
291
|
+
title: escapeHtml(title),
|
|
292
|
+
base: base ? `<base href="${escapeHtml(base)}" />` : "",
|
|
293
|
+
screens: screens.map((screen) => screenMarkup(title, screen)).join("\n")
|
|
294
|
+
});
|
|
295
|
+
const index = join(out, "index.html");
|
|
296
|
+
writeFileSync(index, html);
|
|
297
|
+
written.push(index);
|
|
298
|
+
const vercel = join(out, "vercel.json");
|
|
299
|
+
writeFileSync(vercel, JSON.stringify(VERCEL_CONFIG, null, 2) + "\n");
|
|
300
|
+
written.push(vercel);
|
|
301
|
+
return written;
|
|
302
|
+
};
|
|
303
|
+
var MOVIE_FORMATS = ["gif", "mp4"];
|
|
304
|
+
var DEFAULT_FPS = 15;
|
|
305
|
+
var DEFAULT_HOLD = 2;
|
|
306
|
+
var movieFrames = (times, {
|
|
307
|
+
fps = DEFAULT_FPS,
|
|
308
|
+
speed = 1,
|
|
309
|
+
maxDuration,
|
|
310
|
+
hold = DEFAULT_HOLD
|
|
311
|
+
} = {}) => {
|
|
312
|
+
if (!(fps > 0)) throw new Error(`fps must be positive, got ${fps}`);
|
|
313
|
+
if (!(speed > 0)) throw new Error(`speed must be positive, got ${speed}`);
|
|
314
|
+
if (maxDuration !== void 0 && !(maxDuration > 0))
|
|
315
|
+
throw new Error(`max duration must be positive, got ${maxDuration}`);
|
|
316
|
+
if (!(hold >= 0)) throw new Error(`hold must not be negative, got ${hold}`);
|
|
317
|
+
const last = times.at(-1) ?? 0;
|
|
318
|
+
const rate = maxDuration !== void 0 && last / speed > maxDuration ? last / maxDuration : speed;
|
|
319
|
+
const ticks = Math.ceil(last / rate * fps - 1e-9);
|
|
320
|
+
const frames = [];
|
|
321
|
+
let count = 0;
|
|
322
|
+
for (let tick = 0; tick <= ticks; tick++) {
|
|
323
|
+
const at = tick / fps * rate + 1e-9;
|
|
324
|
+
while (count < times.length && times[count] <= at) count++;
|
|
325
|
+
const previous = frames.at(-1);
|
|
326
|
+
if (previous && previous.count === count) previous.duration += 1 / fps;
|
|
327
|
+
else frames.push({ count, duration: 1 / fps });
|
|
328
|
+
}
|
|
329
|
+
frames.at(-1).count = times.length;
|
|
330
|
+
frames.at(-1).duration += hold;
|
|
331
|
+
return frames;
|
|
332
|
+
};
|
|
333
|
+
var launchBrowser = async () => {
|
|
334
|
+
let playwright;
|
|
335
|
+
try {
|
|
336
|
+
playwright = createRequire(import.meta.url)("playwright");
|
|
337
|
+
} catch {
|
|
338
|
+
throw new Error(
|
|
339
|
+
"--format gif and mp4 film the web player in a headless browser, and need Playwright:\n npm install playwright && npx playwright install chromium"
|
|
340
|
+
);
|
|
341
|
+
}
|
|
342
|
+
return playwright.chromium.launch();
|
|
343
|
+
};
|
|
344
|
+
var hasFfmpeg = () => spawnSync("ffmpeg", ["-version"], { stdio: "ignore" }).status === 0;
|
|
345
|
+
var CONTENT_TYPES = {
|
|
346
|
+
".html": "text/html; charset=utf-8",
|
|
347
|
+
".js": "text/javascript",
|
|
348
|
+
".mjs": "text/javascript",
|
|
349
|
+
".css": "text/css",
|
|
350
|
+
".cast": "application/x-asciicast; charset=utf-8",
|
|
351
|
+
".woff2": "font/woff2"
|
|
352
|
+
};
|
|
353
|
+
var ORIGIN = "http://cli-shot.invalid/";
|
|
354
|
+
var MARGIN = 24;
|
|
355
|
+
var ffmpegArgs = (list, output, format, { fps = DEFAULT_FPS, loop = 0 }) => {
|
|
356
|
+
const input = [
|
|
357
|
+
"-hide_banner",
|
|
358
|
+
"-loglevel",
|
|
359
|
+
"error",
|
|
360
|
+
"-y",
|
|
361
|
+
"-f",
|
|
362
|
+
"concat",
|
|
363
|
+
"-safe",
|
|
364
|
+
"0",
|
|
365
|
+
"-i",
|
|
366
|
+
list
|
|
367
|
+
];
|
|
368
|
+
if (format === "gif") {
|
|
369
|
+
return [
|
|
370
|
+
...input,
|
|
371
|
+
"-filter_complex",
|
|
372
|
+
"split[a][b];[a]palettegen=max_colors=128:stats_mode=full[p];[b][p]paletteuse=dither=none:diff_mode=rectangle",
|
|
373
|
+
"-fps_mode",
|
|
374
|
+
"vfr",
|
|
375
|
+
// ffmpeg counts repeats after the first play: -1 plays once, 0 forever.
|
|
376
|
+
"-loop",
|
|
377
|
+
String(loop === 0 ? 0 : loop === 1 ? -1 : loop - 1),
|
|
378
|
+
output
|
|
379
|
+
];
|
|
380
|
+
}
|
|
381
|
+
return [
|
|
382
|
+
...input,
|
|
383
|
+
"-vf",
|
|
384
|
+
`pad=ceil(iw/2)*2:ceil(ih/2)*2:color=black,fps=${fps}`,
|
|
385
|
+
"-c:v",
|
|
386
|
+
"libx264",
|
|
387
|
+
"-pix_fmt",
|
|
388
|
+
"yuv420p",
|
|
389
|
+
"-crf",
|
|
390
|
+
"20",
|
|
391
|
+
"-tune",
|
|
392
|
+
"stillimage",
|
|
393
|
+
"-movflags",
|
|
394
|
+
"+faststart",
|
|
395
|
+
output
|
|
396
|
+
];
|
|
397
|
+
};
|
|
398
|
+
var toMovie = async ({
|
|
399
|
+
cast,
|
|
400
|
+
screen,
|
|
401
|
+
title = "cli-shot",
|
|
402
|
+
output,
|
|
403
|
+
format,
|
|
404
|
+
browser,
|
|
405
|
+
...options
|
|
406
|
+
}) => {
|
|
407
|
+
if (!hasFfmpeg()) {
|
|
408
|
+
throw new Error(
|
|
409
|
+
`--format ${format} encodes with ffmpeg, which is not on PATH. Install it (brew install ffmpeg, apt install ffmpeg) and run again.`
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
const scale = options.scale ?? 1;
|
|
413
|
+
if (!(scale > 0)) throw new Error(`scale must be positive, got ${scale}`);
|
|
414
|
+
const work = mkdtempSync(join(tmpdir(), "cli-shot-movie-"));
|
|
415
|
+
const owned = browser ? void 0 : await launchBrowser();
|
|
416
|
+
const page = await (browser ?? owned).newPage({
|
|
417
|
+
viewport: { width: 2400, height: 1600 },
|
|
418
|
+
deviceScaleFactor: scale
|
|
419
|
+
});
|
|
420
|
+
try {
|
|
421
|
+
const site = join(work, "site");
|
|
422
|
+
mkdirSync(site);
|
|
423
|
+
writeFileSync(join(site, `${screen}.cast`), cast);
|
|
424
|
+
buildPlayer({ out: site, screens: [screen], title });
|
|
425
|
+
await page.route(`${ORIGIN}**`, (route) => {
|
|
426
|
+
const path = decodeURIComponent(new URL(route.request().url()).pathname);
|
|
427
|
+
const file = join(site, path.endsWith("/") ? `${path}index.html` : path);
|
|
428
|
+
const inside = relative(site, file);
|
|
429
|
+
if (inside.startsWith("..") || inside.startsWith(sep))
|
|
430
|
+
return route.abort();
|
|
431
|
+
return route.fulfill({
|
|
432
|
+
path: file,
|
|
433
|
+
contentType: CONTENT_TYPES[extname(file)] ?? "application/octet-stream"
|
|
434
|
+
});
|
|
435
|
+
});
|
|
436
|
+
await page.goto(`${ORIGIN}?capture&theme=light`);
|
|
437
|
+
await page.waitForSelector('.window[data-capture="ready"]');
|
|
438
|
+
const times = await page.evaluate(
|
|
439
|
+
() => window.cliShotCapture.times,
|
|
440
|
+
void 0
|
|
441
|
+
);
|
|
442
|
+
const box = await page.locator(".window").boundingBox();
|
|
443
|
+
if (!box) throw new Error(`the player drew no window for ${screen}`);
|
|
444
|
+
const clip = {
|
|
445
|
+
x: Math.max(0, Math.floor(box.x - MARGIN)),
|
|
446
|
+
y: Math.max(0, Math.floor(box.y - MARGIN)),
|
|
447
|
+
width: Math.ceil(box.width + MARGIN * 2),
|
|
448
|
+
height: Math.ceil(box.height + MARGIN * 2)
|
|
449
|
+
};
|
|
450
|
+
const frames = movieFrames(times, options);
|
|
451
|
+
const list = [];
|
|
452
|
+
for (const [index, frame] of frames.entries()) {
|
|
453
|
+
await page.evaluate(
|
|
454
|
+
(count) => window.cliShotCapture.until(count),
|
|
455
|
+
frame.count
|
|
456
|
+
);
|
|
457
|
+
const still = join(work, `frame-${String(index).padStart(5, "0")}.png`);
|
|
458
|
+
await page.screenshot({ path: still, clip });
|
|
459
|
+
list.push(`file '${still}'`, `duration ${frame.duration.toFixed(6)}`);
|
|
460
|
+
}
|
|
461
|
+
list.push(list.at(-2));
|
|
462
|
+
const listFile = join(work, "frames.txt");
|
|
463
|
+
writeFileSync(listFile, list.join("\n") + "\n");
|
|
464
|
+
mkdirSync(dirname(output), { recursive: true });
|
|
465
|
+
const args = ffmpegArgs(listFile, output, format, options);
|
|
466
|
+
const result = spawnSync("ffmpeg", args, { encoding: "utf8" });
|
|
467
|
+
if (result.status !== 0) {
|
|
468
|
+
throw new Error(
|
|
469
|
+
`ffmpeg failed for ${output}
|
|
470
|
+
command: ffmpeg ${args.join(" ")}
|
|
471
|
+
said: ${(result.stderr || String(result.error ?? "")).trim().replace(/\s+/g, " ")}`
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
return output;
|
|
475
|
+
} finally {
|
|
476
|
+
await page.close();
|
|
477
|
+
await owned?.close();
|
|
478
|
+
rmSync(work, { recursive: true, force: true });
|
|
479
|
+
}
|
|
480
|
+
};
|
|
481
|
+
|
|
482
|
+
// src/index.ts
|
|
483
|
+
var FORMATS = ["png", "cast", "web", ...MOVIE_FORMATS];
|
|
484
|
+
var drivenScreen = (args) => {
|
|
485
|
+
const at = args.indexOf("--screen");
|
|
486
|
+
return at === -1 ? void 0 : args[at + 1];
|
|
487
|
+
};
|
|
488
|
+
var screenArgs = (args, screen, mock) => [
|
|
489
|
+
...args,
|
|
490
|
+
...mock && !args.includes("--mock") ? ["--mock"] : [],
|
|
491
|
+
...drivenScreen(args) === void 0 ? ["--screen", screen] : []
|
|
492
|
+
];
|
|
493
|
+
var shootFormats = async (screen, {
|
|
494
|
+
command,
|
|
495
|
+
args = [],
|
|
496
|
+
out,
|
|
497
|
+
mock = true,
|
|
498
|
+
formats = ["png"],
|
|
499
|
+
title = basename(command),
|
|
500
|
+
browser,
|
|
501
|
+
...rest
|
|
502
|
+
}) => {
|
|
503
|
+
const events = [];
|
|
504
|
+
const movies = MOVIE_FORMATS.filter((format) => formats.includes(format));
|
|
505
|
+
const keepCast = formats.includes("cast") || formats.includes("web");
|
|
506
|
+
const recording = keepCast || movies.length > 0;
|
|
507
|
+
const startedAt = Date.now() / 1e3;
|
|
508
|
+
const ansi = await capture(command, screenArgs(args, screen, mock), {
|
|
509
|
+
...rest,
|
|
510
|
+
onOutput: recording ? (data, elapsed) => {
|
|
511
|
+
events.push([elapsed / 1e3, "o", data]);
|
|
512
|
+
rest.onOutput?.(data, elapsed);
|
|
513
|
+
} : rest.onOutput
|
|
514
|
+
});
|
|
515
|
+
const written = [];
|
|
516
|
+
if (formats.includes("png")) {
|
|
517
|
+
written.push(toImage(ansi, join(out, `${screen}.png`), rest));
|
|
518
|
+
}
|
|
519
|
+
if (!recording) return written;
|
|
520
|
+
const cast = toCast(
|
|
521
|
+
{
|
|
522
|
+
width: rest.cols ?? DEFAULT_COLS,
|
|
523
|
+
height: rest.rows ?? DEFAULT_ROWS,
|
|
524
|
+
timestamp: startedAt,
|
|
525
|
+
title: screen,
|
|
526
|
+
env: { TERM: "xterm-256color" }
|
|
527
|
+
},
|
|
528
|
+
events
|
|
529
|
+
);
|
|
530
|
+
if (keepCast) {
|
|
531
|
+
const path = join(out, `${screen}.cast`);
|
|
532
|
+
mkdirSync(out, { recursive: true });
|
|
533
|
+
writeFileSync(path, cast);
|
|
534
|
+
written.push(path);
|
|
535
|
+
}
|
|
536
|
+
for (const format of movies) {
|
|
537
|
+
written.push(
|
|
538
|
+
await toMovie({
|
|
539
|
+
...rest,
|
|
540
|
+
cast,
|
|
541
|
+
screen,
|
|
542
|
+
title,
|
|
543
|
+
format,
|
|
544
|
+
browser,
|
|
545
|
+
output: join(out, `${screen}.${format}`)
|
|
546
|
+
})
|
|
547
|
+
);
|
|
548
|
+
}
|
|
549
|
+
return written;
|
|
550
|
+
};
|
|
551
|
+
var shootScreen = async (screen, options) => (await shootFormats(screen, { ...options, formats: ["png"] }))[0];
|
|
552
|
+
var defaultConcurrency = () => Math.max(2, Math.min(8, cpus().length));
|
|
553
|
+
var pool = async (items, limit, run) => {
|
|
554
|
+
const results = new Array(items.length);
|
|
555
|
+
let next = 0;
|
|
556
|
+
const worker = async () => {
|
|
557
|
+
for (let i = next++; i < items.length; i = next++) {
|
|
558
|
+
results[i] = await run(items[i], i);
|
|
559
|
+
}
|
|
560
|
+
};
|
|
561
|
+
await Promise.all(
|
|
562
|
+
Array.from({ length: Math.min(limit, items.length) }, worker)
|
|
563
|
+
);
|
|
564
|
+
return results;
|
|
565
|
+
};
|
|
566
|
+
var shootAll = async (options) => {
|
|
567
|
+
const pinned = drivenScreen(options.args ?? []);
|
|
568
|
+
const screens = pinned ? [pinned] : listScreens(options.command, options.args ?? []);
|
|
569
|
+
return shootScreens(screens, options);
|
|
570
|
+
};
|
|
571
|
+
var shootScreens = async (screens, options) => {
|
|
572
|
+
const filming = options.formats?.some(
|
|
573
|
+
(format) => MOVIE_FORMATS.includes(format)
|
|
574
|
+
);
|
|
575
|
+
const browser = options.browser ?? (filming ? await launchBrowser() : void 0);
|
|
576
|
+
let written;
|
|
577
|
+
try {
|
|
578
|
+
written = (await pool(
|
|
579
|
+
screens,
|
|
580
|
+
options.concurrency ?? defaultConcurrency(),
|
|
581
|
+
(screen) => shootFormats(screen, { ...options, browser })
|
|
582
|
+
)).flat();
|
|
583
|
+
} finally {
|
|
584
|
+
if (browser !== options.browser) await browser?.close();
|
|
585
|
+
}
|
|
586
|
+
if (options.formats?.includes("web")) {
|
|
587
|
+
written.push(
|
|
588
|
+
...buildPlayer({
|
|
589
|
+
out: options.out,
|
|
590
|
+
screens,
|
|
591
|
+
title: options.title ?? basename(options.command),
|
|
592
|
+
base: options.base
|
|
593
|
+
})
|
|
594
|
+
);
|
|
595
|
+
}
|
|
596
|
+
return written;
|
|
597
|
+
};
|
|
598
|
+
|
|
599
|
+
export { DEFAULT_FONT, DEFAULT_FPS, DEFAULT_HOLD, FORMATS, MOVIE_FORMATS, VERCEL_CONFIG, buildPlayer, capture, castEvent, castHeader, drivenScreen, hasFfmpeg, launchBrowser, listScreens, movieFrames, parseCast, shootAll, shootFormats, shootScreen, shootScreens, toCast, toImage, toMovie };
|