cuetake 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.
package/src/cursor.js ADDED
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Cursor and click-effect state at a moment of a Take, derived from the Timeline.
3
+ * Pure functions shared by Node and the render page; CSS pixels and seconds throughout.
4
+ */
5
+
6
+ /** The pointer position at `t`, interpolated between samples; null before the first sample. */
7
+ export function pointerAt(pointer, t) {
8
+ if (!pointer.length || t < pointer[0][0]) return null;
9
+ let low = 0, high = pointer.length - 1;
10
+ while (low < high) { const mid = (low + high + 1) >> 1; if (pointer[mid][0] <= t) low = mid; else high = mid - 1; }
11
+ const [t0, x0, y0] = pointer[low], next = pointer[low + 1];
12
+ if (!next || next[0] === t0) return { x: x0, y: y0 };
13
+ const k = (t - t0) / (next[0] - t0);
14
+ return { x: x0 + (next[1] - x0) * k, y: y0 + (next[2] - y0) * k };
15
+ }
16
+
17
+ /** Presses that spark: clicks at their point, drags where they start. */
18
+ export function presses(events) {
19
+ return events.flatMap(event => event.type === 'click' ? [{ t: event.t, x: event.x, y: event.y }]
20
+ : event.type === 'drag' ? [{ t: event.t, ...event.from }] : []);
21
+ }
22
+
23
+ /** Sparks alive at `t`, each with its progress from 0 to 1. */
24
+ export function sparksAt(pressList, clickEffect, t) {
25
+ if (clickEffect.style === 'none') return [];
26
+ const life = clickEffect.duration / 1000;
27
+ return pressList.filter(p => t >= p.t && t < p.t + life).map(p => ({ x: p.x, y: p.y, progress: (t - p.t) / life }));
28
+ }
29
+
30
+ /** Arrow outline in its 28×36 design box; the hotspot is the tip at (2, 2). */
31
+ export const ARROW_PATH = 'M2 2 L2 27 L8.5 21 L14 33 L19 30.5 L13.5 19 L23 19 Z';
32
+
33
+ /** Cursor sprite geometry in CSS pixels: drawn size and the hotspot offset from its top-left. */
34
+ export function cursorGeometry(cursor) {
35
+ return cursor.style === 'arrow'
36
+ ? { width: cursor.size, height: cursor.size * 36 / 28, hotspot: { x: cursor.size * 2 / 28, y: cursor.size * 2 / 28 } }
37
+ : { width: cursor.size, height: cursor.size, hotspot: { x: cursor.size / 2, y: cursor.size / 2 } };
38
+ }
39
+
40
+ /** Draws one spark centered in a 2D context whose unit is one CSS pixel. */
41
+ export function drawSpark(ctx, x, y, progress, clickEffect, color) {
42
+ const eased = 1 - (1 - progress) ** 3;
43
+ const distance = 5 + eased * clickEffect.radius;
44
+ const length = clickEffect.length * (1 - eased);
45
+ ctx.globalAlpha = 1 - progress;
46
+ ctx.lineCap = 'round';
47
+ for (let i = 0; i < clickEffect.count; i++) {
48
+ const angle = 2 * Math.PI * i / clickEffect.count + Math.PI / 8;
49
+ ctx.beginPath();
50
+ ctx.moveTo(x + distance * Math.cos(angle), y + distance * Math.sin(angle));
51
+ ctx.lineTo(x + (distance + length) * Math.cos(angle), y + (distance + length) * Math.sin(angle));
52
+ // A dark edge under a cursor-colored core stays legible on light and dark pages.
53
+ ctx.strokeStyle = '#171717'; ctx.lineWidth = 4.5; ctx.stroke();
54
+ ctx.strokeStyle = color; ctx.lineWidth = 2.5; ctx.stroke();
55
+ }
56
+ ctx.globalAlpha = 1;
57
+ }
@@ -0,0 +1,54 @@
1
+ /** Timed, viewport-aligned interactions shared by all scenarios. */
2
+ export function createDirector(page, startedAt, fps, focusTargets, wideWindows) {
3
+ let cursor = { x: 0, y: 0 };
4
+ const wait = ms => page.waitForTimeout(Math.max(0, ms));
5
+ const time = () => (Date.now() - startedAt) / 1000;
6
+ async function move(x, y, duration = 500) {
7
+ const from = { ...cursor };
8
+ const start = Date.now();
9
+ const frames = Math.max(1, Math.round(duration * fps / 1000));
10
+ for (let i = 1; i <= frames; i++) {
11
+ const t = i / frames;
12
+ const k = t * t * (3 - 2 * t);
13
+ await page.mouse.move(from.x + (x - from.x) * k, from.y + (y - from.y) * k);
14
+ await wait(start + i * duration / frames - Date.now());
15
+ }
16
+ cursor = { x, y };
17
+ }
18
+ // Clicks, typing and drags are recorded by the in-page probe; only deliberate camera choices live here.
19
+ const focus = (box, t = time()) => focusTargets.push({ t, box });
20
+ /** Options may be a bare number for the action's main timing; `focus: false` keeps the camera wide. */
21
+ const options = (value, key) => typeof value === 'number' ? { [key]: value } : value ?? {};
22
+ async function act({ focus: follow = true }, action) {
23
+ const start = time();
24
+ try { return await action(); }
25
+ finally { if (follow === false) wideWindows.push({ start, end: time() }); }
26
+ }
27
+ function click(locator, opts) {
28
+ const { duration = 450, ...rest } = options(opts, 'duration');
29
+ return act(rest, async () => {
30
+ const target = typeof locator === 'string' ? page.locator(locator) : locator;
31
+ const box = await target.boundingBox();
32
+ if (!box) throw new Error('Click target has no visible bounding box');
33
+ await move(box.x + box.width / 2, box.y + box.height / 2, duration);
34
+ await target.click();
35
+ });
36
+ }
37
+ function type(locator, text, opts) {
38
+ const { msPerChar = 70, ...rest } = options(opts, 'msPerChar');
39
+ return act(rest, async () => {
40
+ await click(locator, rest);
41
+ await page.keyboard.type(text, { delay: msPerChar });
42
+ });
43
+ }
44
+ function drag(from, to, opts) {
45
+ const { duration = 1200, ...rest } = options(opts, 'duration');
46
+ return act(rest, async () => {
47
+ await move(from.x, from.y, 400);
48
+ await page.mouse.down();
49
+ try { await move(to.x, to.y, duration); }
50
+ finally { await page.mouse.up(); }
51
+ });
52
+ }
53
+ return { page, wait, time, at: seconds => wait(seconds * 1000 - (Date.now() - startedAt)), move, click, type, drag, focus };
54
+ }
package/src/edit.js ADDED
@@ -0,0 +1,78 @@
1
+ import { z } from 'zod';
2
+ import { SHORT_SIDE, CHROME_HEIGHT, BACKGROUNDS } from './stage.js';
3
+
4
+ /** An Edit holds every choice Render makes; a Scenario's config only seeds the first one. */
5
+ export const evenSize = z.number().int().min(240).max(7680).refine(n => n % 2 === 0, 'Must be an even pixel count');
6
+ const box = z.object({ x: z.number(), y: z.number(), width: z.number().nonnegative(), height: z.number().nonnegative() });
7
+
8
+ // size names the Final's short side; quality is the H.264 quantizer (lower is sharper and larger).
9
+ const outputFields = z.object({
10
+ size: z.union([z.enum(Object.keys(SHORT_SIDE)), evenSize]).default('2160p'),
11
+ aspect: z.enum(['16:9', '1:1', '9:16']).default('16:9'),
12
+ quality: z.number().int().min(10).max(40).default(22),
13
+ });
14
+
15
+ /** Times are seconds except clickEffect.duration, which is milliseconds; geometry is CSS pixels. */
16
+ export const editFields = {
17
+ cursor: z.object({ style: z.enum(['arrow', 'dot']).default('arrow'), size: z.number().min(12).max(64).default(24), color: z.string().regex(/^#[a-fA-F0-9]{6}$/).default('#ffffff') }).default({}),
18
+ clickEffect: z.object({ style: z.enum(['spark', 'none']).default('spark'), radius: z.number().min(8).max(80).default(32), length: z.number().min(4).max(40).default(16), count: z.number().int().min(4).max(16).default(8), duration: z.number().min(150).max(1000).default(420) }).default({}),
19
+ output: outputFields.default({}),
20
+ // The page in a window on a background; `false` lets the page fill the Final. Radius is in 1080p pixels.
21
+ frame: z.union([z.literal(false), z.object({
22
+ window: z.enum(Object.keys(CHROME_HEIGHT)).default('browser'),
23
+ background: z.enum([...Object.keys(BACKGROUNDS), 'auto', 'blur']).default('aurora'),
24
+ padding: z.number().min(0).max(0.3).default(0.08),
25
+ radius: z.number().min(0).max(48).default(12),
26
+ shadow: z.boolean().default(true),
27
+ url: z.string().max(200).optional(),
28
+ })]).default({}),
29
+ // See camera.js. Each target is framed with `padding` CSS px around it, zooming at most `maxZoom`;
30
+ // fits below `minZoom` stay wide. The camera arrives `lead` before an action, holds `hold` after the
31
+ // last one in a segment, settles in about `response`, and returns wide `endWide` before the end.
32
+ camera: z.object({
33
+ maxZoom: z.number().min(1).max(4).default(2), minZoom: z.number().min(1).max(4).default(1.2), padding: z.number().min(0).max(400).default(48),
34
+ lead: z.number().min(0).max(3).default(0.6), hold: z.number().min(0).max(30).default(1.5), chainGap: z.number().min(0).max(30).default(2),
35
+ response: z.number().min(0.1).max(3).default(0.6), follow: z.boolean().default(true), endWide: z.number().min(0).max(10).default(1.5),
36
+ }).default({}),
37
+ };
38
+
39
+ /** A camera target is a CSS-pixel box the camera reaches at `t` seconds and holds at least until `until`, optionally at a fixed `zoom`. */
40
+ const target = z.object({ t: z.number().nonnegative(), box, until: z.number().nonnegative().optional(), zoom: z.number().min(1).max(4).optional() });
41
+
42
+ export const editSchema = z.object({
43
+ schemaVersion: z.literal(2),
44
+ ...editFields,
45
+ camera: editFields.camera.removeDefault().extend({ targets: z.array(target).default([]) }).default({}),
46
+ // The Final's frame rate; a new Take takes it from the Scenario's capture rate.
47
+ output: outputFields.extend({ fps: z.union([z.literal(30), z.literal(60)]).default(60) }).default({}),
48
+ });
49
+
50
+ /**
51
+ * Camera targets: observed clicks, typing and drags, except those inside a `wide` window ({ start, end }
52
+ * seconds) from an action with `focus: false`. Like a manual zoom in Screen Studio, an explicit focus
53
+ * target replaces only the automatic targets inside its own span (from `lead` before it to `hold` after).
54
+ */
55
+ export function cameraTargets(timeline, focus, wide = [], { lead, hold } = editFields.camera.parse({})) {
56
+ const spans = focus.map(f => ({ start: f.t - lead, end: (f.until ?? f.t) + hold }));
57
+ const inside = (t, windows) => windows.some(w => t >= w.start && t <= w.end);
58
+ const automatic = timeline.events.filter(event => !inside(event.t, wide) && !inside(event.t, spans)).flatMap(event => {
59
+ if (event.type === 'click' && event.box) return [{ t: event.t, box: event.box }];
60
+ if (event.type === 'type' && event.box) return [{ t: event.t, box: event.box, until: event.end }];
61
+ if (event.type === 'drag') {
62
+ const x = Math.min(event.from.x, event.to.x), y = Math.min(event.from.y, event.to.y);
63
+ return [{ t: event.t, box: { x, y, width: Math.abs(event.to.x - event.from.x), height: Math.abs(event.to.y - event.from.y) }, until: event.end }];
64
+ }
65
+ return [];
66
+ });
67
+ return [...automatic, ...focus].sort((a, b) => a.t - b.t);
68
+ }
69
+
70
+ export function createEdit(config, timeline, focus, wide = []) {
71
+ return editSchema.parse({
72
+ schemaVersion: 2,
73
+ cursor: config.cursor, clickEffect: config.clickEffect, output: { ...config.output, fps: config.capture.fps },
74
+ // The browser chrome shows the Scenario's host unless the config names something else.
75
+ frame: config.frame && { url: new URL(config.url).host, ...config.frame },
76
+ camera: { ...config.camera, targets: cameraTargets(timeline, focus, wide, config.camera) },
77
+ });
78
+ }
@@ -0,0 +1,36 @@
1
+ import fs from 'node:fs/promises';
2
+ import { spawn } from 'node:child_process';
3
+ import { createRequire } from 'node:module';
4
+ import { dirname, join } from 'node:path';
5
+ import { chromium } from 'playwright';
6
+
7
+ /** Checks what CueTake needs; installs nothing. Each failed check names the exact fix. */
8
+ export async function doctor() {
9
+ const checks = [];
10
+ const [major, minor] = process.versions.node.split('.').map(Number);
11
+ checks.push(major > 20 || (major === 20 && minor >= 10)
12
+ ? { name: 'node', ok: true, version: process.versions.node }
13
+ : { name: 'node', ok: false, version: process.versions.node, fix: 'Install Node 20.10 or newer.' });
14
+ const browserPath = chromium.executablePath();
15
+ try { await fs.access(browserPath); checks.push({ name: 'chromium', ok: true, path: browserPath }); }
16
+ catch { checks.push({ name: 'chromium', ok: false, fix: 'cuetake install-browser (downloads about 150 MB; ask the user first)' }); }
17
+ const platform = process.platform === 'darwin'
18
+ ? { name: 'platform', ok: true, value: 'macOS' }
19
+ : { name: 'platform', ok: true, value: process.platform, note: 'Only macOS is verified; capture and Render may behave differently here.' };
20
+ checks.push(platform);
21
+ return { ok: checks.every(c => c.ok), checks };
22
+ }
23
+
24
+ /**
25
+ * Downloads the Chromium build that CueTake's own Playwright version drives. Running
26
+ * `npx playwright install` instead may resolve a newer Playwright and fetch a build CueTake never uses.
27
+ */
28
+ export function installBrowser() {
29
+ const cli = join(dirname(createRequire(import.meta.url).resolve('playwright/package.json')), 'cli.js');
30
+ return new Promise((resolve, reject) => {
31
+ // Progress goes to stderr so stdout stays the JSON result.
32
+ const child = spawn(process.execPath, [cli, 'install', 'chromium', '--no-shell'], { stdio: ['ignore', 2, 2] });
33
+ child.on('error', reject);
34
+ child.on('close', code => code === 0 ? resolve({ installed: true, path: chromium.executablePath() }) : reject(new Error(`Browser install exited with ${code}`)));
35
+ });
36
+ }
@@ -0,0 +1,122 @@
1
+ import fs from 'node:fs/promises';
2
+ import { join, resolve } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { doctor } from './environment.js';
5
+ import { z } from 'zod';
6
+ import { startRecording, getRecordingPage, beginCapture, stopRecording, cleanup } from './recorder.js';
7
+ import { renderFinal, inspectFinal } from './render.js';
8
+ import { outputSize } from './stage.js';
9
+ import { resolveAuthProfile } from './auth.js';
10
+ import { createDirector } from './director.js';
11
+ import { collectTimeline } from './probe.js';
12
+ import { editFields, editSchema, createEdit, evenSize } from './edit.js';
13
+ import pkg from '../package.json' with { type: 'json' };
14
+
15
+ const SCHEMA_VERSION = 2;
16
+ /** Scenario config: capture settings plus the defaults that seed each Take's Edit. */
17
+ export const scenarioSchema = z.object({
18
+ name: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
19
+ url: z.string().url().refine(s => /^https?:/.test(s), 'Capture requires HTTP(S)'),
20
+ viewport: z.object({ width: evenSize, height: evenSize }).default({ width: 1440, height: 900 }),
21
+ capture: z.object({ fps: z.union([z.literal(30), z.literal(60)]).default(60), resolutionScale: z.union([z.literal(1), z.literal(2)]).default(2) }).default({}),
22
+ ...editFields,
23
+ });
24
+ const writeJson = (path, data) => fs.writeFile(path, JSON.stringify(data, null, 2) + '\n');
25
+ const readJson = async path => JSON.parse(await fs.readFile(path, 'utf8'));
26
+
27
+ /** New take directories are exclusive: reruns never overwrite a previous take. */
28
+ export async function recordScenario(scenarioPath, outputDir, options = {}) {
29
+ const scenario = await import(pathToFileURL(resolve(scenarioPath)).href);
30
+ const config = scenarioSchema.parse(scenario.config);
31
+ if (typeof scenario.run !== 'function') throw new Error('Scenario must export run(director)');
32
+ const authState = options.authProfile ? await resolveAuthProfile(options.authProfile) : undefined;
33
+ const ready = await doctor();
34
+ if (!ready.ok) throw new Error(JSON.stringify(ready));
35
+ const dir = resolve(outputDir || join('recordings', config.name, new Date().toISOString().replace(/[:.]/g, '-')));
36
+ await fs.mkdir(resolve(dir, '..'), { recursive: true });
37
+ await fs.mkdir(dir); // EEXIST is intentional, including for empty existing folders.
38
+ let project = { schemaVersion: SCHEMA_VERSION, tool: 'CueTake', version: pkg.version, createdAt: new Date().toISOString(), status: 'recording', authenticated: Boolean(authState), config };
39
+ await writeJson(join(dir, 'project.json'), project);
40
+ await fs.copyFile(resolve(scenarioPath), join(dir, 'scenario.mjs'));
41
+ try {
42
+ const session = await startRecording(config.url, {
43
+ ...config.viewport, ...config.capture, outputDir: dir, deferCapture: true, storageState: authState, headed: options.headed,
44
+ });
45
+ const page = getRecordingPage(session.sessionId);
46
+ if (scenario.prepare) await scenario.prepare(page);
47
+ await page.evaluate(() => document.fonts.ready);
48
+ const capture = await beginCapture(session.sessionId);
49
+ const startedAtMs = Date.parse(capture.startedAt);
50
+ const focus = [], wide = [];
51
+ const director = createDirector(page, startedAtMs, config.capture.fps, focus, wide);
52
+ const evidence = await scenario.run(director);
53
+ await page.screenshot({ path: join(dir, 'poster.png') });
54
+ const observed = await collectTimeline(page, startedAtMs);
55
+ const stopped = await stopRecording(session.sessionId);
56
+ await fs.rename(stopped.webmPath, join(dir, 'source.webm'));
57
+ await fs.rename(stopped.webmPath.replace(/\.webm$/, '-capture.json'), join(dir, 'capture.json'));
58
+ const timeline = {
59
+ schemaVersion: SCHEMA_VERSION, viewport: config.viewport, scale: config.capture.resolutionScale, duration: stopped.durationSeconds,
60
+ pointer: observed.pointer, events: [...observed.events, ...focus.map(f => ({ type: 'focus', ...f }))].sort((a, b) => a.t - b.t),
61
+ };
62
+ await writeJson(join(dir, 'timeline.json'), timeline);
63
+ await writeJson(join(dir, 'edit.json'), createEdit(config, timeline, focus, wide));
64
+ project = { ...project, status: 'captured', duration: stopped.durationSeconds, evidence: evidence ?? null };
65
+ await writeJson(join(dir, 'project.json'), project);
66
+ } catch (error) {
67
+ await writeJson(join(dir, 'project.json'), { ...project, status: 'failed', error: error.message });
68
+ throw error;
69
+ } finally { await cleanup(); }
70
+ await renderTake(dir);
71
+ const verification = await verifyTake(dir);
72
+ return { directory: dir, final: join(dir, 'final.mp4'), verification };
73
+ }
74
+
75
+ /** Reads a Take's project.json, Timeline and Edit, refusing Takes from an older schema. */
76
+ async function loadTake(dir) {
77
+ const project = await readJson(join(dir, 'project.json'));
78
+ if (project.schemaVersion !== SCHEMA_VERSION) throw new Error(`${dir} was recorded by an older CueTake (schema ${project.schemaVersion ?? 1}); record it again`);
79
+ return { project, config: scenarioSchema.parse(project.config), timeline: await readJson(join(dir, 'timeline.json')), edit: editSchema.parse(await readJson(join(dir, 'edit.json'))) };
80
+ }
81
+
82
+ export async function renderTake(directory) {
83
+ const dir = resolve(directory);
84
+ const { project, config, timeline, edit } = await loadTake(dir);
85
+ // Render to a temporary output; preserve the last complete final if encoding fails.
86
+ const temporary = join(dir, 'final.pending.mp4');
87
+ try {
88
+ const render = await renderFinal({ sourcePath: join(dir, 'source.webm'), finalPath: temporary, timeline, edit });
89
+ await fs.rename(temporary, join(dir, 'final.mp4'));
90
+ await writeJson(join(dir, 'render.json'), render);
91
+ await fs.rm(join(dir, 'verification.json'), { force: true });
92
+ await writeJson(join(dir, 'project.json'), { ...project, status: 'rendered' });
93
+ } catch (error) { await fs.rm(temporary, { force: true }); throw error; }
94
+ return join(dir, 'final.mp4');
95
+ }
96
+
97
+ export function summarizeFrames(frames, duration) {
98
+ const intervals = frames.slice(1).map((f, i) => f.timeMs - frames[i].timeMs);
99
+ const sorted = intervals.toSorted((a, b) => a - b);
100
+ const seconds = Array.from({ length: Math.ceil(duration) }, (_, second) => ({ second, callbacks: frames.filter(f => f.timeMs >= second * 1000 && f.timeMs < (second + 1) * 1000).length }));
101
+ return { callbacks: frames.length, medianIntervalMs: sorted[Math.floor(sorted.length / 2)] ?? null, maxIntervalMs: sorted.at(-1) ?? null, perSecond: seconds, note: 'Source capture is variable frame rate. Static sections reduce cadence; callback counts are observations, not a guarantee of unique encoded frames. Final output uses constant frame rate without motion interpolation.' };
102
+ }
103
+
104
+ export async function verifyTake(directory) {
105
+ const dir = resolve(directory);
106
+ const { project, config, timeline, edit } = await loadTake(dir);
107
+ const media = await inspectFinal(join(dir, 'final.mp4'));
108
+ const { fps } = edit.output;
109
+ const expected = { ...outputSize(edit, timeline.viewport), fps, frames: Math.round(project.duration * fps) };
110
+ const problems = [
111
+ media.width !== expected.width || media.height !== expected.height ? `size ${media.width}×${media.height}, expected ${expected.width}×${expected.height}` : null,
112
+ Math.abs(media.fps - expected.fps) > 0.01 ? `${media.fps} fps, expected ${expected.fps}` : null,
113
+ media.packets !== expected.frames ? `${media.packets} frames, expected ${expected.frames}` : null,
114
+ media.decodedFrames !== media.packets ? `only ${media.decodedFrames} of ${media.packets} frames decoded` : null,
115
+ ].filter(Boolean);
116
+ if (problems.length) throw new Error(`Final failed verification: ${problems.join('; ')}`);
117
+ const capture = await readJson(join(dir, 'capture.json'));
118
+ const verification = { passed: true, checkedAt: new Date().toISOString(), media, source: { settings: capture.settings, ...summarizeFrames(capture.frames, capture.duration) }, fullDecode: 'passed' };
119
+ await writeJson(join(dir, 'verification.json'), verification);
120
+ await writeJson(join(dir, 'project.json'), { ...project, status: 'verified' });
121
+ return verification;
122
+ }
package/src/probe.js ADDED
@@ -0,0 +1,57 @@
1
+ /**
2
+ * In-page Timeline probe. It records input exactly as the page receives it, so
3
+ * director actions and raw Playwright input are captured alike. All positions
4
+ * are CSS pixels; times are epoch milliseconds until collectTimeline rebases them.
5
+ * Input inside cross-origin iframes never reaches this document and is not seen.
6
+ */
7
+ export async function installProbe(page) {
8
+ await page.evaluate(() => {
9
+ window.__cuetakeProbe?.dispose();
10
+ const abort = new AbortController();
11
+ const on = (type, fn) => document.addEventListener(type, fn, { capture: true, passive: true, signal: abort.signal });
12
+ const at = event => performance.timeOrigin + event.timeStamp;
13
+ const interactive = 'a,button,input,textarea,select,label,summary,[role],[tabindex],[contenteditable]';
14
+ const box = element => {
15
+ const target = element?.closest?.(interactive) || element;
16
+ const r = target?.getBoundingClientRect?.();
17
+ return r ? { x: r.x, y: r.y, width: r.width, height: r.height } : null;
18
+ };
19
+ const state = { pointer: [], downs: [], ups: [], keys: [] };
20
+ on('pointermove', e => state.pointer.push([at(e), e.clientX, e.clientY]));
21
+ on('pointerdown', e => {
22
+ state.pointer.push([at(e), e.clientX, e.clientY]);
23
+ if (e.button === 0) state.downs.push({ ms: at(e), x: e.clientX, y: e.clientY, box: box(e.target) });
24
+ });
25
+ on('pointerup', e => { if (e.button === 0) state.ups.push({ ms: at(e), x: e.clientX, y: e.clientY }); });
26
+ on('keydown', e => state.keys.push({ ms: at(e), box: box(document.activeElement) }));
27
+ // The tab capture never shows the OS pointer; Render draws the cursor instead.
28
+ const css = document.createElement('style');
29
+ css.textContent = '* { cursor:none !important; }';
30
+ document.documentElement.append(css);
31
+ window.__cuetakeProbe = { state, dispose() { abort.abort(); css.remove(); } };
32
+ });
33
+ }
34
+
35
+ const CLICK_SLOP = 6; // CSS px a press may travel and still count as a click
36
+
37
+ /** Rebases probe records to seconds since capture start and derives clicks, drags and typing. */
38
+ export async function collectTimeline(page, startedAtMs) {
39
+ const raw = await page.evaluate(() => window.__cuetakeProbe.state);
40
+ const t = ms => Math.round(ms - startedAtMs) / 1000;
41
+ const pointer = raw.pointer.filter(([ms]) => ms >= startedAtMs).map(([ms, x, y]) => [t(ms), x, y]);
42
+ const events = [];
43
+ for (const down of raw.downs.filter(d => d.ms >= startedAtMs)) {
44
+ const up = raw.ups.find(u => u.ms >= down.ms);
45
+ const moved = up && Math.hypot(up.x - down.x, up.y - down.y) > CLICK_SLOP;
46
+ events.push(moved
47
+ ? { type: 'drag', t: t(down.ms), end: t(up.ms), from: { x: down.x, y: down.y }, to: { x: up.x, y: up.y } }
48
+ : { type: 'click', t: t(down.ms), x: down.x, y: down.y, box: down.box });
49
+ }
50
+ // Consecutive keys into the same field within a second form one typing burst.
51
+ for (const key of raw.keys.filter(k => k.ms >= startedAtMs)) {
52
+ const last = events.at(-1);
53
+ if (last?.type === 'type' && t(key.ms) - last.end <= 1 && JSON.stringify(last.box) === JSON.stringify(key.box)) last.end = t(key.ms);
54
+ else events.push({ type: 'type', t: t(key.ms), end: t(key.ms), box: key.box });
55
+ }
56
+ return { pointer, events: events.sort((a, b) => a.t - b.t) };
57
+ }
@@ -0,0 +1,64 @@
1
+ import { chromium } from 'playwright';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { mkdir } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { startTabCapture, stopTabCapture } from './tab-capture.js';
6
+ import { installProbe } from './probe.js';
7
+
8
+ let browser = null;
9
+ const sessions = new Map();
10
+
11
+ export async function startRecording(url, options = {}) {
12
+ const width = options.width || 1440, height = options.height || 900;
13
+ const resolutionScale = options.resolutionScale || 2;
14
+ // Headless by default. Chromium's new headless mode (channel 'chromium') supports tab capture,
15
+ // but only captures at device scale when the scale is also forced on the browser.
16
+ browser ||= await chromium.launch({
17
+ headless: !options.headed, channel: 'chromium',
18
+ args: ['--auto-accept-this-tab-capture', '--disable-backgrounding-occluded-windows', '--disable-renderer-backgrounding', ...(options.headed ? [] : [`--force-device-scale-factor=${resolutionScale}`])],
19
+ });
20
+ const outputDir = options.outputDir || './recordings';
21
+ await mkdir(outputDir, { recursive: true });
22
+ const context = await browser.newContext({ viewport: { width, height }, deviceScaleFactor: resolutionScale, ...(options.storageState ? { storageState: options.storageState } : {}) });
23
+ const sessionId = randomUUID().slice(0, 8);
24
+ try {
25
+ const page = await context.newPage();
26
+ await page.goto(url, { waitUntil: 'load', timeout: 30_000 });
27
+ sessions.set(sessionId, { context, page, width, height, resolutionScale, options, outputDir });
28
+ if (!options.deferCapture) await beginCapture(sessionId);
29
+ return { sessionId, url };
30
+ } catch (error) { sessions.delete(sessionId); await context.close(); throw error; }
31
+ }
32
+
33
+ export function getRecordingPage(sessionId) {
34
+ const session = sessions.get(sessionId);
35
+ if (!session) throw new Error(`Unknown session ${sessionId}`);
36
+ return session.page;
37
+ }
38
+
39
+ export async function beginCapture(sessionId) {
40
+ const session = sessions.get(sessionId);
41
+ if (!session || session.capture) throw new Error('Session is missing or already recording');
42
+ // Preparation may navigate through login; install the probe only at the final document.
43
+ await installProbe(session.page);
44
+ const capture = await startTabCapture(session.page, { width: session.width * session.resolutionScale, height: session.height * session.resolutionScale, fps: session.options.fps || 60, bitrate: 40_000_000 });
45
+ session.capture = capture;
46
+ return capture;
47
+ }
48
+
49
+ export async function stopRecording(sessionId) {
50
+ const session = sessions.get(sessionId);
51
+ if (!session?.capture) throw new Error('Session has not started recording');
52
+ const webmPath = join(session.outputDir, `recording-${sessionId}.webm`);
53
+ const stats = await stopTabCapture(session.page, webmPath);
54
+ await session.context.close();
55
+ sessions.delete(sessionId);
56
+ return { webmPath, durationSeconds: stats.duration };
57
+ }
58
+
59
+ export async function cleanup() {
60
+ for (const session of sessions.values()) await session.context.close().catch(() => {});
61
+ sessions.clear();
62
+ await browser?.close().catch(() => {});
63
+ browser = null;
64
+ }