@alpha2-sh/editor 0.5.3 → 0.6.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 (39) hide show
  1. package/README.md +58 -1
  2. package/dist/browser/bridge.js +275 -52
  3. package/dist/browser/jobs.d.ts +17 -0
  4. package/dist/browser/jobs.js +40 -0
  5. package/dist/browser/resources.d.ts +9 -4
  6. package/dist/browser/resources.js +17 -5
  7. package/dist/browser/runtime/assets.d.ts +14 -2
  8. package/dist/browser/runtime/assets.js +37 -27
  9. package/dist/browser/runtime/audio.d.ts +12 -2
  10. package/dist/browser/runtime/audio.js +124 -14
  11. package/dist/browser/runtime/engine.js +8 -1
  12. package/dist/browser/runtime/exporter.d.ts +2 -1
  13. package/dist/browser/runtime/exporter.js +15 -4
  14. package/dist/browser/runtime/preview-utils.d.ts +12 -0
  15. package/dist/browser/runtime/preview-utils.js +45 -0
  16. package/dist/browser/runtime/sources.js +11 -34
  17. package/dist/browser/types.d.ts +105 -19
  18. package/dist/browser/worker.d.ts +4 -2
  19. package/dist/browser/worker.js +73 -24
  20. package/dist/core/commands.d.ts +46 -3
  21. package/dist/core/commands.js +212 -40
  22. package/dist/core/compositions.d.ts +27 -0
  23. package/dist/core/compositions.js +43 -0
  24. package/dist/core/data.d.ts +34 -0
  25. package/dist/core/data.js +69 -0
  26. package/dist/core/document.d.ts +10 -1
  27. package/dist/core/document.js +127 -6
  28. package/dist/core/keyframes.d.ts +3 -2
  29. package/dist/core/keyframes.js +6 -2
  30. package/dist/core/sameness.d.ts +6 -0
  31. package/dist/core/sameness.js +42 -0
  32. package/dist/core/session.d.ts +85 -7
  33. package/dist/core/session.js +124 -13
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.js +1 -0
  36. package/dist/native-client/index.d.ts +2 -2
  37. package/dist/native-client/index.js +2 -2
  38. package/dist/ports/index.d.ts +5 -4
  39. package/package.json +3 -3
@@ -1,3 +1,15 @@
1
1
  export function containRect(sourceWidth: any, sourceHeight: any, width: any, height: any): number[];
2
2
  export function previewFrameIndex(seconds: any, fps: any): number;
3
+ /**
4
+ * Loads `video` and resolves once its first frame is available. Rejects with the element's error,
5
+ * with a timeout after `timeoutMs` of active time (a frozen page does not count), or with
6
+ * `signal`'s reason once it aborts. Its listeners are removed on every path.
7
+ */
8
+ export function loadedOrFailed(video: any, { signal, timeoutMs }?: {
9
+ timeoutMs?: number | undefined;
10
+ }): Promise<any>;
11
+ /** Releases a media element's media. */
12
+ export function unloadVideo(video: any): void;
3
13
  export function seekVideoFrame(video: any, seconds: any, tolerance?: number): Promise<void>;
