@slidevideo/cli 0.1.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 (101) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/IMPRESSUM.md +13 -0
  3. package/LICENSE-TERMS.md +58 -0
  4. package/README.md +25 -0
  5. package/addons/slidevideo/geometry.ts +127 -0
  6. package/addons/slidevideo/global-top.vue +232 -0
  7. package/addons/slidevideo/package.json +1 -0
  8. package/addons/slidevideo/playback-entries.ts +14 -0
  9. package/addons/slidevideo/preview.ts +157 -0
  10. package/dist/adapters/browser-runtime.d.ts +37 -0
  11. package/dist/adapters/browser-runtime.js +1 -0
  12. package/dist/adapters/edge.d.ts +7 -0
  13. package/dist/adapters/edge.js +46 -0
  14. package/dist/adapters/elevenlabs.d.ts +7 -0
  15. package/dist/adapters/elevenlabs.js +58 -0
  16. package/dist/adapters/powerpoint-preview.d.ts +2 -0
  17. package/dist/adapters/powerpoint-preview.js +18 -0
  18. package/dist/adapters/powerpoint.d.ts +21 -0
  19. package/dist/adapters/powerpoint.js +434 -0
  20. package/dist/adapters/registry.d.ts +4 -0
  21. package/dist/adapters/registry.js +13 -0
  22. package/dist/adapters/slidev-inputs.d.ts +1 -0
  23. package/dist/adapters/slidev-inputs.js +86 -0
  24. package/dist/adapters/slidev-inspection.d.ts +3 -0
  25. package/dist/adapters/slidev-inspection.js +79 -0
  26. package/dist/adapters/slidev-server.d.ts +1 -0
  27. package/dist/adapters/slidev-server.js +48 -0
  28. package/dist/adapters/slidev.d.ts +30 -0
  29. package/dist/adapters/slidev.js +251 -0
  30. package/dist/annotation-paint.d.ts +19 -0
  31. package/dist/annotation-paint.js +13 -0
  32. package/dist/annotations.d.ts +27 -0
  33. package/dist/annotations.js +115 -0
  34. package/dist/assembly.d.ts +48 -0
  35. package/dist/assembly.js +138 -0
  36. package/dist/calibration.d.ts +24 -0
  37. package/dist/calibration.js +346 -0
  38. package/dist/cli.d.ts +2 -0
  39. package/dist/cli.js +180 -0
  40. package/dist/compositor.d.ts +18 -0
  41. package/dist/compositor.js +155 -0
  42. package/dist/contracts.d.ts +358 -0
  43. package/dist/contracts.js +1 -0
  44. package/dist/errors.d.ts +7 -0
  45. package/dist/errors.js +15 -0
  46. package/dist/executables.d.ts +23 -0
  47. package/dist/executables.js +165 -0
  48. package/dist/installation.d.ts +6 -0
  49. package/dist/installation.js +32 -0
  50. package/dist/license-key.d.ts +12 -0
  51. package/dist/license-key.js +55 -0
  52. package/dist/license-status.d.ts +16 -0
  53. package/dist/license-status.js +12 -0
  54. package/dist/media.d.ts +12 -0
  55. package/dist/media.js +57 -0
  56. package/dist/overlay-assets.d.ts +2 -0
  57. package/dist/overlay-assets.js +58 -0
  58. package/dist/pipeline.d.ts +50 -0
  59. package/dist/pipeline.js +257 -0
  60. package/dist/preview/contracts.d.ts +34 -0
  61. package/dist/preview/contracts.js +1 -0
  62. package/dist/preview/player.d.ts +1 -0
  63. package/dist/preview/player.js +129 -0
  64. package/dist/preview/server.d.ts +1 -0
  65. package/dist/preview/server.js +112 -0
  66. package/dist/preview/view.d.ts +1 -0
  67. package/dist/preview/view.js +36 -0
  68. package/dist/revoked-keys.json +1 -0
  69. package/dist/run.d.ts +12 -0
  70. package/dist/run.js +109 -0
  71. package/dist/setup-install.d.ts +7 -0
  72. package/dist/setup-install.js +98 -0
  73. package/dist/setup-license.d.ts +2 -0
  74. package/dist/setup-license.js +63 -0
  75. package/dist/setup.d.ts +34 -0
  76. package/dist/setup.js +218 -0
  77. package/dist/speech.d.ts +6 -0
  78. package/dist/speech.js +125 -0
  79. package/dist/storyboard.d.ts +6 -0
  80. package/dist/storyboard.js +86 -0
  81. package/dist/timing.d.ts +6 -0
  82. package/dist/timing.js +162 -0
  83. package/package.json +134 -0
  84. package/schemas/annotation-geometry.v1.json +130 -0
  85. package/schemas/revoked-keys.schema.json +11 -0
  86. package/schemas/run-manifest.v1.json +96 -0
  87. package/schemas/schedule.v1.json +108 -0
  88. package/schemas/schedule.v2.json +496 -0
  89. package/schemas/speech.v1.json +173 -0
  90. package/schemas/storyboard.v1.json +461 -0
  91. package/schemas/storyboard.v2.json +802 -0
  92. package/schemas/timing-evidence.v1.json +129 -0
  93. package/skills/slidevideo/SKILL.md +56 -0
  94. package/skills/slidevideo/references/production.md +76 -0
  95. package/skills/slidevideo/references/storyboard.md +272 -0
  96. package/tools/edge-tts/edge-tts.py +19 -0
  97. package/tools/edge-tts/requirements.lock +34 -0
  98. package/tools/powerpoint/Native.cs +277 -0
  99. package/tools/powerpoint/powerpoint.ps1 +714 -0
  100. package/tools/powerpoint/preview.ps1 +100 -0
  101. package/tools/powerpoint/requirements.json +11 -0
