@phil65/demoreel 0.0.0-stage → 0.3.1

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.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +207 -2
  3. package/THIRD_PARTY_NOTICES.md +31 -0
  4. package/dist/args.d.ts +41 -0
  5. package/dist/args.js +252 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +468 -0
  8. package/dist/compose.d.ts +73 -0
  9. package/dist/compose.js +144 -0
  10. package/dist/env.d.ts +38 -0
  11. package/dist/env.js +182 -0
  12. package/dist/idle.d.ts +48 -0
  13. package/dist/idle.js +99 -0
  14. package/dist/index.d.ts +14 -0
  15. package/dist/index.js +13 -0
  16. package/dist/init.d.ts +19 -0
  17. package/dist/init.js +92 -0
  18. package/dist/layout.d.ts +52 -0
  19. package/dist/layout.js +55 -0
  20. package/dist/load.d.ts +2 -0
  21. package/dist/load.js +76 -0
  22. package/dist/marks.d.ts +69 -0
  23. package/dist/marks.js +153 -0
  24. package/dist/motion.d.ts +15 -0
  25. package/dist/motion.js +49 -0
  26. package/dist/openscreen/project.js +793 -0
  27. package/dist/openscreen.d.ts +14 -0
  28. package/dist/openscreen.js +41 -0
  29. package/dist/project.d.ts +143 -0
  30. package/dist/project.js +144 -0
  31. package/dist/record.d.ts +90 -0
  32. package/dist/record.js +189 -0
  33. package/dist/recorder.d.ts +41 -0
  34. package/dist/recorder.js +149 -0
  35. package/dist/render.d.ts +58 -0
  36. package/dist/render.js +139 -0
  37. package/dist/renderer/assets/CanvasPool-CHSHS1-v.js +23 -0
  38. package/dist/renderer/assets/Cursor_App-Starting-zEGhqPJj.svg +8 -0
  39. package/dist/renderer/assets/Cursor_Cross-BuZZnB_U.svg +5 -0
  40. package/dist/renderer/assets/Cursor_Default-DkmrqhKh.svg +5 -0
  41. package/dist/renderer/assets/Cursor_Hand-(Grabbing)-B-Qy-RsV.svg +5 -0
  42. package/dist/renderer/assets/Cursor_Hand-(Open)-DGrW1tFF.svg +5 -0
  43. package/dist/renderer/assets/Cursor_Hand-(Pointing)-Byy2KbtA.svg +5 -0
  44. package/dist/renderer/assets/Cursor_Help-D5NcyFpT.svg +8 -0
  45. package/dist/renderer/assets/Cursor_Move-CerM5f-0.svg +5 -0
  46. package/dist/renderer/assets/Cursor_Not-Allowed-3rttFVa5.svg +7 -0
  47. package/dist/renderer/assets/Cursor_Resize-North-East-South-West-CBd4tbCA.svg +5 -0
  48. package/dist/renderer/assets/Cursor_Resize-North-South-DOxgUIwF.svg +5 -0
  49. package/dist/renderer/assets/Cursor_Resize-North-West-South-East-hzXJFJ2_.svg +5 -0
  50. package/dist/renderer/assets/Cursor_Resize-West-East-rDJgc6AZ.svg +5 -0
  51. package/dist/renderer/assets/Cursor_Text-Cursor-Cn9rFLjY.svg +5 -0
  52. package/dist/renderer/assets/Cursor_Up-Arrow-CYyEN-dA.svg +4 -0
  53. package/dist/renderer/assets/Cursor_Wait-CK8tq-9y.svg +6 -0
  54. package/dist/renderer/assets/RenderTargetSystem-EAUH9iQk.js +404 -0
  55. package/dist/renderer/assets/browserAll-aHn2isHo.js +14 -0
  56. package/dist/renderer/assets/canvasUtils-n5g2f3_X.js +1 -0
  57. package/dist/renderer/assets/getTexelRangeRects-yD6MQ0xy.js +195 -0
  58. package/dist/renderer/assets/getTextureBatchBindGroup-Bwvgbco6.js +1 -0
  59. package/dist/renderer/assets/gif.worker-CjkyQP34.js +3 -0
  60. package/dist/renderer/assets/index-BwP6rH7I.js +556 -0
  61. package/dist/renderer/assets/init-C2Za5NQh.js +83 -0
  62. package/dist/renderer/assets/webworkerAll-JSSmbaR2.js +1 -0
  63. package/dist/renderer/index.html +13 -0
  64. package/dist/renderer/wallpapers/wallpaper1.jpg +0 -0
  65. package/dist/renderer/wallpapers/wallpaper12.jpg +0 -0
  66. package/dist/renderer/wallpapers/wallpaper5.jpg +0 -0
  67. package/dist/renderer/wasm/web-demuxer.wasm +0 -0
  68. package/dist/scene.d.ts +203 -0
  69. package/dist/scene.js +634 -0
  70. package/dist/server.d.ts +12 -0
  71. package/dist/server.js +116 -0
  72. package/dist/sheet.d.ts +37 -0
  73. package/dist/sheet.js +98 -0
  74. package/dist/types.d.ts +103 -0
  75. package/dist/types.js +2 -0
  76. package/dist/zoom.d.ts +57 -0
  77. package/dist/zoom.js +178 -0
  78. package/examples/demo-app/index.html +99 -0
  79. package/examples/local-demo.ts +21 -0
  80. package/licenses/colord.txt +21 -0
  81. package/licenses/earcut.txt +15 -0
  82. package/licenses/eventemitter3.txt +21 -0
  83. package/licenses/gif.js.txt +1 -0
  84. package/licenses/ismobilejs.txt +21 -0
  85. package/licenses/mediabunny.txt +373 -0
  86. package/licenses/motion-dom.txt +21 -0
  87. package/licenses/motion-utils.txt +21 -0
  88. package/licenses/openscreen.txt +21 -0
  89. package/licenses/parse-svg-path.txt +23 -0
  90. package/licenses/pixi-filters.txt +21 -0
  91. package/licenses/pixi.js.txt +21 -0
  92. package/licenses/web-demuxer.txt +21 -0
  93. package/package.json +74 -4