14
+ /** Active time a media element may take to load its first frame. */
15
+ export const MEDIA_LOAD_TIMEOUT_MS: 10000;
@@ -16,6 +16,51 @@ export function containRect(sourceWidth, sourceHeight, width, height) {
16
16
  export function previewFrameIndex(seconds, fps) {
17
17
  return Math.floor(seconds * fps + 1e-7);
18
18
  }
19
+ /** Active time a media element may take to load its first frame. */
20
+ export const MEDIA_LOAD_TIMEOUT_MS = 10_000;
21
+ /**
22
+ * Loads `video` and resolves once its first frame is available. Rejects with the element's error,
23
+ * with a timeout after `timeoutMs` of active time (a frozen page does not count), or with
24
+ * `signal`'s reason once it aborts. Its listeners are removed on every path.
25
+ */
26
+ export function loadedOrFailed(video, { signal, timeoutMs = MEDIA_LOAD_TIMEOUT_MS } = {}) {
27
+ return new Promise((resolve, reject) => {
28
+ const timer = new AbortController();
29
+ const cleanup = () => {
30
+ timer.abort();
31
+ video.removeEventListener("loadeddata", ready);
32
+ video.removeEventListener("error", failed);
33
+ signal?.removeEventListener("abort", aborted);
34
+ };
35
+ const ready = () => {
36
+ cleanup();
37
+ resolve();
38
+ };
39
+ const failed = () => {
40
+ cleanup();
41
+ reject(video.error ?? new Error("video load failed"));
42
+ };
43
+ const aborted = () => {
44
+ cleanup();
45
+ reject(signal.reason);
46
+ };
47
+ if (signal?.aborted)
48
+ return reject(signal.reason);
49
+ void activeTimeout(timeoutMs, timer.signal).then(() => {
50
+ cleanup();
51
+ reject(new Error("video load timed out"));
52
+ });
53
+ video.addEventListener("loadeddata", ready, { once: true });
54
+ video.addEventListener("error", failed, { once: true });
55
+ signal?.addEventListener("abort", aborted, { once: true });
56
+ video.load();
57
+ });
58
+ }
59
+ /** Releases a media element's media. */
60
+ export function unloadVideo(video) {
61
+ video.removeAttribute("src");
62
+ video.load();
63
+ }
19
64
  export async function seekVideoFrame(video, seconds, tolerance = 0.001) {
20
65
  if (!video.seeking &&
21
66
  Math.abs(video.currentTime - seconds) <= tolerance &&
@@ -5,10 +5,9 @@
5
5
  // never evicted, even past the budget. Decoder cursors are scoped per clip consumer so overlapping
6
6
  // uses of one source cannot seek each other. An `HTMLVideoElement` seek is the fallback for codecs
7
7
  // WebCodecs cannot open or frames that keep failing.
8
- import { activeTimeout } from "alpha2/active-clock";
9
8
  import { decoderCursorKey } from "alpha2/frame-supply";
10
9
  import { MediabunnyVideoDecoder } from "alpha2/mediabunny";
11
- import { containRect, seekVideoFrame } from "./preview-utils.js";
10
+ import { containRect, loadedOrFailed, seekVideoFrame, unloadVideo, } from "./preview-utils.js";
12
11
  import { decodeStill, stillRaster } from "./still.js";
13
12
  const TICKS_PER_SECOND = 120_000;
14
13
  /** Failed frames in a row, each retried with a reopened decoder, before element seeks take over. */
@@ -697,7 +696,16 @@ export class SourcePixels {
697
696
  });
698
697
  fallback = { sourceId, asset, consumerId, video };
699
698
  this.#seekVideos.set(cursor, fallback);
700
- await waitForLoad(video);
699
+ try {
700
+ await loadedOrFailed(video);
701
+ }
702
+ catch (error) {
703
+ // A broken element would cost every later frame the seek timeout; the next one tries anew.
704
+ if (this.#seekVideos.get(cursor) === fallback)
705
+ this.#seekVideos.delete(cursor);
706
+ unloadVideo(video);
707
+ throw error;
708
+ }
701
709
  }
702
710
  const { video } = fallback;
703
711
  const duration = Number.isFinite(video.duration)
@@ -781,11 +789,6 @@ function closeOpened(decoder) {
781
789
  decoder.video = null;
782
790
  decoder.opening = null;
783
791
  }
784
- /** Releases a fallback seek element's media. */
785
- function unloadVideo(video) {
786
- video.removeAttribute("src");
787
- video.load();
788
- }
789
792
  function premultiplyInPlace(pixels) {
790
793
  for (let index = 0; index < pixels.length; index += 4) {
791
794
  const alpha = pixels[index + 3];
@@ -796,32 +799,6 @@ function premultiplyInPlace(pixels) {
796
799
  pixels[index + 2] = Math.round((pixels[index + 2] * alpha) / 255);
797
800
  }
798
801
  }
799
- function waitForLoad(video) {
800
- return new Promise((resolve, reject) => {
801
- const timer = new AbortController();
802
- const cleanup = () => {
803
- timer.abort();
804
- video.removeEventListener("loadeddata", ready);
805
- video.removeEventListener("error", failed);
806
- };
807
- const ready = () => {
808
- cleanup();
809
- resolve();
810
- };
811
- const failed = () => {
812
- cleanup();
813
- reject(video.error ?? new Error("video load failed"));
814
- };
815
- // Active time, so a page frozen while the element loads does not time out.
816
- void activeTimeout(10_000, timer.signal).then(() => {
817
- cleanup();
818
- reject(new Error("video load timed out"));
819
- });
820
- video.addEventListener("loadeddata", ready, { once: true });
821
- video.addEventListener("error", failed, { once: true });
822
- video.load();
823
- });
824
- }
825
802
  /**
826
803
  * Which open extension source answers `consumerId`'s read of `asset`. Animated images decode in
827
804
  * order and keep only a window of frames, so each reader gets its own; other providers share one
@@ -85,8 +85,10 @@ export interface RuntimeAsset {
85
85
  readonly hasAudio?: boolean;
86
86
  /**
87
87
  * `false` when this browser cannot decode the file's audio (Safari before 26 has no
88
- * `AudioDecoder`). It then plays and exports silent in this session, while the document still
89
- * records the audio for native hosts and other browsers.
88
+ * `AudioDecoder`). It then plays silent in this session, and an export that would write its
89
+ * sound is refused unless `BrowserExportOptions.undecodableAudio` is `silence`; the document
90
+ * still records the audio for native hosts and other browsers. `conform` for an export purpose
91
+ * decodes a trial again and updates it.
90
92
  */
91
93
  readonly audioDecodable?: boolean;
92
94
  /** When `audioDecodable` is `false`, what the trial decode at import found. */
@@ -122,10 +124,12 @@ export interface BrowserMediaAdapter {
122
124
  /**
123
125
  * Stages one file. The bridge stages at most four files of one import at once.
124
126
  *
125
- * Rejects with an `EditorError` coded `unsupported_media` for a file the adapter does not import,
126
- * `unreadable_media` when this browser or an extension provider cannot read it (the reason is the
127
- * message and `cause`), `too_large` for Lottie, dotLottie or SVG past the engine's parse limits
128
- * (`MAX_LOTTIE_DOCUMENT_BYTES`, `MAX_PROVIDER_DOCUMENT_BYTES`, `MAX_SVG_DOCUMENT_BYTES`),
127
+ * Rejects with an `EditorError` coded `unsupported_media` for a file the adapter does not import
128
+ * or a video this browser decodes none of (its `cause` a `DecodeUnavailableError` with the
129
+ * track's `facts`), `unreadable_media` when this browser or an extension provider cannot read it
130
+ * (the reason is the message and `cause`), `too_large` for Lottie, dotLottie or SVG past the
131
+ * engine's parse limits (`MAX_LOTTIE_DOCUMENT_BYTES`, `MAX_PROVIDER_DOCUMENT_BYTES`,
132
+ * `MAX_SVG_DOCUMENT_BYTES`),
129
133
  * `provider_stalled` past `EXTENSIONS_CALL_TIMEOUT_MS`, and when `signal` aborts.
130
134
  */
131
135
  stage(file: File, signal: AbortSignal, options?: {
@@ -158,12 +162,20 @@ export interface BrowserBridgeOptions {
158
162
  /** Defaults to `createMediaAdapter(runtimeAssets)`. */
159
163
  readonly mediaAdapter?: BrowserMediaAdapter;
160
164
  /**
161
- * The most runtime resources (imported media, rasterized text, proxies) held at once,
162
- * default 128. An import past it is refused with `EditorError` `resource_budget`.
165
+ * The most imported media files (videos, images, audio, fonts, LUTs) this session holds at
166
+ * once, default 128. Media removed from the document still counts while undo or redo can bring
167
+ * it back. Rasterized text and adopted proxies are not counted. An import past the limit is
168
+ * refused with `EditorError` `resource_budget` and changes nothing.
163
169
  */
164
170
  readonly resourceLimit?: number;
165
171
  /** `false` renders picture only: no AudioContext opens and playback runs on the wall clock. */
166
172
  readonly audio?: boolean;
173
+ /**
174
+ * Overrides the preview worker's request deadlines (`WorkerPreviewOptions.requestTimeoutMs`).
175
+ * A request past it gives the worker up: the main-thread renderer takes over the surface and
176
+ * `onError` receives one `preview_worker_failed`.
177
+ */
178
+ readonly workerRequestTimeoutMs?: number;
167
179
  /**
168
180
  * Receives errors no caller awaits, such as a failed preview render or audio that did not start.
169
181
  * The bridge keeps running after each.
@@ -287,6 +299,13 @@ export interface BrowserExportOptions {
287
299
  * an `EditorError` `invalid_video_conversion`.
288
300
  */
289
301
  readonly videoConversion?: "engine" | "browser";
302
+ /**
303
+ * What an export does with audible sources whose audio this browser cannot decode
304
+ * (`RuntimeAsset.audioDecodable` `false`): `refuse` (the default) refuses the export before it
305
+ * renders; `silence` writes them silent. The result's `report.silentAudioSources` lists the
306
+ * sources written silent either way (empty when none).
307
+ */
308
+ readonly undecodableAudio?: "refuse" | "silence";
290
309
  }
291
310
  /** Where a browser export writes its file. */
292
311
  export type ExportOutputTarget = {
@@ -385,7 +404,9 @@ export interface BrowserBridge {
385
404
  /** The playhead, in ticks. */
386
405
  readonly tick: number;
387
406
  readonly playing: boolean;
388
- /** Runtime resources currently held (see `BrowserBridgeOptions.resourceLimit`). */
407
+ /**
408
+ * Runtime resources currently held, counted or not (see `BrowserBridgeOptions.resourceLimit`).
409
+ */
389
410
  readonly resourceCount: number;
390
411
  /**
391
412
  * Preview output volume from 0 to 1, a monitor control outside the project and exports. Kept by
@@ -535,8 +556,11 @@ export interface BrowserBridge {
535
556
  * Plays from the playhead at `rate` (negative plays backwards) under a playback `policy`
536
557
  * (default `drop_video_keep_audio`), stopping at the end of the export range (else of the
537
558
  * content), or looping with `loop`. Sound plays only at rate 1 under a policy that allows it;
538
- * when it cannot start within 3 s the picture plays silently and `onError` hears why. Rejects
539
- * for a zero or non-finite rate (`invalid_rate`) and an unknown policy (`invalid_policy`).
559
+ * when it fails to start or cannot start within 3 s the picture plays silently and `onError`
560
+ * hears why (`audio_unavailable`). A source whose stream this browser cannot decode, or which
561
+ * the file it reads (a proxy, say) does not have, plays silent and is reported once; so is a
562
+ * source whose sound does not arrive for a few mixes in a row, until playback starts again.
563
+ * Rejects a zero or non-finite rate (`invalid_rate`) and an unknown policy (`invalid_policy`).
540
564
  */
541
565
  play(rate?: number, options?: {
542
566
  loop?: boolean;
@@ -593,9 +617,55 @@ export interface BrowserBridge {
593
617
  * ready (`ConformError`) or the document does not compile.
594
618
  */
595
619
  nativeAssets(document?: import("../core/document.js").EditorDocument, options?: Pick<BrowserExportOptions, "media">): Promise<import("../native-client/index.js").NativeAsset[]>;
620
+ /**
621
+ * Runs an engine edit operation (`remove_ranges`, `split_at`, `bake`) on the committed document
622
+ * with this runtime's engine and commits it as one undo step (`EditorSession.applyEdit`), with
623
+ * `then` in the same step. Waits for the engine to load, so it can be called right away.
624
+ *
625
+ * Rejects with the engine's refusal (an `Alpha2Error` whose `details.refusal` names it), with
626
+ * `stale_edit` when the document changed while the engine loaded, with what
627
+ * `EditorSession.applyEdit` refuses, when `signal` aborts before the edit runs, and after the
628
+ * bridge is disposed (`disposed`).
629
+ */
630
+ applyEdit(request: import("alpha2/apply-edit").EditRequest, options?: {
631
+ readonly then?: readonly import("../core/commands.js").Command[];
632
+ readonly label?: string;
633
+ readonly signal?: AbortSignal;
634
+ }): Promise<{
635
+ readonly document: import("../core/document.js").EditorDocument;
636
+ readonly report: import("alpha2/apply-edit").EditReport;
637
+ }>;
638
+ /**
639
+ * Runs an extractor over a source's original media on this page (`runExtractor` from
640
+ * `alpha2/extract`), with an app's `extractor` or a `plugin` it loads (`loadPlugin` from
641
+ * `alpha2/plugins`, manifest and SHA-256 pinned). Resolves with the result and the read taken
642
+ * when the run started; commit them with `EditorSession.applyExtraction(result, { read })`.
643
+ *
644
+ * Rejects without exactly one of `plugin` and `extractor` (`invalid_command`), for a timeline
645
+ * input (`unsupported_media`), without the source's original in this session (`missing_asset`),
646
+ * with the plugin loader's and the extractor's errors (`PLUGIN_*`, `INVALID_INPUT`,
647
+ * `INVALID_EMIT`, `EXTRACTOR_FAILED`, `DECODE_UNAVAILABLE`), with `cancelled` when `signal`
648
+ * aborts or the bridge is disposed, and after disposal (`disposed`).
649
+ */
650
+ extract(run: import("alpha2/extractor").ExtractRun, options: {
651
+ readonly plugin?: {
652
+ readonly manifest: string | URL;
653
+ readonly sha256: string;
654
+ /** The most linear memory the module may have; the loader's default when left out. */
655
+ readonly memoryBytes?: number;
656
+ };
657
+ readonly extractor?: import("alpha2/extractor").Extractor;
658
+ readonly signal?: AbortSignal;
659
+ readonly onProgress?: (progress: import("alpha2/extractor").ExtractProgress) => void;
660
+ }): Promise<{
661
+ readonly result: import("alpha2/extractor").ExtractResult;
662
+ readonly read: import("../core/session.js").ExtractionRead;
663
+ }>;
596
664
  /**
597
665
  * Whether the document's media is ready for `purpose`, as the engine decides from this session's
598
- * originals and kept proxies.
666
+ * originals and kept proxies. Its `stale_data` lists the data sets whose `made_from` no longer
667
+ * matches their source's original (`data`, `source` and the differing `fields`); the set's own
668
+ * `made_by` in the project says how to run its extractor again. Nothing is fixed automatically.
599
669
  */
600
670
  conform(purpose: MediaPurpose, document?: import("../core/document.js").EditorDocument): Promise<ConformReport>;
601
671
  /**
@@ -604,8 +674,10 @@ export interface BrowserBridge {
604
674
  * export that starts restarts the conversion from 0 once it ends. Rejects for a source without a
605
675
  * single video file (`unsupported_media`, including HDR video), without its original in this
606
676
  * session (`missing_asset`), with a proxy already being made (`proxy_busy`), when the conversion
607
- * makes no progress for 30 s (`proxy_stalled`; preview keeps reading the original), or when
608
- * `signal` aborts.
677
+ * makes no progress for 30 s (`proxy_stalled`; preview keeps reading the original), when
678
+ * `signal` aborts, or when the bridge is disposed (`disposed`). Opening another project does not
679
+ * stop it: the proxy is kept in origin storage and used only while a document this session can
680
+ * show has that media.
609
681
  */
610
682
  generateProxy(id: string, options?: {
611
683
  signal?: AbortSignal;
@@ -649,7 +721,9 @@ export interface BrowserBridge {
649
721
  /**
650
722
  * Makes preview read a fresh proxy wherever a source has one (`proxies`), or the original
651
723
  * wherever it is online (`original`, the default). Preview only: an export reads what its own
652
- * `media` says. {@link BrowserBridge.proxyStatus} reports what each source reads.
724
+ * `media` says. {@link BrowserBridge.proxyStatus} reports what each source reads. A kept proxy
725
+ * that cannot be staged or held goes to `onError` once (`EditorError` `proxy_unavailable`), and
726
+ * its source reads the original.
653
727
  */
654
728
  setPreviewMedia(media: "original" | "proxies"): void;
655
729
  /** What {@link BrowserBridge.setPreviewMedia} last set. */
@@ -691,10 +765,13 @@ export interface BrowserBridge {
691
765
  * (`export_busy`), `frameRate` is not one the engine reads (`invalid_frame_rate`), `videoDecode`
692
766
  * is not `auto` or `software` (`invalid_video_decode`), `videoConversion` is not `engine` or
693
767
  * `browser` (`invalid_video_conversion`), the asset decisions are not loaded (`conform_pending`),
694
- * the media is not ready (`ConformError`), the document does not compile, or it shows an HDR
768
+ * the media is not ready (`ConformError`), the document does not compile, it shows an HDR
695
769
  * source this browser previews only degraded (`unsupported_media`, its `cause` a
696
- * `PlanarDecodeUnavailableError` naming the sources). Later failures arrive through the job's
697
- * `result`.
770
+ * `PlanarDecodeUnavailableError` naming the sources), `undecodableAudio` is not `refuse` or
771
+ * `silence` (`invalid_undecodable_audio`), or it would write audio this browser cannot decode
772
+ * (`unsupported_media`, its `cause` a `DecodeUnavailableError` and `details.sources` each
773
+ * source's `id`, `name` and import-time `facts`). `conform` for an export purpose decodes a trial
774
+ * of such audio again first. Later failures arrive through the job's `result`.
698
775
  */
699
776
  startExport(options?: BrowserExportOptions): ExportJob;
700
777
  /**
@@ -724,6 +801,12 @@ export interface WorkerPreviewOptions {
724
801
  readonly opaqueEngineFrames?: "refuse" | "present-degraded";
725
802
  /** `"auto"` (the default: a hardware GPU, else the CPU renderer), `"gpu"` or `"cpu"`. */
726
803
  readonly renderer?: "auto" | "gpu" | "cpu";
804
+ /**
805
+ * Milliseconds of active time (a hidden or frozen page does not count) any request waits for
806
+ * its reply. Default 60000 for `init` and `replaceProject`, 30000 for every other call. Past it
807
+ * the call and every later one reject with a fatal `worker_timeout`.
808
+ */
809
+ readonly requestTimeoutMs?: number;
727
810
  }
728
811
  /** The main-thread side of a preview renderer running in a worker. */
729
812
  export interface WorkerPreview {
@@ -776,6 +859,9 @@ export interface WorkerPreview {
776
859
  mix(startSample: number, frames: number): Promise<Float32Array[]>;
777
860
  /** Drops the render in flight; its `seek` resolves with `rendered: false`. */
778
861
  cancel(): Promise<void>;
779
- /** Releases the worker's engine and terminates the worker. Idempotent. */
862
+ /**
863
+ * Asks the worker to release its engine, waits at most one second for its reply, then terminates
864
+ * it and rejects every pending call. Idempotent.
865
+ */
780
866
  dispose(): Promise<void>;
781
867
  }
@@ -16,9 +16,11 @@ export function installEditorWorker(scope: import("./types.js").EditorWorkerScop
16
16
  * worker; `dispose()` terminates it. This port renders picture and mixes audio blocks only, apart
17
17
  * from a bridge's main-thread audio output. Every call waits for `ready`, which rejects if the
18
18
  * worker cannot start its engine; a disposed preview rejects new calls, and a worker error rejects
19
- * every pending one.
19
+ * every pending and later call. A request unanswered past its deadline (active time, see
20
+ * `WorkerPreviewOptions.requestTimeoutMs`) fails the worker the same way, with a fatal
21
+ * `worker_timeout`. `dispose()` waits at most a second for the worker's reply.
20
22
  * @param {Worker} worker
21
23
  * @param {import("./types.js").WorkerPreviewOptions} [options]
22
24
  * @returns {import("./types.js").WorkerPreview}
23
25
  */
24
- export function createWorkerPreview(worker: Worker, { sessionId, runtimeAssets, canvas, bitmapOutput, width, height, videoConversion, opaqueEngineFrames, renderer, }?: import("./types.js").WorkerPreviewOptions): import("./types.js").WorkerPreview;
26
+ export function createWorkerPreview(worker: Worker, { sessionId, runtimeAssets, canvas, bitmapOutput, width, height, videoConversion, opaqueEngineFrames, renderer, requestTimeoutMs, }?: import("./types.js").WorkerPreviewOptions): import("./types.js").WorkerPreview;
@@ -1,8 +1,17 @@
1
1
  import { Alpha2WasmError, serializeError } from "alpha2/worker-error";
2
+ import { withinActiveTime } from "alpha2/active-clock";
2
3
  import { SourcePixels } from "./runtime/sources.js";
3
4
  import { extensionWasmUrls } from "./runtime/extension-import.js";
4
5
  import { AudioWindowSupplier, mixBlock } from "./runtime/audio.js";
5
6
  const INSTALLED = Symbol.for("alpha2.editorWorker");
7
+ /** How long `WorkerPreview.dispose()` waits for the worker's reply before terminating it. */
8
+ const DISPOSE_REPLY_MS = 1000;
9
+ /** Active milliseconds a request may wait for its reply, by type; others take the default. */
10
+ const REQUEST_TIMEOUT_MS = Object.freeze({
11
+ init: 60_000,
12
+ "replace-project": 60_000,
13
+ });
14
+ const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
6
15
  /**
7
16
  * Serves the editor's preview protocol (`createWorkerPreview`) on `scope`, a dedicated worker's
8
17
  * global. Requests run one at a time in arrival order. A `cancel` or `replace-project` stops the
@@ -190,17 +199,34 @@ function serveEditorWorker(scope) {
190
199
  catch {
191
200
  lossReport = undefined;
192
201
  }
193
- scope.postMessage({
194
- ...response,
195
- ok: false,
196
- error: {
197
- ...serializeError(error, false, "worker_error"),
198
- ...(typeof causeCode === "string" ? { causeCode } : {}),
199
- ...(lossReport === undefined ? {} : { lossReport }),
200
- },
201
- });
202
+ const serialized = serializeError(error, false, "worker_error");
203
+ try {
204
+ scope.postMessage({
205
+ ...response,
206
+ ok: false,
207
+ error: {
208
+ ...serialized,
209
+ ...(typeof causeCode === "string" ? { causeCode } : {}),
210
+ ...(lossReport === undefined ? {} : { lossReport }),
211
+ },
212
+ });
213
+ }
214
+ catch {
215
+ // A field that cannot be cloned must not leave the request unanswered.
216
+ scope.postMessage({
217
+ ...response,
218
+ ok: false,
219
+ error: {
220
+ code: "worker_error",
221
+ message: String(serialized.message),
222
+ fatal: serialized.fatal === true,
223
+ },
224
+ });
225
+ }
202
226
  }
203
227
  });
228
+ // One request that fails outside its handler must not stop the ones after it.
229
+ tail = tail.catch(() => { });
204
230
  };
205
231
  return {
206
232
  async dispose() {
@@ -219,13 +245,17 @@ function serveEditorWorker(scope) {
219
245
  * worker; `dispose()` terminates it. This port renders picture and mixes audio blocks only, apart
220
246
  * from a bridge's main-thread audio output. Every call waits for `ready`, which rejects if the
221
247
  * worker cannot start its engine; a disposed preview rejects new calls, and a worker error rejects
222
- * every pending one.
248
+ * every pending and later call. A request unanswered past its deadline (active time, see
249
+ * `WorkerPreviewOptions.requestTimeoutMs`) fails the worker the same way, with a fatal
250
+ * `worker_timeout`. `dispose()` waits at most a second for the worker's reply.
223
251
  * @param {Worker} worker
224
252
  * @param {import("./types.js").WorkerPreviewOptions} [options]
225
253
  * @returns {import("./types.js").WorkerPreview}
226
254
  */
227
- export function createWorkerPreview(worker, { sessionId = crypto.randomUUID(), runtimeAssets = {}, canvas, bitmapOutput = false, width = 16, height = 16, videoConversion, opaqueEngineFrames, renderer, } = {}) {
228
- let nextId = 0, revision = 0, disposed = false;
255
+ export function createWorkerPreview(worker, { sessionId = crypto.randomUUID(), runtimeAssets = {}, canvas, bitmapOutput = false, width = 16, height = 16, videoConversion, opaqueEngineFrames, renderer, requestTimeoutMs, } = {}) {
256
+ let nextId = 0, revision = 0, disposed = false,
257
+ // Set once the worker failed as a whole; every later call rejects with it at once.
258
+ failure = null;
229
259
  const pending = new Map();
230
260
  const rejectAll = (error) => {
231
261
  for (const waiter of pending.values())
@@ -260,10 +290,14 @@ export function createWorkerPreview(worker, { sessionId = crypto.randomUUID(), r
260
290
  waiter.reject(error);
261
291
  }
262
292
  };
263
- worker.onerror = (event) => rejectAll(new Error(event.message));
264
- const call = (type, body = {}, transfer = []) => {
265
- if (disposed)
266
- return Promise.reject(new Error("Worker preview disposed"));
293
+ const fail = (message, code = "worker_error") => {
294
+ failure ??= new Alpha2WasmError({ code, message, fatal: true });
295
+ rejectAll(failure);
296
+ return failure;
297
+ };
298
+ worker.onerror = (event) => fail(event?.message || "The preview worker failed");
299
+ worker.onmessageerror = () => fail("A preview worker reply could not be read");
300
+ const send = (type, body = {}, transfer = []) => {
267
301
  const requestId = ++nextId;
268
302
  return new Promise((resolve, reject) => {
269
303
  pending.set(requestId, { resolve, reject });
@@ -276,6 +310,16 @@ export function createWorkerPreview(worker, { sessionId = crypto.randomUUID(), r
276
310
  }
277
311
  });
278
312
  };
313
+ const call = (type, body, transfer) => {
314
+ if (disposed)
315
+ return Promise.reject(new Error("Worker preview disposed"));
316
+ if (failure)
317
+ return Promise.reject(failure);
318
+ const limit = requestTimeoutMs ??
319
+ REQUEST_TIMEOUT_MS[type] ??
320
+ DEFAULT_REQUEST_TIMEOUT_MS;
321
+ return withinActiveTime(send(type, body, transfer), limit, () => fail(`The preview worker did not answer ${type} within ${limit / 1000} s of active time`, "worker_timeout"));
322
+ };
279
323
  const ready = call("init", {
280
324
  runtimeAssets,
281
325
  bitmapOutput,
@@ -317,15 +361,20 @@ export function createWorkerPreview(worker, { sessionId = crypto.randomUUID(), r
317
361
  async dispose() {
318
362
  if (disposed)
319
363
  return;
320
- try {
321
- await ready;
322
- await call("dispose");
323
- }
324
- finally {
325
- disposed = true;
326
- worker.terminate();
327
- rejectAll(new Error("Worker disposed"));
364
+ disposed = true;
365
+ // The worker releases its engine if it answers in time; terminating frees it either way.
366
+ if (!failure) {
367
+ let timer = 0;
368
+ await Promise.race([
369
+ send("dispose").catch(() => { }),
370
+ new Promise((resolve) => {
371
+ timer = setTimeout(resolve, DISPOSE_REPLY_MS);
372
+ }),
373
+ ]);
374
+ clearTimeout(timer);
328
375
  }
376
+ worker.terminate();
377
+ rejectAll(new Error("Worker disposed"));
329
378
  },
330
379
  };
331
380
  }
@@ -1,5 +1,6 @@
1
1
  import type { InputKey } from "./compositions.js";
2
- import type { Project, Clip, Track, ClipEffect, CaptionCue, Composition, CompositionNode, MediaSource, EffectResource } from "alpha2/project";
2
+ import type { Project, Clip, Track, ClipEffect, CaptionCue, Composition, CompositionNode, MediaSource, EffectResource, DataSet } from "alpha2/project";
3
+ import type { AppliedEdit } from "alpha2/apply-edit";
3
4
  import type { EditorDocument, TrackMetadata, ClipMetadata, AssetDescriptor, Marker, Result, GraphLayout, GraphPosition } from "./document.js";
4
5
  /**
5
6
  * A document while a command applies: its project may hold input as written (a CSS hex color, say)
@@ -234,6 +235,15 @@ export type Command =
234
235
  readonly id: string;
235
236
  readonly ids: readonly string[];
236
237
  }
238
+ /**
239
+ * Gives clip `id` its own copy of its composition tree when another clip, source or group draws
240
+ * part of it, so a graph command on it changes only this clip. Effect commands do this
241
+ * themselves; graph commands name a composition and change every clip that shows it.
242
+ */
243
+ | {
244
+ readonly type: "clip.detachComposition";
245
+ readonly id: string;
246
+ }
237
247
  /** Gives a clip without one a composition that shows its picture. */
238
248
  | {
239
249
  readonly type: "graph.create";
@@ -394,11 +404,32 @@ export type Command =
394
404
  readonly source?: MediaSource;
395
405
  readonly resource?: EffectResource;
396
406
  }
397
- /** Removes a bin asset and its source or effect resource; refused while a clip reads it. */
407
+ /**
408
+ * Removes a bin asset and its source or effect resource; refused while a clip reads it, and
409
+ * (`data_referenced`, with the set ids as `details.dataSets`) while data sets are anchored to it.
410
+ */
398
411
  | {
399
412
  readonly type: "asset.remove";
400
413
  readonly id: string;
401
414
  }
415
+ /**
416
+ * Adds a data set, or replaces the set with its id in place. Undo history keeps a replaced set
417
+ * whole, about its JSON size, so one put of a set near `MAX_DATA_VALUES` (tens of MB) can evict
418
+ * most or all earlier steps under the default `historyByteLimit`.
419
+ */
420
+ | {
421
+ readonly type: "data.put";
422
+ readonly dataSet: DataSet;
423
+ }
424
+ /**
425
+ * Removes a data set. Refused (`data_referenced`, with the places as `details.references`) while
426
+ * a binding, correction or caption track reads it. To keep what they show, apply a `bake` with
427
+ * this command in its `then` (`EditorSession.applyEdit`).
428
+ */
429
+ | {
430
+ readonly type: "data.remove";
431
+ readonly id: string;
432
+ }
402
433
  /** Replaces the document metadata fields the patch has. */
403
434
  | {
404
435
  readonly type: "metadata.update";
@@ -408,13 +439,25 @@ export type Command =
408
439
  export declare function graphNames(document: DraftDocument): Readonly<Record<string, string>>;
409
440
  /** The node editor positions a document stores. */
410
441
  export declare function graphLayout(document: DraftDocument): GraphLayout;
442
+ /**
443
+ * Puts an engine edit result (`alpha2/apply-edit` `AppliedEdit`, computed from `document`'s
444
+ * project) in `document`, then runs `then` on it as one transaction. Clips the edit created get the
445
+ * editor metadata of the clip each was cut from (`report.created[].from`); removed clips lose
446
+ * theirs. Every part the edit left equal to `document`'s keeps `document`'s object, so a locked
447
+ * track the edit did not touch passes the lock check; the rest is the engine's project as written.
448
+ *
449
+ * Never throws. A refusal is `{ ok: false }` with an `EditorError`, `locked` for a change to a
450
+ * locked track, `invalid_result` for a result that does not validate (an engine defect), or the
451
+ * refusal of a `then` command. `document` is not modified, and the result is deep-frozen.
452
+ */
453
+ export declare function executeEditResult(document: EditorDocument, applied: Pick<AppliedEdit, "projectJson" | "report">, then?: readonly Command[]): Result<EditorDocument>;
411
454
  /**
412
455
  * Applies `command` to `document` and validates the result. `gesture` checks only what a pointer
413
456
  * move can change (see `validateDocumentShape`); the gesture validates in full when it commits.
414
457
  *
415
458
  * Never throws: a refusal is `{ ok: false }` with an `EditorError` (`invalid_command`, `locked`, a
416
459
  * validation code, or an edit code from `alpha2/edit`). `document` and `command` are not modified;
417
- * compositions the edit leaves undrawn are removed from the result.
460
+ * compositions the edit leaves undrawn are removed from the result, which is deep-frozen.
418
461
  */
419
462
  export declare function executeCommand(document: EditorDocument, command: Command, { gesture }?: {
420
463
  gesture?: boolean;