@@ -0,0 +1,16 @@
1
+ export declare const revocationMessage = "This license key was revoked. New exports using this key will include the watermark.";
2
+ export declare function licenseStatus(input: unknown): {
3
+ readonly status: "invalid";
4
+ readonly license?: undefined;
5
+ } | {
6
+ readonly status: "revoked";
7
+ readonly license?: undefined;
8
+ } | {
9
+ readonly status: "active";
10
+ readonly license: {
11
+ key: string;
12
+ digest: string;
13
+ email: string;
14
+ date: string;
15
+ };
16
+ };
@@ -0,0 +1,12 @@
1
+ import { inspectLicenseKey } from './license-key.js';
2
+ import digests from './revoked-keys.json' with { type: 'json' };
3
+ const revoked = new Set(digests);
4
+ export const revocationMessage = 'This license key was revoked. New exports using this key will include the watermark.';
5
+ export function licenseStatus(input) {
6
+ const license = inspectLicenseKey(input);
7
+ if (!license)
8
+ return { status: 'invalid' };
9
+ if (revoked.has(license.digest))
10
+ return { status: 'revoked' };
11
+ return { status: 'active', license };
12
+ }
@@ -0,0 +1,12 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import type { MediaProperties } from './contracts.js';
3
+ export declare const executionScope: AsyncLocalStorage<AbortSignal>;
4
+ export declare function execute(command: string, args: string[], timeout?: number, env?: NodeJS.ProcessEnv): Promise<Buffer>;
5
+ export declare const digest: (value: string | Buffer) => string;
6
+ export declare function hashFile(path: string): Promise<string>;
7
+ export declare function json<T>(path: string): Promise<T>;
8
+ export declare function saveJson(path: string, value: unknown): Promise<void>;
9
+ export declare function probe(path: string): Promise<MediaProperties>;
10
+ export declare function decode(path: string): Promise<void>;
11
+ export declare function audioDuration(path: string): Promise<number>;
12
+ export declare function videoFramePeriod(path: string): Promise<number>;
package/dist/media.js ADDED
@@ -0,0 +1,57 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { spawn } from 'node:child_process';
3
+ import { createHash } from 'node:crypto';
4
+ import { readFile, mkdir, writeFile, rename } from 'node:fs/promises';
5
+ import { dirname } from 'node:path';
6
+ import { ProductionError } from './errors.js';
7
+ import { executable } from './executables.js';
8
+ export const executionScope = new AsyncLocalStorage();
9
+ export async function execute(command, args, timeout = 120000, env = process.env) {
10
+ if (command === 'ffmpeg' || command === 'ffprobe')
11
+ command = executable(command);
12
+ return new Promise((resolve, reject) => {
13
+ const signal = executionScope.getStore();
14
+ signal?.throwIfAborted();
15
+ const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], env, signal, killSignal: 'SIGKILL', windowsHide: true });
16
+ const out = [];
17
+ const err = [];
18
+ const timer = setTimeout(() => { child.kill('SIGKILL'); }, timeout);
19
+ child.stdout.on('data', data => out.push(data));
20
+ child.stderr.on('data', data => err.push(data));
21
+ child.on('error', error => { clearTimeout(timer); reject(new ProductionError('DEPENDENCY', `${command}: ${error.message}`, 3)); });
22
+ child.on('close', code => {
23
+ clearTimeout(timer);
24
+ if (code !== 0)
25
+ reject(new ProductionError('SUBPROCESS', `${command} exited ${code}: ${Buffer.concat(err).toString().slice(-4000)}`, 3));
26
+ else
27
+ resolve(Buffer.concat(out));
28
+ });
29
+ });
30
+ }
31
+ export const digest = (value) => createHash('sha256').update(value).digest('hex');
32
+ export async function hashFile(path) { return digest(await readFile(path)); }
33
+ export async function json(path) { return JSON.parse(await readFile(path, 'utf8')); }
34
+ export async function saveJson(path, value) {
35
+ await mkdir(dirname(path), { recursive: true });
36
+ await writeFile(`${path}.tmp`, JSON.stringify(value, null, 2) + '\n');
37
+ await rename(`${path}.tmp`, path);
38
+ }
39
+ export async function probe(path) {
40
+ const data = JSON.parse((await execute('ffprobe', ['-v', 'error', '-show_streams', '-show_format', '-of', 'json', path])).toString());
41
+ const video = data.streams.find((s) => s.codec_type === 'video');
42
+ const [n, d] = (video?.avg_frame_rate ?? '0/1').split('/').map(Number);
43
+ return { width: video?.width ?? 0, height: video?.height ?? 0, fps: d ? n / d : 0, duration_ms: Number(data.format.duration) * 1000, has_audio: data.streams.some((s) => s.codec_type === 'audio') };
44
+ }
45
+ export async function decode(path) { await execute('ffmpeg', ['-v', 'error', '-xerror', '-i', path, '-f', 'null', '-']); }
46
+ export async function audioDuration(path) { const pcm = await execute('ffmpeg', ['-v', 'error', '-i', path, '-vn', '-ac', '1', '-ar', '48000', '-f', 's16le', '-']); return pcm.length / 96; }
47
+ export async function videoFramePeriod(path) {
48
+ const data = JSON.parse((await execute('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_frames', '-show_entries', 'frame=best_effort_timestamp_time,duration_time', '-of', 'json', path])).toString());
49
+ const frames = data.frames;
50
+ let maximum = 0;
51
+ for (let index = 0; index < frames.length; index++) {
52
+ maximum = Math.max(maximum, Number(frames[index].duration_time ?? 0) * 1000);
53
+ if (index > 0)
54
+ maximum = Math.max(maximum, (Number(frames[index].best_effort_timestamp_time) - Number(frames[index - 1].best_effort_timestamp_time)) * 1000);
55
+ }
56
+ return Math.ceil(maximum);
57
+ }
@@ -0,0 +1,2 @@
1
+ import type { ImageOverlay } from './contracts.js';
2
+ export declare function loadOverlayImage(overlay: Pick<ImageOverlay, 'id' | 'src'>, expectedHash?: string): Promise<import("@napi-rs/canvas").Image>;
@@ -0,0 +1,58 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { extname } from 'node:path';
3
+ import { loadImage } from '@napi-rs/canvas';
4
+ import { SaxesParser } from 'saxes';
5
+ import { ProductionError } from './errors.js';
6
+ import { digest } from './media.js';
7
+ const pngSignature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
8
+ const svgElements = new Set(['svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon']);
9
+ const svgAttributes = new Set([
10
+ 'xmlns', 'viewBox', 'width', 'height', 'preserveAspectRatio',
11
+ 'd', 'points', 'x', 'y', 'x1', 'x2', 'y1', 'y2', 'rx', 'ry', 'cx', 'cy', 'r',
12
+ 'transform', 'fill', 'fill-rule', 'fill-opacity', 'stroke', 'stroke-width',
13
+ 'stroke-opacity', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit',
14
+ 'stroke-dasharray', 'stroke-dashoffset', 'opacity',
15
+ ]);
16
+ const svgPaint = /^(?:none|#[\da-f]{3,8}|[a-z]+|rgba?\([\d.%,\s]+\))$/i;
17
+ function validateSvg(source) {
18
+ const parser = new SaxesParser();
19
+ let depth = 0;
20
+ parser.on('doctype', () => { throw new Error('SVG document types are unsupported'); });
21
+ parser.on('processinginstruction', () => { throw new Error('SVG processing instructions are unsupported'); });
22
+ parser.on('cdata', () => { throw new Error('SVG CDATA is unsupported'); });
23
+ parser.on('text', text => { if (text.trim())
24
+ throw new Error('SVG text is unsupported. Convert text to paths.'); });
25
+ parser.on('opentag', tag => {
26
+ if (!svgElements.has(tag.name) || (tag.name === 'svg') !== (depth === 0)) {
27
+ throw new Error(`Unsupported SVG element <${tag.name}>`);
28
+ }
29
+ depth++;
30
+ for (const [name, value] of Object.entries(tag.attributes)) {
31
+ if (!svgAttributes.has(name) ||
32
+ (name === 'xmlns' && (depth !== 1 || value !== 'http://www.w3.org/2000/svg')) ||
33
+ ((name === 'fill' || name === 'stroke') && !svgPaint.test(value.trim()))) {
34
+ throw new Error(`Unsupported SVG attribute or value for ${name}`);
35
+ }
36
+ }
37
+ });
38
+ parser.on('closetag', () => { depth--; });
39
+ parser.write(source).close();
40
+ }
41
+ export async function loadOverlayImage(overlay, expectedHash) {
42
+ try {
43
+ const bytes = await readFile(overlay.src);
44
+ if (expectedHash !== undefined && digest(bytes) !== expectedHash)
45
+ throw new Error('Asset changed during this run. Start a new run.');
46
+ if (extname(overlay.src).toLowerCase() === '.svg')
47
+ validateSvg(bytes.toString('utf8'));
48
+ else if (!bytes.subarray(0, pngSignature.length).equals(pngSignature))
49
+ throw new Error('Expected PNG image data');
50
+ const image = await loadImage(bytes);
51
+ if (!image.width || !image.height)
52
+ throw new Error('Image must have positive dimensions');
53
+ return image;
54
+ }
55
+ catch (error) {
56
+ throw new ProductionError('OVERLAY_ASSET', `Overlay ${overlay.id}: cannot read ${overlay.src}: ${error.message}`);
57
+ }
58
+ }
@@ -0,0 +1,50 @@
1
+ import type { ProgressReporter } from './contracts.js';
2
+ export type Options = {
3
+ command: string;
4
+ storyboard?: string;
5
+ run?: string;
6
+ cache?: string;
7
+ output?: string;
8
+ resume?: boolean;
9
+ export?: string;
10
+ verify_timing?: boolean;
11
+ timeout_ms: number;
12
+ progress?: ProgressReporter;
13
+ };
14
+ export declare function produce(options: Options): Promise<{
15
+ version: number;
16
+ command: string;
17
+ status: string;
18
+ artifacts: Record<string, string>;
19
+ warnings: string[];
20
+ completed_stages: string[];
21
+ run_id: string | undefined;
22
+ timing_status: string;
23
+ } | {
24
+ inspection: {
25
+ annotation_targets: {
26
+ slide: string;
27
+ targets: {
28
+ identity: string;
29
+ description: string;
30
+ }[];
31
+ }[] | undefined;
32
+ slides: {
33
+ id: string;
34
+ index: number;
35
+ clicks: number;
36
+ clicks_known?: boolean;
37
+ }[];
38
+ media_ids: string[];
39
+ files: string[];
40
+ capabilities: string[];
41
+ };
42
+ version: number;
43
+ command: string;
44
+ status: string;
45
+ artifacts: Record<string, string>;
46
+ warnings: string[];
47
+ completed_stages: string[];
48
+ run_id: string | undefined;
49
+ timing_status: string;
50
+ }>;
@@ -0,0 +1,257 @@
1
+ import { mkdir, readdir, rm } from 'node:fs/promises';
2
+ import { join, resolve } from 'node:path';
3
+ import { loadStoryboard, fingerprint } from './storyboard.js';
4
+ import { presentationAdapter, ttsAdapters } from './adapters/registry.js';
5
+ import { generateSpeech } from './speech.js';
6
+ import { resolveTiming } from './timing.js';
7
+ import { Run, filesIn } from './run.js';
8
+ import { json, saveJson, execute, executionScope, hashFile } from './media.js';
9
+ import { assemble } from './assembly.js';
10
+ import { configuredLicense } from './executables.js';
11
+ import { requireCondition, ProductionError } from './errors.js';
12
+ export async function produce(options) {
13
+ let run;
14
+ let lock;
15
+ let activeAdapter;
16
+ let interrupted = false;
17
+ const controller = new AbortController();
18
+ const interrupt = () => { interrupted = true; controller.abort(); void activeAdapter?.cleanup().catch(() => { }); };
19
+ process.once('SIGINT', interrupt);
20
+ process.once('SIGTERM', interrupt);
21
+ try {
22
+ options.progress?.('Validating inputs');
23
+ if (options.command === 'assemble') {
24
+ requireCondition(options.run, 'RUN_REQUIRED', 'assemble requires --run');
25
+ try {
26
+ options.storyboard = (await json(join(resolve(options.run), 'manifest.json'))).storyboard;
27
+ }
28
+ catch {
29
+ throw new ProductionError('RUN_MANIFEST', 'assemble needs a readable run manifest');
30
+ }
31
+ }
32
+ requireCondition(options.storyboard, 'STORYBOARD_REQUIRED', `${options.command} requires --storyboard`);
33
+ const source = resolve(options.storyboard);
34
+ const story = await loadStoryboard(source);
35
+ const overlays = story.overlays ?? [];
36
+ const adapter = presentationAdapter(story.deck);
37
+ const inspection = await adapter.inspect(story.deck);
38
+ adapter.validate(story, inspection);
39
+ for (const segment of story.narration) {
40
+ const voice = segment.voice ?? story.voice;
41
+ requireCondition(voice, 'VOICE_REQUIRED', `Narration ${segment.id} needs a voice`);
42
+ const tts = ttsAdapters.get(voice.provider);
43
+ requireCondition(tts, 'TTS_ADAPTER', `Unsupported TTS provider ${voice.provider}`, 3);
44
+ tts.validate(voice);
45
+ }
46
+ const result = { version: 1, command: options.command, status: 'completed', artifacts: {}, warnings: story.cues.length || story.annotations?.length ||
47
+ overlays.some(overlay => overlay.visible?.some(interval => typeof interval.start !== 'number' || typeof interval.end !== 'number')) ? ['Phrase cues require paired speech alignment at resolution.'] : [], completed_stages: [], run_id: undefined, timing_status: 'not_evaluated' };
48
+ if (story.cues.some(cue => cue.action.type === 'slide'))
49
+ result.warnings.push('Phrase-driven navigation requires reveal target checks after resolution.');
50
+ if (inspection.slides.some(slide => slide.clicks_known === false))
51
+ result.warnings.push('Slides without explicit click bounds require runtime reveal checks before recording.');
52
+ if (options.command === 'inspect') {
53
+ requireCondition(adapter.inspectTargets, 'ANNOTATION_CAPABILITY', `Adapter ${adapter.id} does not expose annotation targets`, 3);
54
+ activeAdapter = adapter;
55
+ try {
56
+ const annotation_targets = await adapter.inspectTargets(story);
57
+ controller.signal.throwIfAborted();
58
+ return { ...result, inspection: { ...inspection, annotation_targets } };
59
+ }
60
+ finally {
61
+ await adapter.cleanup();
62
+ activeAdapter = undefined;
63
+ }
64
+ }
65
+ const inputs = [...inspection.files, ...story.media.map(media => media.src), ...overlays.map(overlay => overlay.src)];
66
+ if (options.command === 'validate') {
67
+ const fingerprints = await fingerprint(source, inputs);
68
+ await validateOverlayAssets(fingerprints.inputs);
69
+ controller.signal.throwIfAborted();
70
+ return result;
71
+ }
72
+ async function validateOverlayAssets(hashes) {
73
+ if (!overlays.length)
74
+ return;
75
+ const { loadOverlayImage } = await import('./overlay-assets.js');
76
+ const assets = new Map(overlays.map(overlay => [overlay.src, overlay]));
77
+ for (const overlay of assets.values())
78
+ await loadOverlayImage(overlay, hashes[overlay.src]);
79
+ }
80
+ requireCondition(options.run, 'RUN_REQUIRED', `${options.command} requires --run`);
81
+ const directory = resolve(options.run);
82
+ if (options.command === 'build' && !options.resume) {
83
+ let entries = [];
84
+ try {
85
+ entries = await readdir(directory);
86
+ }
87
+ catch (error) {
88
+ if (error.code !== 'ENOENT')
89
+ throw error;
90
+ }
91
+ requireCondition(entries.length === 0, 'NEW_RUN_REQUIRED', 'build requires a new or empty directory. Use --resume for unchanged inputs.');
92
+ }
93
+ await mkdir(directory, { recursive: true });
94
+ lock = join(directory, '.lock');
95
+ try {
96
+ await mkdir(lock);
97
+ }
98
+ catch {
99
+ lock = undefined;
100
+ throw new ProductionError('RUN_LOCKED', 'Another invocation owns this run, or an interrupted process left .lock.');
101
+ }
102
+ const fingerprints = await fingerprint(source, inputs);
103
+ if (options.command === 'build' || options.command === 'record')
104
+ await validateOverlayAssets(fingerprints.inputs);
105
+ run = await Run.open(directory, source, fingerprints.inputs, fingerprints.input_hash);
106
+ result.run_id = run.manifest.run_id;
107
+ const recordedMode = run.manifest.verify_timing ?? (run.manifest.stages.record ? true : undefined);
108
+ const production = { verify_timing: options.verify_timing ?? recordedMode ?? false };
109
+ if (['build', 'record', 'assemble'].includes(options.command)) {
110
+ requireCondition(recordedMode === undefined || recordedMode === production.verify_timing, 'RUN_MODE_MISMATCH', 'Timing verification differs from this run. Start a new run directory.');
111
+ run.manifest.verify_timing = production.verify_timing;
112
+ await run.save();
113
+ options.progress?.(production.verify_timing ? 'Timing verification enabled' : 'Timing verification skipped; the user reviews the video');
114
+ }
115
+ requireCondition(!options.output || !run.manifest.output || resolve(options.output) === run.manifest.output, 'OUTPUT_MISMATCH', 'Run is bound to a different output path');
116
+ const speechPath = join(directory, 'speech/manifest.json');
117
+ const schedulePath = join(directory, 'timing/schedule.json');
118
+ const visualPath = join(directory, 'recording/visual.json');
119
+ const reportPath = join(directory, 'assembly/report.json');
120
+ const selected = options.command === 'build' ? ['tts', 'resolve', 'record', 'assemble'] : [options.command];
121
+ const licensed = selected.includes('assemble') && (run.manifest.assembly_licensed ??
122
+ (run.manifest.stages.assemble?.status === 'completed' || configuredLicense()));
123
+ for (const stage of selected) {
124
+ const reused = run.manifest.stages[stage]?.status === 'completed';
125
+ const labels = { validate: 'Input validation', tts: 'Speech generation', resolve: 'Timing resolution', record: 'Presentation preparation', assemble: 'Assembly and encoding' };
126
+ options.progress?.(reused ? `Verifying saved ${stage}` : labels[stage]);
127
+ if (interrupted)
128
+ throw new ProductionError('INTERRUPTED', 'Production interrupted', 130);
129
+ if (stage !== 'tts')
130
+ await run.verify('tts');
131
+ if (stage === 'record' && run.manifest.stages.resolve?.status === 'completed')
132
+ await run.verify('resolve');
133
+ if (stage === 'assemble') {
134
+ await run.verify('resolve');
135
+ await run.verify('record');
136
+ }
137
+ if (stage === 'record' && run.manifest.stages.record?.status !== 'completed') {
138
+ let existing = [];
139
+ try {
140
+ existing = await filesIn(join(directory, 'recording'));
141
+ }
142
+ catch (error) {
143
+ if (error.code !== 'ENOENT')
144
+ throw error;
145
+ }
146
+ requireCondition(existing.length === 0, 'RECORD_RETRY_NEW_RUN', 'Recording evidence already exists. Start a new run to preserve this attempt.');
147
+ }
148
+ const artifacts = [];
149
+ const operation = async () => {
150
+ if (stage === 'tts') {
151
+ const speech = await generateSpeech(story, join(directory, 'speech'), ttsAdapters, options.cache, options.progress);
152
+ artifacts.push(speechPath, ...speech.assets.map(asset => asset.audio));
153
+ }
154
+ if (stage === 'resolve') {
155
+ const schedule = await resolveTiming(story, await json(speechPath));
156
+ adapter.validate(story, inspection, schedule);
157
+ await saveJson(schedulePath, schedule);
158
+ artifacts.push(schedulePath);
159
+ }
160
+ if (stage === 'record') {
161
+ const schedule = await resolveTiming(story, await json(speechPath));
162
+ if (run.manifest.stages.resolve?.status === 'completed') {
163
+ await run.verify('resolve');
164
+ requireCondition(JSON.stringify(schedule) === JSON.stringify(await json(schedulePath)), 'SCHEDULE_MISMATCH', 'Resolved schedule changed');
165
+ }
166
+ else {
167
+ await saveJson(schedulePath, schedule);
168
+ run.manifest.stages.resolve = { status: 'completed', artifacts: { [schedulePath]: await hashFile(schedulePath) } };
169
+ await run.save();
170
+ }
171
+ adapter.validate(story, inspection, schedule);
172
+ activeAdapter = adapter;
173
+ try {
174
+ await adapter.prepare(story, schedule, join(directory, 'recording'), production);
175
+ const visual = await adapter.execute(options.progress);
176
+ await saveJson(visualPath, visual);
177
+ requireCondition(visual.timing.status !== 'failed' && (!production.verify_timing || visual.timing.status === 'accepted'), 'TIMING_ACCEPTANCE', 'Presentation artifact has no required timing result', 6);
178
+ artifacts.push(visual.file, ...visual.timing.checks.map(check => check.evidence));
179
+ Object.assign(run.manifest.versions, visual.provenance.dependencies, { [`presentation:${visual.provenance.adapter}`]: visual.provenance.version });
180
+ }
181
+ finally {
182
+ await adapter.cleanup();
183
+ activeAdapter = undefined;
184
+ }
185
+ artifacts.push(...await filesIn(join(directory, 'recording')));
186
+ run.manifest.versions.ffmpeg = (await execute('ffmpeg', ['-version'])).toString().split('\n')[0];
187
+ }
188
+ if (stage === 'assemble') {
189
+ const output = resolve(options.output ?? run.manifest.output ?? join(directory, 'final.mp4'));
190
+ requireCondition(!run.manifest.output || run.manifest.output === output, 'OUTPUT_MISMATCH', 'Run is bound to a different output path');
191
+ run.manifest.output = output;
192
+ run.manifest.assembly_licensed = licensed;
193
+ await run.save();
194
+ try {
195
+ await assemble(story, await json(schedulePath), await json(speechPath), await json(visualPath), join(directory, 'assembly'), output, {
196
+ ...production, licensed, inputHashes: run.manifest.inputs,
197
+ });
198
+ }
199
+ catch (error) {
200
+ if (error instanceof ProductionError && error.exitCode === 3)
201
+ throw new ProductionError('ASSEMBLY', error.message, 7);
202
+ throw error;
203
+ }
204
+ artifacts.push(output, reportPath, ...await filesIn(join(directory, 'assembly')));
205
+ }
206
+ };
207
+ let timedOut = false;
208
+ const timer = setTimeout(() => { timedOut = true; controller.abort(); void activeAdapter?.cleanup().catch(() => { }); }, options.timeout_ms);
209
+ try {
210
+ await run.stage(stage, artifacts, async () => {
211
+ try {
212
+ await executionScope.run(controller.signal, operation);
213
+ }
214
+ catch (error) {
215
+ if (timedOut)
216
+ throw new ProductionError('STAGE_TIMEOUT', `${stage} exceeded ${options.timeout_ms} ms`, stage === 'tts' ? 4 : stage === 'record' ? 5 : 7);
217
+ throw error;
218
+ }
219
+ controller.signal.throwIfAborted();
220
+ });
221
+ }
222
+ finally {
223
+ clearTimeout(timer);
224
+ }
225
+ options.progress?.(`${reused ? 'Reused' : 'Completed'} ${stage}`);
226
+ }
227
+ if (options.export) {
228
+ await run.verify('resolve');
229
+ await run.exportSchedule(options.export, await json(schedulePath));
230
+ }
231
+ result.completed_stages = Object.entries(run.manifest.stages).filter(([, value]) => value?.status === 'completed').map(([key]) => key);
232
+ if (result.completed_stages.includes('tts'))
233
+ result.artifacts.speech = speechPath;
234
+ if (result.completed_stages.includes('resolve'))
235
+ result.artifacts.schedule = schedulePath;
236
+ if (result.completed_stages.includes('record')) {
237
+ result.artifacts.capture = visualPath;
238
+ result.timing_status = (await json(visualPath)).timing.status;
239
+ }
240
+ if (result.completed_stages.includes('assemble'))
241
+ result.artifacts.video = run.manifest.output;
242
+ if (result.completed_stages.includes('record') && result.timing_status === 'not_evaluated')
243
+ result.warnings.push(result.completed_stages.includes('assemble') ? 'Timing was not verified. The delivered video is ready for user review.' : 'Timing was not verified. Assemble the capture to produce the video.');
244
+ return result;
245
+ }
246
+ catch (error) {
247
+ if (interrupted)
248
+ throw new ProductionError('INTERRUPTED', 'Production interrupted', 130);
249
+ throw error;
250
+ }
251
+ finally {
252
+ process.removeListener('SIGINT', interrupt);
253
+ process.removeListener('SIGTERM', interrupt);
254
+ if (lock)
255
+ await rm(lock, { recursive: true });
256
+ }
257
+ }
@@ -0,0 +1,34 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { Rectangle, ResolvedAnnotation } from '../contracts.js';
3
+ export interface NativePreview {
4
+ request(req: IncomingMessage, res: ServerResponse): Promise<void>;
5
+ }
6
+ export type PreviewSession = {
7
+ url: string;
8
+ } | NativePreview;
9
+ export type PlayerConfig = {
10
+ deck: string;
11
+ duration: number;
12
+ width: number;
13
+ height: number;
14
+ approximate: string[];
15
+ stage: {
16
+ url: string;
17
+ } | {
18
+ annotations: ResolvedAnnotation[];
19
+ };
20
+ };
21
+ export type NativeFrame = {
22
+ position_ms: number;
23
+ status: 'paused' | 'playing' | 'ended';
24
+ viewport: {
25
+ width: number;
26
+ height: number;
27
+ };
28
+ content: Rectangle;
29
+ annotations: {
30
+ id: string;
31
+ bounds: Rectangle;
32
+ }[];
33
+ image: string;
34
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,129 @@
1
+ import { annotationPaint } from '../annotation-paint.js';
2
+ const labels = { loading: 'Loading presentation…', ready: 'Ready', playing: 'Playing', paused: 'Paused', ended: 'Finished', error: 'Playback failed' };
3
+ const stage = document.querySelector('#stage');
4
+ const status = document.querySelector('#status');
5
+ const clock = document.querySelector('#clock');
6
+ const progress = document.querySelector('#progress');
7
+ const play = document.querySelector('#play');
8
+ const pause = document.querySelector('#pause');
9
+ const restart = document.querySelector('#restart');
10
+ function time(ms) {
11
+ const seconds = Math.floor(ms / 1000);
12
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;
13
+ }
14
+ function display(state, elapsed, message) {
15
+ const label = message || labels[state];
16
+ if (status.textContent !== label)
17
+ status.textContent = label;
18
+ document.body.toggleAttribute('data-error', state === 'error');
19
+ progress.value = elapsed;
20
+ clock.textContent = `${time(elapsed)} / ${time(progress.max)}`;
21
+ play.disabled = state !== 'ready' && state !== 'paused';
22
+ pause.disabled = state !== 'playing';
23
+ restart.disabled = state === 'loading' || state === 'ready';
24
+ }
25
+ function failed(error) {
26
+ display('error', progress.value, error instanceof Error ? error.message : String(error));
27
+ }
28
+ async function request(path, method = 'GET') {
29
+ const response = await fetch(path, { method });
30
+ if (!response.ok)
31
+ throw new Error(await response.text() || `Preview server returned ${response.status}`);
32
+ return response.json();
33
+ }
34
+ function slidevPlayer(url, width, height) {
35
+ const frame = document.createElement('iframe');
36
+ frame.title = 'Slide presentation';
37
+ frame.tabIndex = -1;
38
+ frame.allow = "screen-wake-lock; autoplay 'none'; microphone 'none'; camera 'none'";
39
+ frame.style.width = `${width}px`;
40
+ frame.style.height = `${height}px`;
41
+ frame.style.transformOrigin = 'top left';
42
+ const resize = () => { frame.style.transform = `scale(${stage.clientWidth / width})`; };
43
+ new ResizeObserver(resize).observe(stage);
44
+ resize();
45
+ const origin = new URL(url).origin;
46
+ const send = (action) => frame.contentWindow?.postMessage({ type: 'slidevideo-preview', action }, origin);
47
+ window.addEventListener('message', event => {
48
+ if (event.source !== frame.contentWindow || event.origin !== origin)
49
+ return;
50
+ const data = event.data;
51
+ if (data?.type === 'slidevideo-preview-state' && Object.hasOwn(labels, data.status)) {
52
+ display(data.status, data.elapsedMs, data.message);
53
+ }
54
+ });
55
+ frame.addEventListener('load', () => send('hello'));
56
+ frame.src = url;
57
+ stage.append(frame);
58
+ return send;
59
+ }
60
+ function nativePlayer(annotations) {
61
+ const canvas = document.createElement('canvas');
62
+ canvas.setAttribute('aria-label', 'PowerPoint presentation');
63
+ const context = canvas.getContext('2d');
64
+ stage.append(canvas);
65
+ const markers = new Map(annotations.map(marker => [marker.id, marker]));
66
+ let refreshTimer;
67
+ let revision = 0;
68
+ async function refresh(current) {
69
+ const frame = await request('/native/frame');
70
+ const image = new Image();
71
+ image.src = frame.image;
72
+ await image.decode();
73
+ if (current !== revision)
74
+ return;
75
+ if (canvas.width !== frame.viewport.width)
76
+ canvas.width = frame.viewport.width;
77
+ if (canvas.height !== frame.viewport.height)
78
+ canvas.height = frame.viewport.height;
79
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
80
+ for (const { id, bounds } of frame.annotations) {
81
+ const marker = markers.get(id);
82
+ if (!marker)
83
+ throw new Error(`Unknown native annotation ${id}`);
84
+ const fill = annotationPaint(marker, { ...frame, bounds });
85
+ for (const paint of [fill, ...(fill.bottom_border ? [fill.bottom_border] : [])]) {
86
+ context.save();
87
+ context.globalAlpha = paint.opacity;
88
+ context.globalCompositeOperation = paint.blend;
89
+ context.fillStyle = paint.color;
90
+ const { x, y, width, height } = paint.rectangle;
91
+ context.fillRect(x, y, width, height);
92
+ context.restore();
93
+ }
94
+ }
95
+ display(frame.status, frame.position_ms);
96
+ refreshTimer = window.setTimeout(() => refresh(current).catch(failed), frame.status === 'playing' ? 16 : 500);
97
+ }
98
+ void refresh(revision).catch(failed);
99
+ return async (command) => {
100
+ clearTimeout(refreshTimer);
101
+ const current = ++revision;
102
+ try {
103
+ await request(`/native/control?command=${command}`, 'POST');
104
+ if (current === revision)
105
+ await refresh(current);
106
+ }
107
+ catch (error) {
108
+ failed(error);
109
+ }
110
+ };
111
+ }
112
+ try {
113
+ const config = await request('/config.json');
114
+ document.getElementById('deck').textContent = config.deck;
115
+ stage.style.setProperty('--ratio', String(config.width / config.height));
116
+ progress.max = config.duration;
117
+ if (config.approximate.length) {
118
+ const pacing = document.getElementById('pacing');
119
+ pacing.textContent = `Estimated narration timing (150 words/min): ${config.approximate.join(', ')}`;
120
+ pacing.hidden = false;
121
+ }
122
+ const command = 'url' in config.stage ? slidevPlayer(config.stage.url, config.width, config.height) : nativePlayer(config.stage.annotations);
123
+ play.onclick = () => command('play');
124
+ pause.onclick = () => command('pause');
125
+ restart.onclick = () => command('restart');
126
+ }
127
+ catch (error) {
128
+ failed(error);
129
+ }
@@ -0,0 +1 @@
1
+ export declare function servePreview(storyboard: string, cache: string | undefined, port: number, ready: (url: string, approximate: string[]) => void): Promise<void>;