@@ -0,0 +1,14 @@
1
+ export declare const PACKAGE_ROOT: string;
2
+ export declare const RENDERER_DIR: string;
3
+ export declare const PROJECT_BUNDLE: string;
4
+ export interface OpenScreenProjectApi {
5
+ PROJECT_VERSION: number;
6
+ validateProjectData(candidate: unknown): boolean;
7
+ normalizeProjectEditor(editor: unknown): Record<string, unknown>;
8
+ resolveProjectMedia(project: unknown): unknown;
9
+ ZOOM_DEPTH_SCALES: Record<number, number>;
10
+ TRANSITION_WINDOW_MS: number;
11
+ ZOOM_IN_TRANSITION_WINDOW_MS: number;
12
+ }
13
+ export declare function rendererDir(): string;
14
+ export declare function openscreenProjectApi(): Promise<OpenScreenProjectApi>;
@@ -0,0 +1,41 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ /**
10
+ * Access to the prebuilt OpenScreen bundles in `dist/` (built by `npm run build:renderer`
11
+ * from the vendored, unmodified OpenScreen sources):
12
+ *
13
+ * - `dist/renderer/`: static browser app running OpenScreen's VideoExporter (headless export)
14
+ * - `dist/openscreen/project.js`: OpenScreen's project validation/normalisation for Node
15
+ *
16
+ * Paths resolve relative to the package root, so this works from `src/` (dev) and `dist/`.
17
+ */
18
+ import fs from "node:fs";
19
+ import path from "node:path";
20
+ import { fileURLToPath, pathToFileURL } from "node:url";
21
+ import { DemoreelError } from "./env.js";
22
+ export const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
23
+ export const RENDERER_DIR = path.join(PACKAGE_ROOT, "dist", "renderer");
24
+ export const PROJECT_BUNDLE = path.join(PACKAGE_ROOT, "dist", "openscreen", "project.js");
25
+ function missing(what) {
26
+ throw new DemoreelError(`demoreel's prebuilt OpenScreen bundle is missing (${what}).`, "in a git checkout run `npm run build:renderer`; from npm, reinstall demoreel");
27
+ }
28
+ export function rendererDir() {
29
+ if (!fs.existsSync(path.join(RENDERER_DIR, "index.html")))
30
+ missing(RENDERER_DIR);
31
+ return RENDERER_DIR;
32
+ }
33
+ let api = null;
34
+ export function openscreenProjectApi() {
35
+ api ??= (async () => {
36
+ if (!fs.existsSync(PROJECT_BUNDLE))
37
+ missing(PROJECT_BUNDLE);
38
+ return (await import(__rewriteRelativeImportExtension(pathToFileURL(PROJECT_BUNDLE).href)));
39
+ })();
40
+ return api;
41
+ }
@@ -0,0 +1,143 @@
1
+ import type { Caption, CursorSample, SpeedRegion, TrimRegion, ZoomRegion } from "./types.ts";
2
+ export declare const PROJECT_VERSION = 2;
3
+ export declare const CURSOR_TELEMETRY_VERSION = 2;
4
+ export interface LookOptions {
5
+ /** Wallpaper: "#hex", CSS gradient, or one of OpenScreen's "/wallpapers/wallpaperN.jpg". */
6
+ wallpaper: string;
7
+ /** 0-100; 40 => the recording covers 84% of the canvas. */
8
+ padding: number;
9
+ borderRadius: number;
10
+ shadowIntensity: number;
11
+ motionBlurAmount: number;
12
+ /** "16:9", "9:16", "1:1", "4:3", "4:5", "16:10", "10:16" or "native". */
13
+ aspectRatio: string;
14
+ /** Where captions sit; "auto" (default) = bottom, unless that covers an active target. */
15
+ captionPosition: "auto" | "bottom" | "top";
16
+ captionFontSize: number;
17
+ }
18
+ export declare const DEFAULT_LOOK: LookOptions;
19
+ /** Caption box in percent of the output canvas (OpenScreen annotation position/size). */
20
+ export declare function captionRect(position: LookOptions["captionPosition"] | undefined): {
21
+ x: number;
22
+ y: number;
23
+ width: number;
24
+ height: number;
25
+ };
26
+ export declare function captionAnnotations(captions: Caption[], look?: LookOptions): {
27
+ id: string;
28
+ startMs: number;
29
+ endMs: number;
30
+ type: string;
31
+ content: string;
32
+ textContent: string;
33
+ position: {
34
+ x: number;
35
+ y: number;
36
+ };
37
+ size: {
38
+ width: number;
39
+ height: number;
40
+ };
41
+ style: {
42
+ color: string;
43
+ backgroundColor: string;
44
+ fontSize: number;
45
+ fontFamily: string;
46
+ fontWeight: string;
47
+ fontStyle: string;
48
+ textDecoration: string;
49
+ textAlign: string;
50
+ textAnimation: string;
51
+ };
52
+ zIndex: number;
53
+ }[];
54
+ export interface BuildProjectOptions {
55
+ videoPath: string;
56
+ zoomRegions: ZoomRegion[];
57
+ captions: Caption[];
58
+ trimRegions?: TrimRegion[];
59
+ speedRegions?: SpeedRegion[];
60
+ look?: Partial<LookOptions>;
61
+ }
62
+ export type OpenScreenProject = ReturnType<typeof buildProject>;
63
+ export declare function buildProject(opts: BuildProjectOptions): {
64
+ version: number;
65
+ videoPath: string;
66
+ media: {
67
+ screenVideoPath: string;
68
+ cursorCaptureMode: string;
69
+ };
70
+ editor: {
71
+ wallpaper: string;
72
+ shadowIntensity: number;
73
+ showBlur: boolean;
74
+ showTrimWaveform: boolean;
75
+ motionBlurAmount: number;
76
+ borderRadius: number;
77
+ padding: number;
78
+ cropRegion: {
79
+ x: number;
80
+ y: number;
81
+ width: number;
82
+ height: number;
83
+ };
84
+ zoomRegions: ZoomRegion[];
85
+ autoZoomEnabled: boolean;
86
+ autoFocusAll: boolean;
87
+ trimRegions: TrimRegion[];
88
+ speedRegions: SpeedRegion[];
89
+ annotationRegions: {
90
+ id: string;
91
+ startMs: number;
92
+ endMs: number;
93
+ type: string;
94
+ content: string;
95
+ textContent: string;
96
+ position: {
97
+ x: number;
98
+ y: number;
99
+ };
100
+ size: {
101
+ width: number;
102
+ height: number;
103
+ };
104
+ style: {
105
+ color: string;
106
+ backgroundColor: string;
107
+ fontSize: number;
108
+ fontFamily: string;
109
+ fontWeight: string;
110
+ fontStyle: string;
111
+ textDecoration: string;
112
+ textAlign: string;
113
+ textAnimation: string;
114
+ };
115
+ zIndex: number;
116
+ }[];
117
+ aspectRatio: string;
118
+ webcamLayoutPreset: string;
119
+ webcamMaskShape: string;
120
+ webcamMirrored: boolean;
121
+ webcamReactiveZoom: boolean;
122
+ webcamSizePreset: number;
123
+ webcamPosition: null;
124
+ exportQuality: string;
125
+ exportFormat: string;
126
+ gifFrameRate: number;
127
+ gifLoop: boolean;
128
+ gifSizePreset: string;
129
+ cursorTheme: string;
130
+ };
131
+ };
132
+ /**
133
+ * Normalises cursor telemetry for OpenScreen: finite, sorted, non-negative times; positions
134
+ * clamped to 0-1; consecutive duplicate samples dropped (clicks are always kept).
135
+ */
136
+ export declare function normalizeSamples(samples: CursorSample[]): Required<CursorSample>[];
137
+ export declare function buildCursorData(samples: CursorSample[]): {
138
+ version: number;
139
+ provider: "none";
140
+ samples: Required<CursorSample>[];
141
+ assets: unknown[];
142
+ };
143
+ export declare function writeProject(outDir: string, name: string, project: unknown, videoPath: string, cursorData: unknown): string;
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Writes an OpenScreen v2 project (`*.openscreen`) plus the cursor sidecar
3
+ * (`<video>.cursor.json`, the file OpenScreen's main process reads in
4
+ * electron/ipc/handlers.ts::readCursorRecordingFile).
5
+ */
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ export const PROJECT_VERSION = 2;
9
+ export const CURSOR_TELEMETRY_VERSION = 2;
10
+ export const DEFAULT_LOOK = {
11
+ wallpaper: "linear-gradient(135deg, #1f2a6b 0%, #5b3fa8 55%, #c0589b 100%)",
12
+ padding: 40,
13
+ borderRadius: 14,
14
+ shadowIntensity: 0.6,
15
+ motionBlurAmount: 0.2,
16
+ aspectRatio: "16:9",
17
+ captionPosition: "auto",
18
+ captionFontSize: 30,
19
+ };
20
+ /** Caption box in percent of the output canvas (OpenScreen annotation position/size). */
21
+ export function captionRect(position) {
22
+ return { x: 15, y: position === "top" ? 3.5 : 88.5, width: 70, height: 8 };
23
+ }
24
+ export function captionAnnotations(captions, look = DEFAULT_LOOK) {
25
+ return captions.map((c, i) => {
26
+ const r = captionRect(c.position ?? look.captionPosition);
27
+ return {
28
+ id: `annotation-${i + 1}`,
29
+ startMs: Math.round(c.startMs),
30
+ endMs: Math.round(c.endMs),
31
+ type: "text",
32
+ content: c.text,
33
+ textContent: c.text,
34
+ position: { x: r.x, y: r.y },
35
+ size: { width: r.width, height: r.height },
36
+ style: {
37
+ color: "#ffffff",
38
+ backgroundColor: "rgba(12, 14, 28, 0.72)",
39
+ fontSize: look.captionFontSize,
40
+ fontFamily: "Inter, 'DejaVu Sans', system-ui, sans-serif",
41
+ fontWeight: "bold",
42
+ fontStyle: "normal",
43
+ textDecoration: "none",
44
+ textAlign: "center",
45
+ textAnimation: "none",
46
+ },
47
+ zIndex: i + 1,
48
+ };
49
+ });
50
+ }
51
+ export function buildProject(opts) {
52
+ const look = { ...DEFAULT_LOOK, ...opts.look };
53
+ const videoPath = path.resolve(opts.videoPath);
54
+ return {
55
+ version: PROJECT_VERSION,
56
+ // Legacy field: OpenScreen <= 1.2 (v1 projects) only reads `videoPath`; >= 1.3 prefers `media`.
57
+ videoPath,
58
+ media: {
59
+ screenVideoPath: videoPath,
60
+ cursorCaptureMode: "editable-overlay",
61
+ },
62
+ editor: {
63
+ wallpaper: look.wallpaper,
64
+ shadowIntensity: look.shadowIntensity,
65
+ showBlur: false,
66
+ showTrimWaveform: true,
67
+ motionBlurAmount: look.motionBlurAmount,
68
+ borderRadius: look.borderRadius,
69
+ padding: look.padding,
70
+ cropRegion: { x: 0, y: 0, width: 1, height: 1 },
71
+ zoomRegions: opts.zoomRegions,
72
+ autoZoomEnabled: false,
73
+ autoFocusAll: false,
74
+ trimRegions: opts.trimRegions ?? [],
75
+ speedRegions: opts.speedRegions ?? [],
76
+ annotationRegions: captionAnnotations(opts.captions, look),
77
+ aspectRatio: look.aspectRatio,
78
+ webcamLayoutPreset: "picture-in-picture",
79
+ webcamMaskShape: "rectangle",
80
+ webcamMirrored: true,
81
+ webcamReactiveZoom: false,
82
+ webcamSizePreset: 25,
83
+ webcamPosition: null,
84
+ exportQuality: "good",
85
+ exportFormat: "mp4",
86
+ gifFrameRate: 15,
87
+ gifLoop: true,
88
+ gifSizePreset: "medium",
89
+ cursorTheme: "default",
90
+ },
91
+ };
92
+ }
93
+ const round4 = (v) => Math.round(v * 10000) / 10000;
94
+ const clamp01 = (v) => (Number.isFinite(v) ? Math.min(1, Math.max(0, v)) : 0.5);
95
+ /**
96
+ * Normalises cursor telemetry for OpenScreen: finite, sorted, non-negative times; positions
97
+ * clamped to 0-1; consecutive duplicate samples dropped (clicks are always kept).
98
+ */
99
+ export function normalizeSamples(samples) {
100
+ const sorted = samples
101
+ .filter((s) => Number.isFinite(s.timeMs))
102
+ .map((s, i) => ({ s, i }))
103
+ .sort((a, b) => a.s.timeMs - b.s.timeMs || a.i - b.i)
104
+ .map(({ s }) => s);
105
+ const out = [];
106
+ for (const s of sorted) {
107
+ const n = {
108
+ timeMs: Math.max(0, Math.round(s.timeMs * 10) / 10),
109
+ cx: round4(clamp01(s.cx)),
110
+ cy: round4(clamp01(s.cy)),
111
+ assetId: s.assetId ?? null,
112
+ visible: s.visible ?? true,
113
+ cursorType: s.cursorType ?? "arrow",
114
+ interactionType: s.interactionType ?? "move",
115
+ };
116
+ const prev = out[out.length - 1];
117
+ if (prev &&
118
+ n.interactionType === "move" &&
119
+ prev.interactionType === "move" &&
120
+ prev.cx === n.cx &&
121
+ prev.cy === n.cy &&
122
+ prev.cursorType === n.cursorType &&
123
+ prev.visible === n.visible &&
124
+ n.timeMs - prev.timeMs < 1) {
125
+ continue;
126
+ }
127
+ out.push(n);
128
+ }
129
+ return out;
130
+ }
131
+ export function buildCursorData(samples) {
132
+ return {
133
+ version: CURSOR_TELEMETRY_VERSION,
134
+ provider: "none",
135
+ samples: normalizeSamples(samples),
136
+ assets: [],
137
+ };
138
+ }
139
+ export function writeProject(outDir, name, project, videoPath, cursorData) {
140
+ const projectPath = path.join(outDir, `${name}.openscreen`);
141
+ fs.writeFileSync(projectPath, JSON.stringify(project, null, 2));
142
+ fs.writeFileSync(`${videoPath}.cursor.json`, JSON.stringify(cursorData));
143
+ return projectPath;
144
+ }
@@ -0,0 +1,90 @@
1
+ import type { Page } from "playwright";
2
+ import { type ComposeResult } from "./compose.ts";
3
+ import type { IdleOptions } from "./idle.ts";
4
+ import type { LookOptions } from "./project.ts";
5
+ import { type PacingOptions, Scene } from "./scene.ts";
6
+ import type { ActionRecord, RecordingResult, Viewport } from "./types.ts";
7
+ import type { ZoomOptions } from "./zoom.ts";
8
+ export interface ScenarioContext {
9
+ /** URL of the scenario's `serve` directory ("" if none). */
10
+ baseUrl: string;
11
+ }
12
+ export interface Scenario {
13
+ /** Output file stem (`<name>.openscreen`, `<name>.mp4`). */
14
+ name: string;
15
+ /** Browser viewport == recorded frame size in px (default 1920x1080). */
16
+ viewport?: Viewport;
17
+ /**
18
+ * Enlarge the page with CSS `zoom` on <html> (1.5 => a 1920x1080 recording lays out like a
19
+ * 1280x720 page at 1.5x). Chromium's screencast ignores deviceScaleFactor (frames are in DIP),
20
+ * so this is the only way to get "retina" pixels. Media queries still see the full viewport,
21
+ * so only use it for pages whose layout you control.
22
+ */
23
+ cssZoom?: number;
24
+ /** Static directory (relative to the scenario file) served at `ctx.baseUrl`. */
25
+ serve?: string;
26
+ /** Saved Playwright storageState JSON file (relative to the scenario file, like `serve`). */
27
+ storageState?: string;
28
+ colorScheme?: "light" | "dark";
29
+ /** Seed for the cursor-path jitter (same seed => same motion). */
30
+ seed?: number;
31
+ pacing?: Partial<PacingOptions>;
32
+ zoom?: Partial<ZoomOptions>;
33
+ look?: Partial<LookOptions>;
34
+ /** Cut (or speed up) idle stretches with OpenScreen trim/speed regions. */
35
+ trimIdle?: boolean | Partial<IdleOptions>;
36
+ run(scene: Scene, ctx: ScenarioContext): Promise<void>;
37
+ }
38
+ /** Identity helper that gives scenario files type checking and editor completion. */
39
+ export declare function defineScenario(s: Scenario): Scenario;
40
+ export interface RecordOptions {
41
+ /** Output directory (default: out/<name>). */
42
+ outDir?: string;
43
+ /** Path of the scenario file; `serve` and `storageState` are resolved relative to it (default: cwd). */
44
+ scenarioFile?: string;
45
+ /** Override scenario fields (e.g. from CLI flags). */
46
+ overrides?: Partial<Omit<Scenario, "run" | "name">>;
47
+ /** Override `scenario.storageState` (resolved relative to cwd). */
48
+ storageState?: string;
49
+ /** Show the browser while recording (debugging; the recording then includes OS chrome timing). */
50
+ headed?: boolean;
51
+ log?: (msg: string) => void;
52
+ }
53
+ export interface RecordResult extends ComposeResult {
54
+ result: RecordingResult;
55
+ outDir: string;
56
+ zoomRegions: ComposeResult["timeline"]["zoomRegions"];
57
+ }
58
+ export interface DryRunError {
59
+ message: string;
60
+ /** Index of the failing step: the number of actions that completed before it. */
61
+ actionIndex: number;
62
+ }
63
+ export interface DryRunOptions {
64
+ /** Path of the scenario file; `serve` and `storageState` are resolved relative to it (default: cwd). */
65
+ scenarioFile?: string;
66
+ /** Override scenario fields (e.g. from CLI flags). */
67
+ overrides?: Partial<Omit<Scenario, "run" | "name">>;
68
+ /** Override `scenario.storageState` (resolved relative to cwd). */
69
+ storageState?: string;
70
+ /** Show the browser while running. */
71
+ headed?: boolean;
72
+ /** Called with the Playwright page at the end of the run (both on success and failure), before closing the browser. */
73
+ atEnd?: (page: Page) => Promise<void> | void;
74
+ /** Called on failure with the error and page, before `atEnd` and before closing the browser. */
75
+ onFailure?: (err: DryRunError, page: Page) => Promise<void> | void;
76
+ }
77
+ export interface DryRunResult {
78
+ ok: boolean;
79
+ actions: ActionRecord[];
80
+ durationMs: number;
81
+ error?: DryRunError;
82
+ }
83
+ /** Resolves a Playwright storageState file path and throws a clear DemoreelError if missing. */
84
+ export declare function resolveStorageState(statePath: string | undefined, baseDir?: string): string | undefined;
85
+ export declare function recordScenario(input: Scenario, opts?: RecordOptions): Promise<RecordResult>;
86
+ /**
87
+ * Runs a scenario quickly in fast mode (no ffmpeg, no CDP screencast, no output files).
88
+ * Invokes `atEnd(page)` on both success and failure before closing the browser and static server.
89
+ */
90
+ export declare function dryRunScenario(input: Scenario, opts?: DryRunOptions): Promise<DryRunResult>;
package/dist/record.js ADDED
@@ -0,0 +1,189 @@
1
+ /** Runs a scenario in headless Chromium, records it and writes the OpenScreen project. */
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { compose } from "./compose.js";
5
+ import { checkFfmpeg, DemoreelError, launchChromium } from "./env.js";
6
+ import { ScreencastRecorder } from "./recorder.js";
7
+ import { Scene } from "./scene.js";
8
+ import { serveStatic } from "./server.js";
9
+ /** Identity helper that gives scenario files type checking and editor completion. */
10
+ export function defineScenario(s) {
11
+ return s;
12
+ }
13
+ /** Resolves a Playwright storageState file path and throws a clear DemoreelError if missing. */
14
+ export function resolveStorageState(statePath, baseDir = process.cwd()) {
15
+ if (!statePath)
16
+ return undefined;
17
+ const resolved = path.resolve(baseDir, statePath);
18
+ if (!fs.existsSync(resolved)) {
19
+ throw new DemoreelError(`storageState file not found: ${resolved}`, `demoreel login <url> --state ${statePath}`);
20
+ }
21
+ return resolved;
22
+ }
23
+ function mergeScenario(input, overrides) {
24
+ const scenario = { ...input, ...overrides };
25
+ if (!scenario.name || typeof scenario.run !== "function") {
26
+ throw new Error("a scenario needs a `name` and an async `run(scene, ctx)` (use defineScenario)");
27
+ }
28
+ return scenario;
29
+ }
30
+ /** Shared Chromium context + static server setup for both recording and dry runs. */
31
+ async function openScenarioSession(input, opts) {
32
+ const scenario = mergeScenario(input, opts.overrides);
33
+ const baseDir = opts.scenarioFile ? path.dirname(path.resolve(opts.scenarioFile)) : process.cwd();
34
+ const storageState = opts.storageState
35
+ ? resolveStorageState(opts.storageState, process.cwd())
36
+ : resolveStorageState(scenario.storageState, baseDir);
37
+ let server = null;
38
+ if (scenario.serve) {
39
+ const dir = path.resolve(baseDir, scenario.serve);
40
+ if (!fs.existsSync(dir))
41
+ throw new Error(`scenario.serve: ${dir} does not exist`);
42
+ server = await serveStatic(dir);
43
+ }
44
+ const viewport = scenario.viewport ?? { width: 1920, height: 1080 };
45
+ let browser = null;
46
+ try {
47
+ browser = await launchChromium({ headless: !opts.headed });
48
+ const context = await browser.newContext({
49
+ viewport,
50
+ deviceScaleFactor: 1,
51
+ colorScheme: scenario.colorScheme ?? "light",
52
+ ...(storageState ? { storageState } : {}),
53
+ });
54
+ if (scenario.cssZoom && scenario.cssZoom !== 1) {
55
+ await context.addInitScript((z) => {
56
+ const apply = () => document.documentElement?.style.setProperty("zoom", String(z), "important");
57
+ apply();
58
+ new MutationObserver(apply).observe(document, { childList: true });
59
+ document.addEventListener("DOMContentLoaded", apply);
60
+ }, scenario.cssZoom);
61
+ }
62
+ const page = await context.newPage();
63
+ const close = async () => {
64
+ await browser?.close().catch(() => { });
65
+ await server?.close();
66
+ };
67
+ return { scenario, viewport, browser, context, page, baseUrl: server?.url ?? "", close };
68
+ }
69
+ catch (e) {
70
+ await browser?.close().catch(() => { });
71
+ await server?.close();
72
+ throw e;
73
+ }
74
+ }
75
+ export async function recordScenario(input, opts = {}) {
76
+ const scenario = mergeScenario(input, opts.overrides);
77
+ checkFfmpeg();
78
+ const outDir = path.resolve(opts.outDir ?? path.join("out", scenario.name));
79
+ const timings = {};
80
+ const t0 = Date.now();
81
+ const session = await openScenarioSession(input, opts);
82
+ const framesDir = path.join(outDir, ".frames");
83
+ fs.mkdirSync(outDir, { recursive: true });
84
+ fs.rmSync(framesDir, { recursive: true, force: true });
85
+ let recorder = null;
86
+ let scene = null;
87
+ try {
88
+ scene = new Scene(session.page, session.viewport, async () => {
89
+ recorder = new ScreencastRecorder(session.page, framesDir, {
90
+ maxWidth: session.viewport.width,
91
+ maxHeight: session.viewport.height,
92
+ });
93
+ await recorder.start();
94
+ return recorder;
95
+ }, { seed: session.scenario.seed, pacing: session.scenario.pacing });
96
+ const tRun = Date.now();
97
+ await session.scenario.run(scene, { baseUrl: session.baseUrl });
98
+ // Hold the last frame so the final zoom-out and captions finish.
99
+ const lastCaptionEnd = Math.max(0, ...scene.captions.map((c) => c.endMs));
100
+ await scene.pause(Math.max(900, lastCaptionEnd - scene.now() + 300));
101
+ timings.scenarioMs = Date.now() - tRun;
102
+ }
103
+ catch (e) {
104
+ await session.close();
105
+ throw e;
106
+ }
107
+ const rec = recorder;
108
+ if (!rec || !scene) {
109
+ await session.close();
110
+ throw new Error("scenario never started recording (call scene.goto first)");
111
+ }
112
+ const { durationMs, frameCount } = await rec.stop();
113
+ await session.close();
114
+ const videoPath = path.join(outDir, "recording.mp4");
115
+ const tEnc = Date.now();
116
+ await rec.encode(videoPath, 30);
117
+ timings.encodeMs = Date.now() - tEnc;
118
+ const frameTimes = rec.frameTimes;
119
+ fs.rmSync(framesDir, { recursive: true, force: true });
120
+ timings.recordTotalMs = Date.now() - t0;
121
+ const composed = compose({
122
+ name: session.scenario.name,
123
+ outDir,
124
+ videoPath,
125
+ durationMs,
126
+ frameCount,
127
+ viewport: session.viewport,
128
+ frameSize: rec.frameSize,
129
+ actions: scene.actions,
130
+ captions: scene.captions,
131
+ samples: scene.samples,
132
+ frameTimes,
133
+ timings,
134
+ zoom: session.scenario.zoom,
135
+ look: session.scenario.look,
136
+ trimIdle: session.scenario.trimIdle,
137
+ });
138
+ const result = {
139
+ videoPath,
140
+ durationMs,
141
+ frameSize: rec.frameSize,
142
+ viewport: session.viewport,
143
+ samples: scene.samples,
144
+ actions: scene.actions,
145
+ captions: scene.captions,
146
+ frameTimes,
147
+ frameCount,
148
+ timings,
149
+ };
150
+ return { ...composed, result, outDir, zoomRegions: composed.timeline.zoomRegions };
151
+ }
152
+ /**
153
+ * Runs a scenario quickly in fast mode (no ffmpeg, no CDP screencast, no output files).
154
+ * Invokes `atEnd(page)` on both success and failure before closing the browser and static server.
155
+ */
156
+ export async function dryRunScenario(input, opts = {}) {
157
+ const t0 = performance.now();
158
+ const session = await openScenarioSession(input, opts);
159
+ try {
160
+ const startClock = async () => {
161
+ const origin = performance.now();
162
+ return { now: () => performance.now() - origin };
163
+ };
164
+ const scene = new Scene(session.page, session.viewport, startClock, {
165
+ seed: session.scenario.seed,
166
+ pacing: session.scenario.pacing,
167
+ fast: true,
168
+ });
169
+ try {
170
+ await session.scenario.run(scene, { baseUrl: session.baseUrl });
171
+ const durationMs = Math.round(performance.now() - t0);
172
+ await opts.atEnd?.(session.page);
173
+ return { ok: true, actions: scene.actions, durationMs };
174
+ }
175
+ catch (e) {
176
+ const durationMs = Math.round(performance.now() - t0);
177
+ const error = {
178
+ message: e instanceof Error ? e.message : String(e),
179
+ actionIndex: scene.actions.length,
180
+ };
181
+ await opts.onFailure?.(error, session.page);
182
+ await opts.atEnd?.(session.page);
183
+ return { ok: false, actions: scene.actions, durationMs, error };
184
+ }
185
+ }
186
+ finally {
187
+ await session.close();
188
+ }
189
+ }
@@ -0,0 +1,41 @@
1
+ import type { Page } from "playwright";
2
+ export interface ScreencastOptions {
3
+ quality?: number;
4
+ maxWidth: number;
5
+ maxHeight: number;
6
+ }
7
+ export declare class ScreencastRecorder {
8
+ private session;
9
+ private frames;
10
+ private lastFrameData;
11
+ private pending;
12
+ private stopTs;
13
+ private firstFrame;
14
+ private resolveFirst;
15
+ frameSize: {
16
+ width: number;
17
+ height: number;
18
+ };
19
+ private page;
20
+ private dir;
21
+ private opts;
22
+ constructor(page: Page, dir: string, opts: ScreencastOptions);
23
+ /** Epoch ms of the first frame; all telemetry is expressed relative to this. */
24
+ get t0(): number;
25
+ start(): Promise<void>;
26
+ /** Recording-clock times (ms since the first frame) of all captured frames. */
27
+ get frameTimes(): number[];
28
+ /** Current time on the recording clock (ms since first frame). */
29
+ now(): number;
30
+ stop(): Promise<{
31
+ durationMs: number;
32
+ frameCount: number;
33
+ }>;
34
+ /**
35
+ * Encode the captured frames to a CFR H.264 MP4: for every output frame time we pick the
36
+ * latest captured frame (sample-and-hold) and pipe its JPEG to ffmpeg, so timing is exact.
37
+ */
38
+ encode(outPath: string, fps?: number): Promise<{
39
+ outputFrames: number;
40
+ }>;
41
+ }