@openvidstudio/capture 0.0.0-stage → 0.1.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.
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Records a real command run as timed text rather than as pixels.
3
+ *
4
+ * Two backends, same cast format:
5
+ *
6
+ * **pty** allocates a real pseudo-terminal through the optional `node-pty` module. The
7
+ * program under capture sees a terminal, so it keeps its colour, its progress bars, and
8
+ * its cursor addressing, which is what makes a recording look like the thing the user
9
+ * actually ran. A pty merges stdout and stderr onto one stream by construction, so every
10
+ * event in a pty cast is tagged "o": that is the pty's behaviour, not a loss of fidelity
11
+ * this module introduced.
12
+ *
13
+ * **pipe** is the fallback, and the only mode available when `node-pty` is not installed.
14
+ * It keeps stdout and stderr separate and needs no native build, at the cost that many
15
+ * programs detect no terminal is attached and suppress colour entirely, and a full-screen
16
+ * TUI replays only as far as the replay component understands its control sequences.
17
+ *
18
+ * `node-pty` is deliberately an optional peer dependency rather than a dependency: it
19
+ * compiles a native addon, and requiring one from everybody to record `npm test` would be
20
+ * a bad trade. The mode actually used is always reported back, so a dull, colourless
21
+ * recording has a visible cause rather than being a mystery.
22
+ */
23
+ export type TerminalMode = "pty" | "pipe";
24
+ export interface TerminalStep {
25
+ type: "type" | "wait";
26
+ text?: string;
27
+ ms?: number;
28
+ }
29
+ export type TerminalEvent = [number, "o" | "e", string];
30
+ export interface TerminalCast {
31
+ version: 1;
32
+ command: string;
33
+ cols: number;
34
+ rows: number;
35
+ durationMs: number;
36
+ exitCode: number | null;
37
+ /** Which backend produced this cast. Absent in casts recorded before pty support existed. */
38
+ mode?: TerminalMode;
39
+ events: TerminalEvent[];
40
+ }
41
+ export interface RecordTerminalOptions {
42
+ command: string;
43
+ args?: string[];
44
+ cwd: string;
45
+ script?: TerminalStep[];
46
+ cols?: number;
47
+ rows?: number;
48
+ timeoutMs?: number;
49
+ /** "auto" uses a pty when node-pty is installed. "pipe" never does. "pty" fails if it is not. */
50
+ mode?: "auto" | "pty" | "pipe";
51
+ /**
52
+ * Stop recording after this many characters of output, and say so in the cast.
53
+ *
54
+ * The memory caps below are a safety net against a runaway process; this is a different
55
+ * thing, and a real one. A command whose output is genuinely enormous produces a cast
56
+ * nothing can replay: fetching one real installer for a demo returned 169,000 characters,
57
+ * which at any watchable typing speed is over an hour of screen time for a seven second
58
+ * beat. The first screenful is what a demo shows anyway, so bound it deliberately and
59
+ * mark the cast truncated rather than recording an unusable one or trimming it by hand
60
+ * afterwards, which would make the video stop matching the recording.
61
+ */
62
+ maxOutputChars?: number;
63
+ }
64
+ export interface RecordTerminalResult {
65
+ cast: TerminalCast;
66
+ truncated: boolean;
67
+ mode: TerminalMode;
68
+ }
69
+ /** A runaway process can emit output forever; cap what is retained rather than exhausting memory. */
70
+ export declare const MAX_EVENTS = 20000;
71
+ export declare const MAX_TOTAL_BYTES: number;
72
+ interface PtyProcess {
73
+ onData(cb: (data: string) => void): void;
74
+ onExit(cb: (e: {
75
+ exitCode: number;
76
+ signal?: number;
77
+ }) => void): void;
78
+ write(data: string): void;
79
+ kill(signal?: string): void;
80
+ }
81
+ interface PtyModule {
82
+ spawn(file: string, args: string[], opts: {
83
+ name: string;
84
+ cols: number;
85
+ rows: number;
86
+ cwd: string;
87
+ env: NodeJS.ProcessEnv;
88
+ }): PtyProcess;
89
+ }
90
+ /**
91
+ * Loads node-pty if it is present, and returns null rather than throwing if it is not.
92
+ *
93
+ * A native module can also be present but unloadable, typically after a Node version
94
+ * change rebuilt nothing, which throws a different error than "cannot find module". Both
95
+ * cases mean the same thing here: no pty is available, fall back.
96
+ */
97
+ export declare function loadPty(): PtyModule | null;
98
+ export declare function recordTerminal(opts: RecordTerminalOptions): Promise<RecordTerminalResult>;
99
+ export {};
@@ -0,0 +1,190 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_TOTAL_BYTES = exports.MAX_EVENTS = void 0;
4
+ exports.loadPty = loadPty;
5
+ exports.recordTerminal = recordTerminal;
6
+ const node_child_process_1 = require("node:child_process");
7
+ /** A runaway process can emit output forever; cap what is retained rather than exhausting memory. */
8
+ exports.MAX_EVENTS = 20000;
9
+ exports.MAX_TOTAL_BYTES = 4 * 1024 * 1024;
10
+ const DEFAULT_COLS = 100;
11
+ const DEFAULT_ROWS = 30;
12
+ const DEFAULT_TIMEOUT_MS = 120000;
13
+ /**
14
+ * Loads node-pty if it is present, and returns null rather than throwing if it is not.
15
+ *
16
+ * A native module can also be present but unloadable, typically after a Node version
17
+ * change rebuilt nothing, which throws a different error than "cannot find module". Both
18
+ * cases mean the same thing here: no pty is available, fall back.
19
+ */
20
+ function loadPty() {
21
+ try {
22
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
23
+ return require("node-pty");
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ /** Collects timestamped output chunks, enforcing the retention caps once for both backends. */
30
+ class CastRecorder {
31
+ constructor(maxChars) {
32
+ this.maxChars = maxChars;
33
+ this.events = [];
34
+ this.truncated = false;
35
+ this.totalBytes = 0;
36
+ this.totalChars = 0;
37
+ this.started = Date.now();
38
+ }
39
+ record(stream, text) {
40
+ if (this.truncated)
41
+ return;
42
+ this.totalBytes += Buffer.byteLength(text);
43
+ // A deliberate character bound cuts mid-chunk, because a chunk can itself be the whole
44
+ // file. The memory caps below drop the chunk instead, since by then the goal is only to
45
+ // stop growing.
46
+ if (this.maxChars !== undefined && this.totalChars + text.length > this.maxChars) {
47
+ const room = Math.max(0, this.maxChars - this.totalChars);
48
+ if (room > 0)
49
+ this.events.push([this.elapsed(), stream, text.slice(0, room)]);
50
+ this.totalChars = this.maxChars;
51
+ this.truncated = true;
52
+ this.events.push([this.elapsed(), "e", "\n[openvidstudio: output truncated]\n"]);
53
+ return;
54
+ }
55
+ if (this.events.length >= exports.MAX_EVENTS || this.totalBytes > exports.MAX_TOTAL_BYTES) {
56
+ this.truncated = true;
57
+ this.events.push([this.elapsed(), "e", "\n[openvidstudio: output truncated]\n"]);
58
+ return;
59
+ }
60
+ this.totalChars += text.length;
61
+ this.events.push([this.elapsed(), stream, text]);
62
+ }
63
+ elapsed() {
64
+ return Date.now() - this.started;
65
+ }
66
+ }
67
+ function childEnv(cols, rows) {
68
+ return { ...process.env, COLUMNS: String(cols), LINES: String(rows), TERM: "xterm-256color" };
69
+ }
70
+ /**
71
+ * Replays scripted input against the child's stdin. Typing is sent as one write per step
72
+ * rather than per character: the replay component controls on-screen typing cadence, so
73
+ * simulating keystroke timing at the process level would double it.
74
+ */
75
+ async function replayScript(steps, write, done, isSettled) {
76
+ for (const step of steps ?? []) {
77
+ if (isSettled())
78
+ return;
79
+ if (step.type === "wait") {
80
+ await new Promise((r) => setTimeout(r, step.ms ?? 0));
81
+ }
82
+ else if (step.type === "type") {
83
+ write(step.text ?? "");
84
+ }
85
+ }
86
+ done();
87
+ }
88
+ async function recordWithPty(pty, opts, cols, rows, timeoutMs) {
89
+ const recorder = new CastRecorder(opts.maxOutputChars);
90
+ const child = pty.spawn(opts.command, opts.args ?? [], {
91
+ name: "xterm-256color",
92
+ cols,
93
+ rows,
94
+ cwd: opts.cwd,
95
+ env: childEnv(cols, rows),
96
+ });
97
+ const exitCode = await new Promise((resolve) => {
98
+ let settled = false;
99
+ const finish = (code) => {
100
+ if (settled)
101
+ return;
102
+ settled = true;
103
+ clearTimeout(timer);
104
+ resolve(code);
105
+ };
106
+ const timer = setTimeout(() => {
107
+ recorder.record("e", `\n[openvidstudio: timed out after ${timeoutMs / 1000}s]\n`);
108
+ child.kill();
109
+ }, timeoutMs);
110
+ // A pty is one stream by construction: the program's stderr is written to the same
111
+ // terminal its stdout is, which is exactly why colour survives.
112
+ child.onData((data) => recorder.record("o", data));
113
+ child.onExit(({ exitCode: code }) => finish(code));
114
+ void replayScript(opts.script, (text) => child.write(text), () => {
115
+ /* A pty has no stdin to close: EOF is sent by the script itself, as Ctrl-D. */
116
+ }, () => settled);
117
+ });
118
+ return { recorder, exitCode };
119
+ }
120
+ async function recordWithPipes(opts, cols, rows, timeoutMs) {
121
+ const recorder = new CastRecorder(opts.maxOutputChars);
122
+ // shell:false with an argv array, same discipline as every other spawn in this package:
123
+ // `command` and `args` come from a beats.json a human approved, but they are still not
124
+ // concatenated into a command line.
125
+ const child = (0, node_child_process_1.spawn)(opts.command, opts.args ?? [], {
126
+ cwd: opts.cwd,
127
+ shell: false,
128
+ env: childEnv(cols, rows),
129
+ });
130
+ const exitCode = await new Promise((resolve, reject) => {
131
+ let settled = false;
132
+ const finish = (code) => {
133
+ if (settled)
134
+ return;
135
+ settled = true;
136
+ clearTimeout(timer);
137
+ resolve(code);
138
+ };
139
+ const timer = setTimeout(() => {
140
+ recorder.record("e", `\n[openvidstudio: timed out after ${timeoutMs / 1000}s]\n`);
141
+ child.kill("SIGTERM");
142
+ setTimeout(() => child.kill("SIGKILL"), 3000).unref?.();
143
+ }, timeoutMs);
144
+ child.stdout?.on("data", (c) => recorder.record("o", c.toString("utf8")));
145
+ child.stderr?.on("data", (c) => recorder.record("e", c.toString("utf8")));
146
+ child.on("error", (err) => {
147
+ if (settled)
148
+ return;
149
+ settled = true;
150
+ clearTimeout(timer);
151
+ const msg = /ENOENT/.test(String(err))
152
+ ? `Command not found: "${opts.command}". Check it is installed and on PATH for this process.`
153
+ : String(err);
154
+ reject(new Error(msg));
155
+ });
156
+ child.on("close", (code) => finish(code));
157
+ void replayScript(opts.script, (text) => child.stdin?.write(text), () => child.stdin?.end(), () => settled);
158
+ });
159
+ return { recorder, exitCode };
160
+ }
161
+ async function recordTerminal(opts) {
162
+ const cols = opts.cols ?? DEFAULT_COLS;
163
+ const rows = opts.rows ?? DEFAULT_ROWS;
164
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
165
+ const requested = opts.mode ?? "auto";
166
+ const pty = requested === "pipe" ? null : loadPty();
167
+ if (requested === "pty" && !pty) {
168
+ throw new Error(`mode "pty" was requested but node-pty is not loadable. Install it in the project that runs this ` +
169
+ `capture ("npm install node-pty"), which compiles a native addon, or use mode "auto" to fall back to ` +
170
+ `piped stdout/stderr.`);
171
+ }
172
+ const mode = pty ? "pty" : "pipe";
173
+ const { recorder, exitCode } = pty
174
+ ? await recordWithPty(pty, opts, cols, rows, timeoutMs)
175
+ : await recordWithPipes(opts, cols, rows, timeoutMs);
176
+ return {
177
+ cast: {
178
+ version: 1,
179
+ command: [opts.command, ...(opts.args ?? [])].join(" "),
180
+ cols,
181
+ rows,
182
+ durationMs: recorder.elapsed(),
183
+ exitCode,
184
+ mode,
185
+ events: recorder.events,
186
+ },
187
+ truncated: recorder.truncated,
188
+ mode,
189
+ };
190
+ }
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@openvidstudio/capture",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Zoom-compensated browser capture plus desktop, mobile, and terminal recording backends. No Remotion, no React, no video pipeline.",
5
+ "license": "Apache-2.0",
6
+ "type": "commonjs",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "dependencies": {
13
+ "playwright": "^1.63.0",
14
+ "zod": "^4.6.4"
15
+ },
16
+ "devDependencies": {
17
+ "@types/node": "^26.5.1",
18
+ "typescript": "7.0.2"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/AnayDhawan/openvidstudio.git",
26
+ "directory": "packages/capture"
27
+ },
28
+ "homepage": "https://github.com/AnayDhawan/openvidstudio#readme",
29
+ "bugs": {
30
+ "url": "https://github.com/AnayDhawan/openvidstudio/issues"
31
+ },
32
+ "keywords": [
33
+ "playwright",
34
+ "screenshot",
35
+ "screen-recording",
36
+ "capture",
37
+ "ffmpeg",
38
+ "adb"
39
+ ],
40
+ "scripts": {
41
+ "build": "tsc",
42
+ "typecheck": "tsc --noEmit"
43
+ }
6
44
  }