@sealpixel/core 1.0.0-rc.20 → 1.0.0-rc.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/session.js CHANGED
@@ -3,9 +3,10 @@ import { compile } from './compile.js';
3
3
  import { SealpixelError } from './errors.js';
4
4
  import * as hist from './history.js';
5
5
  import { InlineRenderer } from './inline-renderer.js';
6
- import { createRegistry } from './registry.js';
6
+ import { createRegistry, parseAppendedOperation } from './registry.js';
7
7
  const hashMismatch = () => new SealpixelError('SOURCE_MISMATCH', 'the saved edit log belongs to a different image (hash differs)');
8
8
  const supersededError = () => new SealpixelError('ABORTED', 'a newer load() replaced this one');
9
+ const disposedError = () => new SealpixelError('ABORTED', 'the session is disposed; create a new session');
9
10
  const EXT = {
10
11
  'image/png': 'png',
11
12
  'image/jpeg': 'jpg',
@@ -66,6 +67,12 @@ export function createEditorSession(options) {
66
67
  let inflight = null;
67
68
  let idleResolvers = [];
68
69
  let disposed = false;
70
+ /**
71
+ * The version at which a load failed. The preview of the restored image
72
+ * keeps the load error on the stage. A later edit changes the version, and
73
+ * its preview clears the error as before.
74
+ */
75
+ let failedLoadVersion = -1;
69
76
  const emit = () => {
70
77
  for (const l of listeners)
71
78
  l(state);
@@ -93,7 +100,7 @@ export function createEditorSession(options) {
93
100
  schedulePreview();
94
101
  };
95
102
  function schedulePreview() {
96
- if (!previewEnabled || state.status !== 'ready')
103
+ if (disposed || !previewEnabled || state.status !== 'ready')
97
104
  return;
98
105
  if (timer)
99
106
  clearTimeout(timer);
@@ -134,7 +141,11 @@ export function createEditorSession(options) {
134
141
  }
135
142
  const preview = { image, geometry, viewGeometry: viewGeometry ?? geometry, version };
136
143
  inflight = null;
137
- set({ preview, previewPending: false, error: null });
144
+ set({
145
+ preview,
146
+ previewPending: false,
147
+ error: version === failedLoadVersion ? state.error : null,
148
+ });
138
149
  settleIdle();
139
150
  return preview;
140
151
  }
@@ -142,7 +153,10 @@ export function createEditorSession(options) {
142
153
  if (inflight?.controller === controller)
143
154
  inflight = null;
144
155
  const e = SealpixelError.from(error);
145
- if (e.name === 'ABORTED' || version !== state.version) {
156
+ // Only an abort that the session caused has a successor that settles
157
+ // `previewPending`. An abort from elsewhere, such as a shared renderer
158
+ // that its host disposed, is reported like any other failure.
159
+ if ((e.name === 'ABORTED' && controller.signal.aborted) || version !== state.version) {
146
160
  settleIdle();
147
161
  return null;
148
162
  }
@@ -152,6 +166,7 @@ export function createEditorSession(options) {
152
166
  }
153
167
  }
154
168
  async function renderDetached(transform, options) {
169
+ ensureAlive();
155
170
  if (state.status !== 'ready') {
156
171
  throw new SealpixelError('NO_SOURCE', 'renderDetached needs a loaded image');
157
172
  }
@@ -173,9 +188,13 @@ export function createEditorSession(options) {
173
188
  throw new SealpixelError('DECODE_FAILED', `${source}: HTTP ${res.status}`);
174
189
  return {
175
190
  bytes: new Uint8Array(await res.arrayBuffer()),
176
- name: source.split('/').pop() ?? null,
191
+ // The query and the fragment are not part of the file name.
192
+ name: source.split(/[?#]/, 1)[0]?.split('/').pop() ?? null,
177
193
  };
178
194
  }
195
+ // A Blob knows its size: refuse a large one before reading it into memory.
196
+ if (source.size > maxClientBytes)
197
+ throw tooLarge(source.size);
179
198
  const name = 'name' in source && typeof source.name === 'string' ? source.name : null;
180
199
  return { bytes: new Uint8Array(await source.arrayBuffer()), name };
181
200
  }
@@ -193,6 +212,9 @@ export function createEditorSession(options) {
193
212
  const index = typeof wrapped?.index === 'number' ? wrapped.index : undefined;
194
213
  return { log, index };
195
214
  }
215
+ function tooLarge(byteLength) {
216
+ return new SealpixelError('TOO_LARGE', `${byteLength} bytes exceed the client limit of ${maxClientBytes}`);
217
+ }
196
218
  /** Runs `task` after every renderer switch that started before it. */
197
219
  function exclusive(task) {
198
220
  const run = loadQueue.then(task);
@@ -205,8 +227,9 @@ export function createEditorSession(options) {
205
227
  * that names an image the renderer does not hold renders wrong pixels.
206
228
  */
207
229
  async function restoreCommitted() {
208
- // Nothing committed: the state is `empty` and nothing renders.
209
- if (!committed)
230
+ // Nothing committed: the state is `empty` and nothing renders. A disposed
231
+ // session renders nothing either.
232
+ if (!committed || disposed)
210
233
  return;
211
234
  try {
212
235
  await loadInto(committed.bytes, committed.id);
@@ -244,6 +267,7 @@ export function createEditorSession(options) {
244
267
  const session = {
245
268
  registry,
246
269
  async load(source, loadOptions = {}) {
270
+ ensureAlive();
247
271
  const generation = ++loadGeneration;
248
272
  const superseded = () => generation !== loadGeneration;
249
273
  if (timer)
@@ -256,9 +280,8 @@ export function createEditorSession(options) {
256
280
  const { bytes, name } = await readBytes(source);
257
281
  if (superseded())
258
282
  throw supersededError();
259
- if (bytes.byteLength > maxClientBytes) {
260
- throw new SealpixelError('TOO_LARGE', `${bytes.byteLength} bytes exceed the client limit of ${maxClientBytes}`);
261
- }
283
+ if (bytes.byteLength > maxClientBytes)
284
+ throw tooLarge(bytes.byteLength);
262
285
  const id = loadOptions.id ?? (name ? name.replace(/\.[^.]+$/, '') : 'image');
263
286
  // Validate what can be validated before the renderer switches.
264
287
  const saved = loadOptions.editLog === undefined ? null : resolveSavedState(loadOptions.editLog);
@@ -271,12 +294,14 @@ export function createEditorSession(options) {
271
294
  return await exclusive(async () => {
272
295
  if (superseded())
273
296
  throw supersededError();
297
+ ensureAlive();
274
298
  const loaded = await loadInto(bytes, id);
275
299
  // The renderer holds the new image now. Until the state commits to
276
300
  // it, any failure puts the renderer back on the committed image.
277
301
  try {
278
302
  if (superseded())
279
303
  throw supersededError();
304
+ ensureAlive();
280
305
  const descriptor = loaded.descriptor;
281
306
  const history = saved
282
307
  ? savedHistory(saved, descriptor, loadOptions.index)
@@ -313,20 +338,29 @@ export function createEditorSession(options) {
313
338
  // renderer switches ahead of it, so the state never says `ready` while
314
339
  // an older load still holds the renderer on another image.
315
340
  await exclusive(async () => {
316
- if (!superseded())
317
- set({ status: state.source ? 'ready' : 'empty', error: e });
341
+ if (superseded())
342
+ return;
343
+ set({ status: state.source ? 'ready' : 'empty', error: e });
344
+ // `load` dropped the preview. The renderer holds the previous image
345
+ // again, so the stage shows it again.
346
+ failedLoadVersion = state.version;
347
+ schedulePreview();
318
348
  });
319
349
  throw e;
320
350
  }
321
351
  },
322
352
  dispatch(op) {
323
353
  ensureReady();
324
- const violation = state.source
325
- ? registry.validateOperation(op, state.document, state.source)
326
- : null;
327
- if (violation)
328
- throw new SealpixelError('OPTION_VIOLATION', `${op.type}: ${violation}`);
329
- setHistory(hist.dispatch(state.history, op));
354
+ const id = op?.id;
355
+ if (typeof id !== 'string' || id === '') {
356
+ throw new SealpixelError('INVALID_EDIT_LOG', 'op has no non-empty string "id"');
357
+ }
358
+ // A retried op is a no-op before any check: its first dispatch already
359
+ // passed them, and the state it applied to may be gone.
360
+ if (state.history.log.ops.some((existing) => existing.id === id))
361
+ return;
362
+ const parsed = parseAppendedOperation(registry, op, state.document, state.source);
363
+ setHistory(hist.dispatch(state.history, parsed));
330
364
  },
331
365
  undo() {
332
366
  setHistory(hist.undo(state.history));
@@ -359,7 +393,7 @@ export function createEditorSession(options) {
359
393
  throw state.error ?? new SealpixelError('ABORTED', 'preview superseded');
360
394
  },
361
395
  whenIdle() {
362
- if (!state.previewPending && !timer && !inflight)
396
+ if (disposed || (!state.previewPending && !timer && !inflight))
363
397
  return Promise.resolve();
364
398
  return new Promise((resolve) => idleResolvers.push(resolve));
365
399
  },
@@ -439,16 +473,28 @@ export function createEditorSession(options) {
439
473
  return { filename, result };
440
474
  },
441
475
  dispose() {
476
+ if (disposed)
477
+ return;
442
478
  disposed = true;
443
479
  if (timer)
444
480
  clearTimeout(timer);
481
+ timer = null;
445
482
  inflight?.controller.abort();
483
+ inflight = null;
446
484
  listeners.clear();
485
+ // No preview runs any more: settle every `whenIdle` that waits for one.
486
+ set({ previewPending: false });
487
+ settleIdle();
447
488
  if (ownsRenderer)
448
489
  renderer.dispose();
449
490
  },
450
491
  };
492
+ function ensureAlive() {
493
+ if (disposed)
494
+ throw disposedError();
495
+ }
451
496
  function ensureReady() {
497
+ ensureAlive();
452
498
  if (state.status !== 'ready')
453
499
  throw new SealpixelError('NO_SOURCE', 'load an image first');
454
500
  }
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAMA,OAAO,EAAsB,eAAe,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9E,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,KAAK,IAAI,MAAM,cAAc,CAAC;AACrC,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAGtD,OAAO,EAAE,cAAc,EAAiB,MAAM,eAAe,CAAC;AAoJ9D,MAAM,YAAY,GAAG,GAAG,EAAE,CACxB,IAAI,cAAc,CAChB,iBAAiB,EACjB,gEAAgE,CACjE,CAAC;AAEJ,MAAM,eAAe,GAAG,GAAG,EAAE,CAAC,IAAI,cAAc,CAAC,SAAS,EAAE,kCAAkC,CAAC,CAAC;AAEhG,MAAM,GAAG,GAA4C;IACnD,WAAW,EAAE,KAAK;IAClB,YAAY,EAAE,KAAK;IACnB,YAAY,EAAE,MAAM;CACrB,CAAC;AAEF,MAAM,UAAU,mBAAmB,CAAC,OAAuB;IACzD,MAAM,QAAQ,GAAG,cAAc,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IACjD,MAAM,mBAAmB,GAAG,OAAO,CAAC,MAAM,EAAE,mBAAmB,IAAI,EAAE,CAAC;IACtE,MAAM,cAAc,GAAG,OAAO,CAAC,MAAM,EAAE,cAAc,IAAI,IAAI,CAAC;IAC9D,MAAM,QAAQ,GACZ,OAAO,CAAC,QAAQ;QAChB,IAAI,cAAc,CAAC;YACjB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,mBAAmB;YACnB,kBAAkB,EAAE,OAAO,CAAC,WAAW,EAAE,OAAO,IAAI,IAAI;SACzD,CAAC,CAAC;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AC,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;QACnF,OAAO;IACT,CAAC;IACD,MAAM,GAAG,GAAG,GAAG,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;IACtC,IAAI,CAAC;QACH,MAAM,CAAC,GAAG,QAAQ,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;QACtC,CAAC,CAAC,IAAI,GAAG,GAAG,CAAC;QACb,CAAC,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACtB,CAAC,CAAC,GAAG,GAAG,UAAU,CAAC;QACnB,CAAC,CAAC,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC;QACzB,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;QAC7B,CAAC,CAAC,KAAK,EAAE,CAAC;QACV,CAAC,CAAC,MAAM,EAAE,CAAC;IACb,CAAC;YAAS,CAAC;QACT,UAAU,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,eAAe,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC;IACrD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Headless editor session. Owns the edit log (as `History`), the derived\n * document, and a renderer. Every state change schedules a debounced preview\n * render on the working copy; stale results are discarded by version.\n */\nimport type { RgbaBuffer } from '@sealpixel/wasm';\nimport { type AssetResolver, webCryptoSha256, withAssets } from './assets.js';\nimport { compile } from './compile.js';\nimport { SealpixelError } from './errors.js';\nimport * as hist from './history.js';\nimport { InlineRenderer } from './inline-renderer.js';\nimport type { Geometry } from './plan.js';\nimport type { AnyPlugin, AssetDeclaration, Document } from './plugin.js';\nimport { createRegistry, type Registry } from './registry.js';\nimport type { Renderer } from './renderer.js';\nimport type { ExportResult } from './renderer-core.js';\nimport type { EditLog, History, Operation, OutputOptions, SourceDescriptor } from './types.js';\n\nexport type LoadSource = Uint8Array | ArrayBuffer | Blob | string;\n\nexport interface LoadOptions {\n /** Saved state to resume from (an `EditLog` or `{ log, index }`), validated through the registry. */\n editLog?: unknown;\n /** History position to resume at. Defaults to the end of the log. */\n index?: number;\n /** Source id. Defaults to the File name without extension, or `image`. */\n id?: string;\n}\n\nexport interface SessionOptions {\n plugins: readonly AnyPlugin[];\n /** Defaults to an `InlineRenderer` built from `plugins`. Pass a `WorkerRenderer` in browsers. */\n renderer?: Renderer;\n /**\n * How much of the original stays in the browser. Default 16 megapixels and\n * 50e6 bytes, enough for a camera JPEG of 60 megapixels. An image above\n * `maxClientMegapixels` is not resident: the preview works on a working\n * copy, and `export` fails with `NOT_RESIDENT`: the host renders the\n * original elsewhere. An image above\n * `maxClientBytes` does not load at all (`TOO_LARGE`). The megapixel limit\n * reaches the renderer with every load, so a shared worker follows the\n * session that loads into it.\n */\n limits?: { maxClientMegapixels?: number; maxClientBytes?: number };\n preview?: { debounceMs?: number; enabled?: boolean };\n /**\n * The preview image. The session always decodes the original in WebAssembly\n * and downscales it itself. `maxSide` is the longest side for the default\n * renderer. Default 2048. A `renderer` passed in uses its own setting.\n */\n workingCopy?: { maxSide?: number };\n /** Fonts and images referenced by the log. Defaults to the plugins' declarations with relative urls. */\n assets?: AssetResolver;\n /**\n * How `download` hands bytes to the user. Defaults to an `<a download>`\n * click in browsers; required elsewhere.\n */\n saveFile?: (bytes: Uint8Array, filename: string, mimeType: string) => void | Promise<void>;\n}\n\nexport interface PreviewState {\n image: RgbaBuffer;\n /** Geometry of the real output, whatever the stage shows. */\n geometry: Geometry;\n /**\n * Geometry of the log the preview image was rendered from. Equals\n * `geometry` without a preview transform; with one (a tool showing the\n * uncropped image) it describes the pixels on the stage, so the UI can map\n * preview pixels back to the source and keep the view steady.\n */\n viewGeometry: Geometry;\n /** Version of the history the preview reflects. */\n version: number;\n}\n\nexport interface SessionState {\n status: 'empty' | 'loading' | 'ready' | 'error';\n source: SourceDescriptor | null;\n /** Whether full-resolution pixels are held client-side (local export possible). */\n resident: boolean;\n history: History;\n document: Document;\n /** Increments on every history change. */\n version: number;\n preview: PreviewState | null;\n previewPending: boolean;\n error: SealpixelError | null;\n}\n\nexport interface ExportOptions {\n output: OutputOptions;\n embedEditLog?: boolean;\n upTo?: number;\n}\n\nexport interface DownloadOptions extends Partial<ExportOptions> {\n filename?: string;\n}\n\nexport interface EditorSession {\n readonly registry: Registry;\n /**\n * Loads an image, optionally resuming a saved state. On failure the session\n * stays on the previous image: the state and the renderer keep describing\n * it. When a newer `load` starts before this one finishes, this one rejects\n * with `ABORTED` and the newer one wins.\n */\n load(source: LoadSource, options?: LoadOptions): Promise<SourceDescriptor>;\n dispatch(op: Operation): void;\n undo(): void;\n redo(): void;\n /** Moves to `index`, clamped to the log. A non-finite index, such as `NaN`, changes nothing. */\n timeTravel(index: number): void;\n canUndo(): boolean;\n canRedo(): boolean;\n getState(): SessionState;\n getEditLog(): { log: EditLog; index: number };\n getDocument(): Document;\n subscribe(listener: (state: SessionState) => void): () => void;\n /** Forces a preview render now and resolves when it is applied. */\n renderPreview(): Promise<PreviewState>;\n /** Resolves when no preview render is pending. */\n whenIdle(): Promise<void>;\n /**\n * Replaces the history with a saved state for the loaded image (controlled\n * mode). Validates through the registry and checks the source.\n */\n setEditLog(saved: unknown, index?: number): void;\n /**\n * Transforms the log before preview rendering only. Tools use it to show,\n * for example, the un-cropped image while the crop gizmo is active.\n */\n setPreviewTransform(transform: ((log: EditLog) => EditLog) | null): void;\n /**\n * Renders a working-copy-sized image from the current log, transformed, and returns\n * it without touching the stage, the state or the history. Tools use it to\n * show what an edit the user has not made yet would look like: the filter\n * tool renders its thumbnails from the log with the filter removed, so a\n * chosen preset does not end up baked into the alternatives beside it.\n */\n renderDetached(\n transform: (log: EditLog) => EditLog,\n options?: { signal?: AbortSignal },\n ): Promise<RgbaBuffer>;\n /**\n * Registers an asset the user supplied (for example an uploaded sticker):\n * stores the bytes in the renderer and records the declaration in the log\n * so the log stays self-describing. Returns the declaration with its hash.\n */\n addAsset(bytes: Uint8Array, options?: { id?: string; url?: string }): Promise<AssetDeclaration>;\n /**\n * Renders the full resolution in the browser. Throws `NOT_RESIDENT` when the\n * image is above `maxClientMegapixels`: the host then renders the original\n * elsewhere, from the log that `getEditLog()` returns.\n */\n export(options: ExportOptions): Promise<ExportResult>;\n /** Exports like `export` and hands the file to `saveFile`. */\n download(options?: DownloadOptions): Promise<{ filename: string; result: ExportResult }>;\n dispose(): void;\n}\n\nconst hashMismatch = () =>\n new SealpixelError(\n 'SOURCE_MISMATCH',\n 'the saved edit log belongs to a different image (hash differs)',\n );\n\nconst supersededError = () => new SealpixelError('ABORTED', 'a newer load() replaced this one');\n\nconst EXT: Record<OutputOptions['format'], string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n};\n\nexport function createEditorSession(options: SessionOptions): EditorSession {\n const registry = createRegistry(options.plugins);\n const maxClientMegapixels = options.limits?.maxClientMegapixels ?? 16;\n const maxClientBytes = options.limits?.maxClientBytes ?? 50e6;\n const renderer =\n options.renderer ??\n new InlineRenderer({\n plugins: options.plugins,\n maxClientMegapixels,\n workingCopyMaxSide: options.workingCopy?.maxSide ?? 2048,\n });\n // A renderer handed in by the host outlives this session: hosts reuse it across sessions.\n const ownsRenderer = options.renderer === undefined;\n const debounceMs = options.preview?.debounceMs ?? 80;\n const previewEnabled = options.preview?.enabled ?? true;\n\n const listeners = new Set<(state: SessionState) => void>();\n const emptyHistory = () =>\n hist.createHistory({\n version: 1,\n source: { id: '', width: 1, height: 1 },\n plugins: registry.pluginVersions(),\n ops: [],\n });\n let state: SessionState = {\n status: 'empty',\n source: null,\n resident: false,\n history: emptyHistory(),\n document: registry.initialDocument(),\n version: 0,\n preview: null,\n previewPending: false,\n error: null,\n };\n\n let previewTransform: ((log: EditLog) => EditLog) | null = null;\n /**\n * The image that `state.source` describes and the renderer holds, with its\n * original bytes to restore the renderer after a failed load. Changes only\n * together with `state.source`.\n */\n let committed: { bytes: Uint8Array; id: string } | null = null;\n /** Increments on every `load`. A load that sees a newer one gives up. */\n let loadGeneration = 0;\n /** Serializes the part of `load` that switches the renderer. */\n let loadQueue: Promise<unknown> = Promise.resolve();\n /** Bytes of assets added through `addAsset`, re-put after a renderer reload. */\n const localAssets = new Map<string, Uint8Array>();\n const resolver: AssetResolver | undefined = options.assets\n ? {\n declarations: () => options.assets?.declarations() ?? [],\n resolve: async (id) =>\n localAssets.get(id) ?? (await (options.assets as AssetResolver).resolve(id)),\n }\n : undefined;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let inflight: { version: number; controller: AbortController } | null = null;\n let idleResolvers: (() => void)[] = [];\n let disposed = false;\n\n const emit = () => {\n for (const l of listeners) l(state);\n };\n const set = (patch: Partial<SessionState>) => {\n state = { ...state, ...patch };\n emit();\n };\n const settleIdle = () => {\n if (!state.previewPending && !timer && !inflight) {\n const resolvers = idleResolvers;\n idleResolvers = [];\n for (const r of resolvers) r();\n }\n };\n\n const setHistory = (history: History) => {\n if (history === state.history) return;\n set({\n history,\n document: compile(hist.current(history), registry),\n version: state.version + 1,\n });\n schedulePreview();\n };\n\n function schedulePreview(): void {\n if (!previewEnabled || state.status !== 'ready') return;\n if (timer) clearTimeout(timer);\n set({ previewPending: true });\n timer = setTimeout(() => {\n timer = null;\n void runPreview();\n }, debounceMs);\n }\n\n async function runPreview(): Promise<PreviewState | null> {\n if (state.status !== 'ready') {\n set({ previewPending: false });\n settleIdle();\n return null;\n }\n inflight?.controller.abort();\n const version = state.version;\n const controller = new AbortController();\n inflight = { version, controller };\n const base = hist.current(state.history);\n const log = previewTransform ? previewTransform(base) : base;\n try {\n const [image, geometry, viewGeometry] = await Promise.all([\n withAssets(\n () => renderer.render({ log, target: 'workingCopy', signal: controller.signal }),\n resolver,\n (id, bytes) => renderer.putAsset(id, bytes),\n ),\n // Geometry always describes the real output, even when a preview\n // transform shows something else on the stage.\n renderer.geometry({ log: base, target: 'workingCopy' }),\n // The stage needs the geometry of what it shows to keep the view steady.\n previewTransform ? renderer.geometry({ log, target: 'workingCopy' }) : null,\n ]);\n if (disposed || controller.signal.aborted || version !== state.version) {\n // With previews disabled no later render clears `inflight`, so a stale\n // result has to, or `whenIdle` never resolves.\n if (inflight?.controller === controller) inflight = null;\n settleIdle();\n return null;\n }\n const preview = { image, geometry, viewGeometry: viewGeometry ?? geometry, version };\n inflight = null;\n set({ preview, previewPending: false, error: null });\n settleIdle();\n return preview;\n } catch (error) {\n if (inflight?.controller === controller) inflight = null;\n const e = SealpixelError.from(error);\n if (e.name === 'ABORTED' || version !== state.version) {\n settleIdle();\n return null;\n }\n set({ previewPending: false, error: e });\n settleIdle();\n return null;\n }\n }\n\n async function renderDetached(\n transform: (log: EditLog) => EditLog,\n options?: { signal?: AbortSignal },\n ): Promise<RgbaBuffer> {\n if (state.status !== 'ready') {\n throw new SealpixelError('NO_SOURCE', 'renderDetached needs a loaded image');\n }\n const log = transform(hist.current(state.history));\n return withAssets(\n () =>\n renderer.render({\n log,\n target: 'workingCopy',\n ...(options?.signal ? { signal: options.signal } : {}),\n }),\n resolver,\n (id, bytes) => renderer.putAsset(id, bytes),\n );\n }\n\n async function readBytes(\n source: LoadSource,\n ): Promise<{ bytes: Uint8Array; name: string | null }> {\n if (source instanceof Uint8Array) return { bytes: source, name: null };\n if (source instanceof ArrayBuffer) return { bytes: new Uint8Array(source), name: null };\n if (typeof source === 'string') {\n const res = await fetch(source);\n if (!res.ok) throw new SealpixelError('DECODE_FAILED', `${source}: HTTP ${res.status}`);\n return {\n bytes: new Uint8Array(await res.arrayBuffer()),\n name: source.split('/').pop() ?? null,\n };\n }\n const name =\n 'name' in source && typeof (source as File).name === 'string' ? (source as File).name : null;\n return { bytes: new Uint8Array(await source.arrayBuffer()), name };\n }\n\n /**\n * Decodes the original in WebAssembly. The renderer keeps the full image\n * only within `maxClientMegapixels`; the preview always uses the working copy.\n */\n function loadInto(bytes: Uint8Array, id: string) {\n return renderer.load(bytes, id, { maxClientMegapixels });\n }\n\n function resolveSavedState(saved: unknown): { log: EditLog; index: number | undefined } {\n const wrapped = saved as { log?: unknown; index?: unknown };\n const raw = wrapped && typeof wrapped === 'object' && 'log' in wrapped ? wrapped.log : saved;\n const log = registry.parseEditLog(raw);\n const index = typeof wrapped?.index === 'number' ? wrapped.index : undefined;\n return { log, index };\n }\n\n /** Runs `task` after every renderer switch that started before it. */\n function exclusive<T>(task: () => Promise<T>): Promise<T> {\n const run = loadQueue.then(task);\n loadQueue = run.catch(() => {});\n return run;\n }\n\n /**\n * Puts the committed image back into the renderer after a load switched it\n * and then failed. If that fails too, the session drops to `empty`: a state\n * that names an image the renderer does not hold renders wrong pixels.\n */\n async function restoreCommitted(): Promise<void> {\n // Nothing committed: the state is `empty` and nothing renders.\n if (!committed) return;\n try {\n await loadInto(committed.bytes, committed.id);\n } catch {\n committed = null;\n set({\n status: 'empty',\n source: null,\n resident: false,\n history: emptyHistory(),\n document: registry.initialDocument(),\n version: state.version + 1,\n preview: null,\n });\n }\n }\n\n /** History for a saved state resumed on a freshly loaded image. Throws `SOURCE_MISMATCH`. */\n function savedHistory(\n saved: { log: EditLog; index: number | undefined },\n descriptor: SourceDescriptor,\n index: number | undefined,\n ): History {\n const { log } = saved;\n if (log.source.hash !== undefined && log.source.hash !== descriptor.hash) {\n throw hashMismatch();\n }\n if (log.source.width !== descriptor.width || log.source.height !== descriptor.height) {\n throw new SealpixelError(\n 'SOURCE_MISMATCH',\n `the saved edit log expects ${log.source.width}x${log.source.height}, image is ${descriptor.width}x${descriptor.height}`,\n );\n }\n return hist.createHistory(\n {\n ...log,\n source: {\n ...log.source,\n hash: descriptor.hash ?? log.source.hash,\n } as SourceDescriptor,\n },\n index ?? saved.index ?? log.ops.length,\n );\n }\n\n const session: EditorSession = {\n registry,\n\n async load(source, loadOptions = {}) {\n const generation = ++loadGeneration;\n const superseded = () => generation !== loadGeneration;\n if (timer) clearTimeout(timer);\n timer = null;\n inflight?.controller.abort();\n inflight = null;\n set({ status: 'loading', error: null, preview: null, previewPending: false });\n try {\n const { bytes, name } = await readBytes(source);\n if (superseded()) throw supersededError();\n if (bytes.byteLength > maxClientBytes) {\n throw new SealpixelError(\n 'TOO_LARGE',\n `${bytes.byteLength} bytes exceed the client limit of ${maxClientBytes}`,\n );\n }\n const id = loadOptions.id ?? (name ? name.replace(/\\.[^.]+$/, '') : 'image');\n // Validate what can be validated before the renderer switches.\n const saved =\n loadOptions.editLog === undefined ? null : resolveSavedState(loadOptions.editLog);\n if (saved?.log.source.hash !== undefined) {\n if (saved.log.source.hash !== (await webCryptoSha256(bytes))) throw hashMismatch();\n if (superseded()) throw supersededError();\n }\n return await exclusive(async () => {\n if (superseded()) throw supersededError();\n const loaded = await loadInto(bytes, id);\n // The renderer holds the new image now. Until the state commits to\n // it, any failure puts the renderer back on the committed image.\n try {\n if (superseded()) throw supersededError();\n const descriptor = loaded.descriptor;\n const history = saved\n ? savedHistory(saved, descriptor, loadOptions.index)\n : hist.createHistory({\n version: 1,\n source: descriptor,\n plugins: registry.pluginVersions(),\n ops: [],\n });\n const document = compile(hist.current(history), registry);\n committed = { bytes, id };\n set({\n status: 'ready',\n source: descriptor,\n resident: loaded.resident,\n history,\n document,\n version: state.version + 1,\n preview: null,\n error: null,\n });\n schedulePreview();\n return descriptor;\n } catch (error) {\n await restoreCommitted();\n throw error;\n }\n });\n } catch (error) {\n const e = SealpixelError.from(error);\n // Only the newest load reports into the state. It waits for the\n // renderer switches ahead of it, so the state never says `ready` while\n // an older load still holds the renderer on another image.\n await exclusive(async () => {\n if (!superseded()) set({ status: state.source ? 'ready' : 'empty', error: e });\n });\n throw e;\n }\n },\n\n dispatch(op) {\n ensureReady();\n const violation = state.source\n ? registry.validateOperation(op, state.document, state.source)\n : null;\n if (violation) throw new SealpixelError('OPTION_VIOLATION', `${op.type}: ${violation}`);\n setHistory(hist.dispatch(state.history, op));\n },\n undo() {\n setHistory(hist.undo(state.history));\n },\n redo() {\n setHistory(hist.redo(state.history));\n },\n timeTravel(index) {\n setHistory(hist.timeTravel(state.history, index));\n },\n canUndo: () => hist.canUndo(state.history),\n canRedo: () => hist.canRedo(state.history),\n getState: () => state,\n getEditLog: () => ({ log: state.history.log, index: state.history.index }),\n getDocument: () => state.document,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n async renderPreview() {\n ensureReady();\n if (timer) clearTimeout(timer);\n timer = null;\n const result = await runPreview();\n if (result) return result;\n if (state.preview && state.preview.version === state.version) return state.preview;\n throw state.error ?? new SealpixelError('ABORTED', 'preview superseded');\n },\n\n whenIdle() {\n if (!state.previewPending && !timer && !inflight) return Promise.resolve();\n return new Promise((resolve) => idleResolvers.push(resolve));\n },\n\n setEditLog(saved, index) {\n ensureReady();\n const descriptor = state.source as SourceDescriptor;\n const resolved = resolveSavedState(saved);\n const log = resolved.log;\n if (\n log.source.hash !== undefined &&\n descriptor.hash !== undefined &&\n log.source.hash !== descriptor.hash\n ) {\n throw new SealpixelError(\n 'SOURCE_MISMATCH',\n 'the edit log belongs to a different image (hash differs)',\n );\n }\n if (log.source.width !== descriptor.width || log.source.height !== descriptor.height) {\n throw new SealpixelError('SOURCE_MISMATCH', 'the edit log has different source dimensions');\n }\n setHistory(\n hist.createHistory(\n { ...log, source: descriptor },\n index ?? resolved.index ?? log.ops.length,\n ),\n );\n },\n\n renderDetached,\n setPreviewTransform(transform) {\n previewTransform = transform;\n set({ version: state.version + 1 });\n schedulePreview();\n },\n\n async addAsset(bytes, assetOptions = {}) {\n ensureReady();\n const hash = await webCryptoSha256(bytes);\n const declaration: AssetDeclaration = {\n id: assetOptions.id ?? `asset.${hash.slice(0, 16)}`,\n hash,\n ...(assetOptions.url === undefined ? {} : { url: assetOptions.url }),\n };\n await renderer.putAsset(declaration.id, bytes);\n localAssets.set(declaration.id, bytes);\n const existing = state.history.log.assets ?? [];\n if (!existing.some((a) => a.id === declaration.id)) {\n const log: EditLog = { ...state.history.log, assets: [...existing, declaration] };\n set({ history: { ...state.history, log } });\n }\n return declaration;\n },\n\n async export(exportOptions) {\n ensureReady();\n if (!state.resident) {\n throw new SealpixelError(\n 'NOT_RESIDENT',\n `the image is larger than maxClientMegapixels (${maxClientMegapixels}), so its full resolution is not in the browser; render the original outside the browser with the log from getEditLog()`,\n );\n }\n const log = state.history.log;\n const upTo = exportOptions.upTo ?? state.history.index;\n const violations = registry.validateDocument(\n upTo === state.history.index ? state.document : compile(log, registry, upTo),\n log.source,\n );\n if (violations.length > 0) {\n throw new SealpixelError(\n 'OPTION_VIOLATION',\n violations.map((v) => `${v.plugin}: ${v.message}`).join('; '),\n violations,\n );\n }\n return renderer.export({\n log,\n output: exportOptions.output,\n upTo,\n ...(exportOptions.embedEditLog === undefined\n ? {}\n : { embedEditLog: exportOptions.embedEditLog }),\n });\n },\n\n async download(downloadOptions = {}) {\n ensureReady();\n const output = downloadOptions.output ?? { format: 'image/png' };\n const exportOptions: ExportOptions = {\n output,\n ...(downloadOptions.embedEditLog === undefined\n ? {}\n : { embedEditLog: downloadOptions.embedEditLog }),\n ...(downloadOptions.upTo === undefined ? {} : { upTo: downloadOptions.upTo }),\n };\n const save = options.saveFile ?? browserSaveFile;\n const result = await session.export(exportOptions);\n const filename =\n downloadOptions.filename ??\n `${state.source?.id ?? 'image'}-${result.hash.slice(0, 8)}.${EXT[output.format]}`;\n await save(result.bytes, filename, result.mimeType);\n return { filename, result };\n },\n\n dispose() {\n disposed = true;\n if (timer) clearTimeout(timer);\n inflight?.controller.abort();\n listeners.clear();\n if (ownsRenderer) renderer.dispose();\n },\n };\n\n function ensureReady(): void {\n if (state.status !== 'ready') throw new SealpixelError('NO_SOURCE', 'load an image first');\n }\n\n return session;\n}\n\n/** Default `saveFile`: an `<a download>` click, with the share sheet as a fallback on iOS Safari. */\nexport async function browserSaveFile(\n bytes: Uint8Array,\n filename: string,\n mimeType: string,\n): Promise<void> {\n if (typeof document === 'undefined' || typeof URL.createObjectURL !== 'function') {\n throw new SealpixelError(\n 'DOWNLOAD_UNSUPPORTED',\n 'no DOM available; pass saveFile to createEditorSession',\n );\n }\n const blob = new Blob([bytes as BlobPart], { type: mimeType });\n const nav = navigator as Navigator & { canShare?: (d: ShareData) => boolean };\n const isIOS = /iP(hone|ad|od)/.test(navigator.userAgent);\n if (\n isIOS &&\n typeof File !== 'undefined' &&\n nav.canShare?.({ files: [new File([blob], filename, { type: mimeType })] })\n ) {\n await navigator.share({ files: [new File([blob], filename, { type: mimeType })] });\n return;\n }\n const url = URL.createObjectURL(blob);\n try {\n const a = document.createElement('a');\n a.href = url;\n a.download = filename;\n a.rel = 'noopener';\n a.style.display = 'none';\n document.body.appendChild(a);\n a.click();\n a.remove();\n } finally {\n setTimeout(() => URL.revokeObjectURL(url), 10_000);\n }\n}\n"]}
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAMA,OAAO,EAAsB,eAAe,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9E,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,KAAK,IAAI,MAAM,cAAc,CAAC;AACrC,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAGtD,OAAO,EAAE,cAAc,EAAE,sBAAsB,EAAiB,MAAM,eAAe,CAAC;AA6JtF,MAAM,YAAY,GAAG,GAAG,EAAE,CACxB,IAAI,cAAc,CAChB,iBAAiB,EACjB,gEAAgE,CACjE,CAAC;AAEJ,MAAM,eAAe,GAAG,GAAG,EAAE,CAAC,IAAI,cAAc,CAAC,SAAS,EAAE,kCAAkC,CAAC,CAAC;AAEhG,MAAM,aAAa,GAAG,GAAG,EAAE,CACzB,IAAI,cAAc,CAAC,SAAS,EAAE,+CAA+C,CAAC,CAAC;AAEjF,MAAM,GAAG,GAA4C;IACnD,WAAW,EAAE,KAAK;IAClB,YAAY,EAAE,KAAK;IACnB,YAAY,EAAE,MAAM;CACrB,CAAC;AAEF,MAAM,UA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it log (as `History`), the derived\n * document, and a renderer. Every state change schedules a debounced preview\n * render on the working copy; stale results are discarded by version.\n */\nimport type { RgbaBuffer } from '@sealpixel/wasm';\nimport { type AssetResolver, webCryptoSha256, withAssets } from './assets.js';\nimport { compile } from './compile.js';\nimport { SealpixelError } from './errors.js';\nimport * as hist from './history.js';\nimport { InlineRenderer } from './inline-renderer.js';\nimport type { Geometry } from './plan.js';\nimport type { AnyPlugin, AssetDeclaration, Document } from './plugin.js';\nimport { createRegistry, parseAppendedOperation, type Registry } from './registry.js';\nimport type { Renderer } from './renderer.js';\nimport type { ExportResult } from './renderer-core.js';\nimport type { EditLog, History, Operation, OutputOptions, SourceDescriptor } from './types.js';\n\nexport type LoadSource = Uint8Array | ArrayBuffer | Blob | string;\n\nexport interface LoadOptions {\n /** Saved state to resume from (an `EditLog` or `{ log, index }`), validated through the registry. */\n editLog?: unknown;\n /** History position to resume at. Defaults to the end of the log. */\n index?: number;\n /** Source id. Defaults to the File name without extension, or `image`. */\n id?: string;\n}\n\nexport interface SessionOptions {\n plugins: readonly AnyPlugin[];\n /** Defaults to an `InlineRenderer` built from `plugins`. Pass a `WorkerRenderer` in browsers. */\n renderer?: Renderer;\n /**\n * How much of the original stays in the browser. Default 16 megapixels and\n * 50e6 bytes, enough for a camera JPEG of 60 megapixels. An image above\n * `maxClientMegapixels` is not resident: the preview works on a working\n * copy, and `export` fails with `NOT_RESIDENT`: the host renders the\n * original elsewhere. An image above\n * `maxClientBytes` does not load at all (`TOO_LARGE`). The megapixel limit\n * reaches the renderer with every load, so a shared worker follows the\n * session that loads into it.\n */\n limits?: { maxClientMegapixels?: number; maxClientBytes?: number };\n preview?: { debounceMs?: number; enabled?: boolean };\n /**\n * The preview image. The session always decodes the original in WebAssembly\n * and downscales it itself. `maxSide` is the longest side for the default\n * renderer. Default 2048. A `renderer` passed in uses its own setting.\n */\n workingCopy?: { maxSide?: number };\n /** Fonts and images referenced by the log. Defaults to the plugins' declarations with relative urls. */\n assets?: AssetResolver;\n /**\n * How `download` hands bytes to the user. Defaults to an `<a download>`\n * click in browsers; required elsewhere.\n */\n saveFile?: (bytes: Uint8Array, filename: string, mimeType: string) => void | Promise<void>;\n}\n\nexport interface PreviewState {\n image: RgbaBuffer;\n /** Geometry of the real output, whatever the stage shows. */\n geometry: Geometry;\n /**\n * Geometry of the log the preview image was rendered from. Equals\n * `geometry` without a preview transform; with one (a tool showing the\n * uncropped image) it describes the pixels on the stage, so the UI can map\n * preview pixels back to the source and keep the view steady.\n */\n viewGeometry: Geometry;\n /** Version of the history the preview reflects. */\n version: number;\n}\n\nexport interface SessionState {\n status: 'empty' | 'loading' | 'ready' | 'error';\n source: SourceDescriptor | null;\n /** Whether full-resolution pixels are held client-side (local export possible). */\n resident: boolean;\n history: History;\n document: Document;\n /** Increments on every history change. */\n version: number;\n preview: PreviewState | null;\n previewPending: boolean;\n error: SealpixelError | null;\n}\n\nexport interface ExportOptions {\n output: OutputOptions;\n embedEditLog?: boolean;\n upTo?: number;\n}\n\nexport interface DownloadOptions extends Partial<ExportOptions> {\n filename?: string;\n}\n\nexport interface EditorSession {\n readonly registry: Registry;\n /**\n * Loads an image, optionally resuming a saved state. On failure the session\n * stays on the previous image: the state and the renderer keep describing\n * it. When a newer `load` starts before this one finishes, this one rejects\n * with `ABORTED` and the newer one wins.\n */\n load(source: LoadSource, options?: LoadOptions): Promise<SourceDescriptor>;\n /**\n * Appends `op` at the current position. Checks it like a log parse does\n * and throws `SealpixelError` with the same code. An op without an `id` is\n * an error. An op whose `id` is already in the log is a no-op.\n */\n dispatch(op: Operation): void;\n undo(): void;\n redo(): void;\n /** Moves to `index`, clamped to the log. A non-finite index, such as `NaN`, changes nothing. */\n timeTravel(index: number): void;\n canUndo(): boolean;\n canRedo(): boolean;\n getState(): SessionState;\n getEditLog(): { log: EditLog; index: number };\n getDocument(): Document;\n subscribe(listener: (state: SessionState) => void): () => void;\n /** Forces a preview render now and resolves when it is applied. */\n renderPreview(): Promise<PreviewState>;\n /** Resolves when no preview render is pending. Resolves at once after `dispose`. */\n whenIdle(): Promise<void>;\n /**\n * Replaces the history with a saved state for the loaded image (controlled\n * mode). Validates through the registry and checks the source.\n */\n setEditLog(saved: unknown, index?: number): void;\n /**\n * Transforms the log before preview rendering only. Tools use it to show,\n * for example, the un-cropped image while the crop gizmo is active.\n */\n setPreviewTransform(transform: ((log: EditLog) => EditLog) | null): void;\n /**\n * Renders a working-copy-sized image from the current log, transformed, and returns\n * it without touching the stage, the state or the history. Tools use it to\n * show what an edit the user has not made yet would look like: the filter\n * tool renders its thumbnails from the log with the filter removed, so a\n * chosen preset does not end up baked into the alternatives beside it.\n */\n renderDetached(\n transform: (log: EditLog) => EditLog,\n options?: { signal?: AbortSignal },\n ): Promise<RgbaBuffer>;\n /**\n * Registers an asset the user supplied (for example an uploaded sticker):\n * stores the bytes in the renderer and records the declaration in the log\n * so the log stays self-describing. Returns the declaration with its hash.\n */\n addAsset(bytes: Uint8Array, options?: { id?: string; url?: string }): Promise<AssetDeclaration>;\n /**\n * Renders the full resolution in the browser. Throws `NOT_RESIDENT` when the\n * image is above `maxClientMegapixels`: the host then renders the original\n * elsewhere, from the log that `getEditLog()` returns.\n */\n export(options: ExportOptions): Promise<ExportResult>;\n /** Exports like `export` and hands the file to `saveFile`. */\n download(options?: DownloadOptions): Promise<{ filename: string; result: ExportResult }>;\n /**\n * Stops the previews and settles every pending `whenIdle`. After it, every\n * method that needs the renderer fails with `ABORTED`.\n */\n dispose(): void;\n}\n\nconst hashMismatch = () =>\n new SealpixelError(\n 'SOURCE_MISMATCH',\n 'the saved edit log belongs to a different image (hash differs)',\n );\n\nconst supersededError = () => new SealpixelError('ABORTED', 'a newer load() replaced this one');\n\nconst disposedError = () =>\n new SealpixelError('ABORTED', 'the session is disposed; create a new session');\n\nconst EXT: Record<OutputOptions['format'], string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n};\n\nexport function createEditorSession(options: SessionOptions): EditorSession {\n const registry = createRegistry(options.plugins);\n const maxClientMegapixels = options.limits?.maxClientMegapixels ?? 16;\n const maxClientBytes = options.limits?.maxClientBytes ?? 50e6;\n const renderer =\n options.renderer ??\n new InlineRenderer({\n plugins: options.plugins,\n maxClientMegapixels,\n workingCopyMaxSide: options.workingCopy?.maxSide ?? 2048,\n });\n // A renderer handed in by the host outlives this session: hosts reuse it across sessions.\n const ownsRenderer = options.renderer === undefined;\n const debounceMs = options.preview?.debounceMs ?? 80;\n const previewEnabled = options.preview?.enabled ?? true;\n\n const listeners = new Set<(state: SessionState) => void>();\n const emptyHistory = () =>\n hist.createHistory({\n version: 1,\n source: { id: '', width: 1, height: 1 },\n plugins: registry.pluginVersions(),\n ops: [],\n });\n let state: SessionState = {\n status: 'empty',\n source: null,\n resident: false,\n history: emptyHistory(),\n document: registry.initialDocument(),\n version: 0,\n preview: null,\n previewPending: false,\n error: null,\n };\n\n let previewTransform: ((log: EditLog) => EditLog) | null = null;\n /**\n * The image that `state.source` describes and the renderer holds, with its\n * original bytes to restore the renderer after a failed load. Changes only\n * together with `state.source`.\n */\n let committed: { bytes: Uint8Array; id: string } | null = null;\n /** Increments on every `load`. A load that sees a newer one gives up. */\n let loadGeneration = 0;\n /** Serializes the part of `load` that switches the renderer. */\n let loadQueue: Promise<unknown> = Promise.resolve();\n /** Bytes of assets added through `addAsset`, re-put after a renderer reload. */\n const localAssets = new Map<string, Uint8Array>();\n const resolver: AssetResolver | undefined = options.assets\n ? {\n declarations: () => options.assets?.declarations() ?? [],\n resolve: async (id) =>\n localAssets.get(id) ?? (await (options.assets as AssetResolver).resolve(id)),\n }\n : undefined;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let inflight: { version: number; controller: AbortController } | null = null;\n let idleResolvers: (() => void)[] = [];\n let disposed = false;\n /**\n * The version at which a load failed. The preview of the restored image\n * keeps the load error on the stage. A later edit changes the version, and\n * its preview clears the error as before.\n */\n let failedLoadVersion = -1;\n\n const emit = () => {\n for (const l of listeners) l(state);\n };\n const set = (patch: Partial<SessionState>) => {\n state = { ...state, ...patch };\n emit();\n };\n const settleIdle = () => {\n if (!state.previewPending && !timer && !inflight) {\n const resolvers = idleResolvers;\n idleResolvers = [];\n for (const r of resolvers) r();\n }\n };\n\n const setHistory = (history: History) => {\n if (history === state.history) return;\n set({\n history,\n document: compile(hist.current(history), registry),\n version: state.version + 1,\n });\n schedulePreview();\n };\n\n function schedulePreview(): void {\n if (disposed || !previewEnabled || state.status !== 'ready') return;\n if (timer) clearTimeout(timer);\n set({ previewPending: true });\n timer = setTimeout(() => {\n timer = null;\n void runPreview();\n }, debounceMs);\n }\n\n async function runPreview(): Promise<PreviewState | null> {\n if (state.status !== 'ready') {\n set({ previewPending: false });\n settleIdle();\n return null;\n }\n inflight?.controller.abort();\n const version = state.version;\n const controller = new AbortController();\n inflight = { version, controller };\n const base = hist.current(state.history);\n const log = previewTransform ? previewTransform(base) : base;\n try {\n const [image, geometry, viewGeometry] = await Promise.all([\n withAssets(\n () => renderer.render({ log, target: 'workingCopy', signal: controller.signal }),\n resolver,\n (id, bytes) => renderer.putAsset(id, bytes),\n ),\n // Geometry always describes the real output, even when a preview\n // transform shows something else on the stage.\n renderer.geometry({ log: base, target: 'workingCopy' }),\n // The stage needs the geometry of what it shows to keep the view steady.\n previewTransform ? renderer.geometry({ log, target: 'workingCopy' }) : null,\n ]);\n if (disposed || controller.signal.aborted || version !== state.version) {\n // With previews disabled no later render clears `inflight`, so a stale\n // result has to, or `whenIdle` never resolves.\n if (inflight?.controller === controller) inflight = null;\n settleIdle();\n return null;\n }\n const preview = { image, geometry, viewGeometry: viewGeometry ?? geometry, version };\n inflight = null;\n set({\n preview,\n previewPending: false,\n error: version === failedLoadVersion ? state.error : null,\n });\n settleIdle();\n return preview;\n } catch (error) {\n if (inflight?.controller === controller) inflight = null;\n const e = SealpixelError.from(error);\n // Only an abort that the session caused has a successor that settles\n // `previewPending`. An abort from elsewhere, such as a shared renderer\n // that its host disposed, is reported like any other failure.\n if ((e.name === 'ABORTED' && controller.signal.aborted) || version !== state.version) {\n settleIdle();\n return null;\n }\n set({ previewPending: false, error: e });\n settleIdle();\n return null;\n }\n }\n\n async function renderDetached(\n transform: (log: EditLog) => EditLog,\n options?: { signal?: AbortSignal },\n ): Promise<RgbaBuffer> {\n ensureAlive();\n if (state.status !== 'ready') {\n throw new SealpixelError('NO_SOURCE', 'renderDetached needs a loaded image');\n }\n const log = transform(hist.current(state.history));\n return withAssets(\n () =>\n renderer.render({\n log,\n target: 'workingCopy',\n ...(options?.signal ? { signal: options.signal } : {}),\n }),\n resolver,\n (id, bytes) => renderer.putAsset(id, bytes),\n );\n }\n\n async function readBytes(\n source: LoadSource,\n ): Promise<{ bytes: Uint8Array; name: string | null }> {\n if (source instanceof Uint8Array) return { bytes: source, name: null };\n if (source instanceof ArrayBuffer) return { bytes: new Uint8Array(source), name: null };\n if (typeof source === 'string') {\n const res = await fetch(source);\n if (!res.ok) throw new SealpixelError('DECODE_FAILED', `${source}: HTTP ${res.status}`);\n return {\n bytes: new Uint8Array(await res.arrayBuffer()),\n // The query and the fragment are not part of the file name.\n name: source.split(/[?#]/, 1)[0]?.split('/').pop() ?? null,\n };\n }\n // A Blob knows its size: refuse a large one before reading it into memory.\n if (source.size > maxClientBytes) throw tooLarge(source.size);\n const name =\n 'name' in source && typeof (source as File).name === 'string' ? (source as File).name : null;\n return { bytes: new Uint8Array(await source.arrayBuffer()), name };\n }\n\n /**\n * Decodes the original in WebAssembly. The renderer keeps the full image\n * only within `maxClientMegapixels`; the preview always uses the working copy.\n */\n function loadInto(bytes: Uint8Array, id: string) {\n return renderer.load(bytes, id, { maxClientMegapixels });\n }\n\n function resolveSavedState(saved: unknown): { log: EditLog; index: number | undefined } {\n const wrapped = saved as { log?: unknown; index?: unknown };\n const raw = wrapped && typeof wrapped === 'object' && 'log' in wrapped ? wrapped.log : saved;\n const log = registry.parseEditLog(raw);\n const index = typeof wrapped?.index === 'number' ? wrapped.index : undefined;\n return { log, index };\n }\n\n function tooLarge(byteLength: number): SealpixelError {\n return new SealpixelError(\n 'TOO_LARGE',\n `${byteLength} bytes exceed the client limit of ${maxClientBytes}`,\n );\n }\n\n /** Runs `task` after every renderer switch that started before it. */\n function exclusive<T>(task: () => Promise<T>): Promise<T> {\n const run = loadQueue.then(task);\n loadQueue = run.catch(() => {});\n return run;\n }\n\n /**\n * Puts the committed image back into the renderer after a load switched it\n * and then failed. If that fails too, the session drops to `empty`: a state\n * that names an image the renderer does not hold renders wrong pixels.\n */\n async function restoreCommitted(): Promise<void> {\n // Nothing committed: the state is `empty` and nothing renders. A disposed\n // session renders nothing either.\n if (!committed || disposed) return;\n try {\n await loadInto(committed.bytes, committed.id);\n } catch {\n committed = null;\n set({\n status: 'empty',\n source: null,\n resident: false,\n history: emptyHistory(),\n document: registry.initialDocument(),\n version: state.version + 1,\n preview: null,\n });\n }\n }\n\n /** History for a saved state resumed on a freshly loaded image. Throws `SOURCE_MISMATCH`. */\n function savedHistory(\n saved: { log: EditLog; index: number | undefined },\n descriptor: SourceDescriptor,\n index: number | undefined,\n ): History {\n const { log } = saved;\n if (log.source.hash !== undefined && log.source.hash !== descriptor.hash) {\n throw hashMismatch();\n }\n if (log.source.width !== descriptor.width || log.source.height !== descriptor.height) {\n throw new SealpixelError(\n 'SOURCE_MISMATCH',\n `the saved edit log expects ${log.source.width}x${log.source.height}, image is ${descriptor.width}x${descriptor.height}`,\n );\n }\n return hist.createHistory(\n {\n ...log,\n source: {\n ...log.source,\n hash: descriptor.hash ?? log.source.hash,\n } as SourceDescriptor,\n },\n index ?? saved.index ?? log.ops.length,\n );\n }\n\n const session: EditorSession = {\n registry,\n\n async load(source, loadOptions = {}) {\n ensureAlive();\n const generation = ++loadGeneration;\n const superseded = () => generation !== loadGeneration;\n if (timer) clearTimeout(timer);\n timer = null;\n inflight?.controller.abort();\n inflight = null;\n set({ status: 'loading', error: null, preview: null, previewPending: false });\n try {\n const { bytes, name } = await readBytes(source);\n if (superseded()) throw supersededError();\n if (bytes.byteLength > maxClientBytes) throw tooLarge(bytes.byteLength);\n const id = loadOptions.id ?? (name ? name.replace(/\\.[^.]+$/, '') : 'image');\n // Validate what can be validated before the renderer switches.\n const saved =\n loadOptions.editLog === undefined ? null : resolveSavedState(loadOptions.editLog);\n if (saved?.log.source.hash !== undefined) {\n if (saved.log.source.hash !== (await webCryptoSha256(bytes))) throw hashMismatch();\n if (superseded()) throw supersededError();\n }\n return await exclusive(async () => {\n if (superseded()) throw supersededError();\n ensureAlive();\n const loaded = await loadInto(bytes, id);\n // The renderer holds the new image now. Until the state commits to\n // it, any failure puts the renderer back on the committed image.\n try {\n if (superseded()) throw supersededError();\n ensureAlive();\n const descriptor = loaded.descriptor;\n const history = saved\n ? savedHistory(saved, descriptor, loadOptions.index)\n : hist.createHistory({\n version: 1,\n source: descriptor,\n plugins: registry.pluginVersions(),\n ops: [],\n });\n const document = compile(hist.current(history), registry);\n committed = { bytes, id };\n set({\n status: 'ready',\n source: descriptor,\n resident: loaded.resident,\n history,\n document,\n version: state.version + 1,\n preview: null,\n error: null,\n });\n schedulePreview();\n return descriptor;\n } catch (error) {\n await restoreCommitted();\n throw error;\n }\n });\n } catch (error) {\n const e = SealpixelError.from(error);\n // Only the newest load reports into the state. It waits for the\n // renderer switches ahead of it, so the state never says `ready` while\n // an older load still holds the renderer on another image.\n await exclusive(async () => {\n if (superseded()) return;\n set({ status: state.source ? 'ready' : 'empty', error: e });\n // `load` dropped the preview. The renderer holds the previous image\n // again, so the stage shows it again.\n failedLoadVersion = state.version;\n schedulePreview();\n });\n throw e;\n }\n },\n\n dispatch(op) {\n ensureReady();\n const id = (op as { id?: unknown } | null)?.id;\n if (typeof id !== 'string' || id === '') {\n throw new SealpixelError('INVALID_EDIT_LOG', 'op has no non-empty string \"id\"');\n }\n // A retried op is a no-op before any check: its first dispatch already\n // passed them, and the state it applied to may be gone.\n if (state.history.log.ops.some((existing) => existing.id === id)) return;\n const parsed = parseAppendedOperation(\n registry,\n op,\n state.document,\n state.source as SourceDescriptor,\n );\n setHistory(hist.dispatch(state.history, parsed));\n },\n undo() {\n setHistory(hist.undo(state.history));\n },\n redo() {\n setHistory(hist.redo(state.history));\n },\n timeTravel(index) {\n setHistory(hist.timeTravel(state.history, index));\n },\n canUndo: () => hist.canUndo(state.history),\n canRedo: () => hist.canRedo(state.history),\n getState: () => state,\n getEditLog: () => ({ log: state.history.log, index: state.history.index }),\n getDocument: () => state.document,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n async renderPreview() {\n ensureReady();\n if (timer) clearTimeout(timer);\n timer = null;\n const result = await runPreview();\n if (result) return result;\n if (state.preview && state.preview.version === state.version) return state.preview;\n throw state.error ?? new SealpixelError('ABORTED', 'preview superseded');\n },\n\n whenIdle() {\n if (disposed || (!state.previewPending && !timer && !inflight)) return Promise.resolve();\n return new Promise((resolve) => idleResolvers.push(resolve));\n },\n\n setEditLog(saved, index) {\n ensureReady();\n const descriptor = state.source as SourceDescriptor;\n const resolved = resolveSavedState(saved);\n const log = resolved.log;\n if (\n log.source.hash !== undefined &&\n descriptor.hash !== undefined &&\n log.source.hash !== descriptor.hash\n ) {\n throw new SealpixelError(\n 'SOURCE_MISMATCH',\n 'the edit log belongs to a different image (hash differs)',\n );\n }\n if (log.source.width !== descriptor.width || log.source.height !== descriptor.height) {\n throw new SealpixelError('SOURCE_MISMATCH', 'the edit log has different source dimensions');\n }\n setHistory(\n hist.createHistory(\n { ...log, source: descriptor },\n index ?? resolved.index ?? log.ops.length,\n ),\n );\n },\n\n renderDetached,\n setPreviewTransform(transform) {\n previewTransform = transform;\n set({ version: state.version + 1 });\n schedulePreview();\n },\n\n async addAsset(bytes, assetOptions = {}) {\n ensureReady();\n const hash = await webCryptoSha256(bytes);\n const declaration: AssetDeclaration = {\n id: assetOptions.id ?? `asset.${hash.slice(0, 16)}`,\n hash,\n ...(assetOptions.url === undefined ? {} : { url: assetOptions.url }),\n };\n await renderer.putAsset(declaration.id, bytes);\n localAssets.set(declaration.id, bytes);\n const existing = state.history.log.assets ?? [];\n if (!existing.some((a) => a.id === declaration.id)) {\n const log: EditLog = { ...state.history.log, assets: [...existing, declaration] };\n set({ history: { ...state.history, log } });\n }\n return declaration;\n },\n\n async export(exportOptions) {\n ensureReady();\n if (!state.resident) {\n throw new SealpixelError(\n 'NOT_RESIDENT',\n `the image is larger than maxClientMegapixels (${maxClientMegapixels}), so its full resolution is not in the browser; render the original outside the browser with the log from getEditLog()`,\n );\n }\n const log = state.history.log;\n const upTo = exportOptions.upTo ?? state.history.index;\n const violations = registry.validateDocument(\n upTo === state.history.index ? state.document : compile(log, registry, upTo),\n log.source,\n );\n if (violations.length > 0) {\n throw new SealpixelError(\n 'OPTION_VIOLATION',\n violations.map((v) => `${v.plugin}: ${v.message}`).join('; '),\n violations,\n );\n }\n return renderer.export({\n log,\n output: exportOptions.output,\n upTo,\n ...(exportOptions.embedEditLog === undefined\n ? {}\n : { embedEditLog: exportOptions.embedEditLog }),\n });\n },\n\n async download(downloadOptions = {}) {\n ensureReady();\n const output = downloadOptions.output ?? { format: 'image/png' };\n const exportOptions: ExportOptions = {\n output,\n ...(downloadOptions.embedEditLog === undefined\n ? {}\n : { embedEditLog: downloadOptions.embedEditLog }),\n ...(downloadOptions.upTo === undefined ? {} : { upTo: downloadOptions.upTo }),\n };\n const save = options.saveFile ?? browserSaveFile;\n const result = await session.export(exportOptions);\n const filename =\n downloadOptions.filename ??\n `${state.source?.id ?? 'image'}-${result.hash.slice(0, 8)}.${EXT[output.format]}`;\n await save(result.bytes, filename, result.mimeType);\n return { filename, result };\n },\n\n dispose() {\n if (disposed) return;\n disposed = true;\n if (timer) clearTimeout(timer);\n timer = null;\n inflight?.controller.abort();\n inflight = null;\n listeners.clear();\n // No preview runs any more: settle every `whenIdle` that waits for one.\n set({ previewPending: false });\n settleIdle();\n if (ownsRenderer) renderer.dispose();\n },\n };\n\n function ensureAlive(): void {\n if (disposed) throw disposedError();\n }\n\n function ensureReady(): void {\n ensureAlive();\n if (state.status !== 'ready') throw new SealpixelError('NO_SOURCE', 'load an image first');\n }\n\n return session;\n}\n\n/** Default `saveFile`: an `<a download>` click, with the share sheet as a fallback on iOS Safari. */\nexport async function browserSaveFile(\n bytes: Uint8Array,\n filename: string,\n mimeType: string,\n): Promise<void> {\n if (typeof document === 'undefined' || typeof URL.createObjectURL !== 'function') {\n throw new SealpixelError(\n 'DOWNLOAD_UNSUPPORTED',\n 'no DOM available; pass saveFile to createEditorSession',\n );\n }\n const blob = new Blob([bytes as BlobPart], { type: mimeType });\n const nav = navigator as Navigator & { canShare?: (d: ShareData) => boolean };\n const isIOS = /iP(hone|ad|od)/.test(navigator.userAgent);\n if (\n isIOS &&\n typeof File !== 'undefined' &&\n nav.canShare?.({ files: [new File([blob], filename, { type: mimeType })] })\n ) {\n await navigator.share({ files: [new File([blob], filename, { type: mimeType })] });\n return;\n }\n const url = URL.createObjectURL(blob);\n try {\n const a = document.createElement('a');\n a.href = url;\n a.download = filename;\n a.rel = 'noopener';\n a.style.display = 'none';\n document.body.appendChild(a);\n a.click();\n a.remove();\n } finally {\n setTimeout(() => URL.revokeObjectURL(url), 10_000);\n }\n}\n"]}
@@ -87,12 +87,18 @@ export type ResultOf = {
87
87
  export interface Transport {
88
88
  postMessage(message: unknown, transfer?: ArrayBuffer[]): void;
89
89
  onMessage(handler: (message: unknown) => void): void;
90
+ /**
91
+ * Reports that the other side can no longer answer, for example a worker
92
+ * script that failed or a message that could not be deserialized. Optional:
93
+ * a transport without it never reports a failure.
94
+ */
95
+ onError?(handler: (reason: string) => void): void;
90
96
  close?(): void;
91
97
  }
92
98
  /** Adapter for a `Worker` or `DedicatedWorkerGlobalScope`. */
93
99
  export declare function webTransport(target: {
94
100
  postMessage(message: unknown, transfer?: Transferable[]): void;
95
- addEventListener(type: 'message', listener: (event: MessageEvent) => void): void;
101
+ addEventListener(type: string, listener: (event: MessageEvent) => void): void;
96
102
  terminate?(): void;
97
103
  close?(): void;
98
104
  }): Transport;
@@ -3,6 +3,14 @@ export function webTransport(target) {
3
3
  return {
4
4
  postMessage: (m, transfer) => target.postMessage(m, transfer ?? []),
5
5
  onMessage: (handler) => target.addEventListener('message', (e) => handler(e.data)),
6
+ onError: (handler) => {
7
+ const report = (event) => {
8
+ const message = event.message;
9
+ handler(typeof message === 'string' && message ? `${event.type}: ${message}` : event.type);
10
+ };
11
+ target.addEventListener('error', report);
12
+ target.addEventListener('messageerror', report);
13
+ },
6
14
  close: () => {
7
15
  target.terminate?.();
8
16
  target.close?.();
@@ -1 +1 @@
1
- {"version":3,"file":"worker-protocol.js","sourceRoot":"","sources":["../src/worker-protocol.ts"],"names":[],"mappings":"AA4DA,8DAA8D;AAC9D,MAAM,UAAU,YAAY,CAAC,MAK5B;IACC,OAAO;QACL,WAAW,EAAE,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,EAAE,QAAQ,IAAI,EAAE,CAAC;QACnE,SAAS,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QAClF,KAAK,EAAE,GAAG,EAAE;YACV,MAAM,CAAC,SAAS,EAAE,EAAE,CAAC;YACrB,MAAM,CAAC,KAAK,EAAE,EAAE,CAAC;QACnB,CAAC;KACF,CAAC;AACJ,CAAC;AAED,0EAA0E;AAC1E,MAAM,UAAU,eAAe,CAAC,KAAc;IAC5C,MAAM,GAAG,GAAkB,EAAE,CAAC;IAC9B,MAAM,KAAK,GAAG,CAAC,CAAU,EAAE,EAAE;QAC3B,IACE,CAAC,YAAY,UAAU;YACvB,CAAC,CAAC,MAAM,YAAY,WAAW;YAC/B,CAAC,CAAC,UAAU,KAAK,CAAC;YAClB,CAAC,CAAC,UAAU,KAAK,CAAC,CAAC,MAAM,CAAC,UAAU,EACpC,CAAC;YACD,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;QACrB,CAAC;aAAM,IAAI,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,CAAC,YAAY,UAAU,CAAC,EAAE,CAAC;YACpE,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,CAA4B,CAAC;gBAAE,KAAK,CAAC,KAAK,CAAC,CAAC;QAChF,CAAC;IACH,CAAC,CAAC;IACF,KAAK,CAAC,KAAK,CAAC,CAAC;IACb,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/**\n * Messages between `WorkerRenderer` (main thread) and `startSealpixelWorker`.\n * Buffers travel as transferables; everything else is structured-cloned.\n */\nimport type { RgbaBuffer } from '@sealpixel/wasm';\nimport type { Geometry } from './plan.js';\nimport type {\n ExportRequest,\n ExportResult,\n LoadedSource,\n RendererLoadOptions,\n RenderRequest,\n} from './renderer-core.js';\nimport type { SourceDescriptor } from './types.js';\n\nexport type WorkerRequest =\n | { id: number; type: 'init' }\n | { id: number; type: 'load'; bytes: Uint8Array; sourceId: string; options?: RendererLoadOptions }\n | { id: number; type: 'loadWorkingCopy'; workingCopy: RgbaBuffer; descriptor: SourceDescriptor }\n | { id: number; type: 'loadWorkingCopyEncoded'; bytes: Uint8Array; descriptor: SourceDescriptor }\n | { id: number; type: 'render'; req: Omit<RenderRequest, 'signal'> }\n | { id: number; type: 'export'; req: ExportRequest }\n | {\n id: number;\n type: 'geometry';\n log: RenderRequest['log'];\n target: 'workingCopy' | 'full';\n upTo?: number;\n }\n | { id: number; type: 'unload' }\n | { id: number; type: 'asset'; assetId: string; bytes: Uint8Array }\n | { id: number; type: 'abort'; target: number };\n\nexport type WorkerResponse =\n | { id: number; ok: true; result: unknown }\n | { id: number; ok: false; error: { name: string; message: string; details?: unknown } };\n\nexport type ResultOf = {\n init: { coreVersion: string; plugins: Record<string, number> };\n load: LoadedSource;\n loadWorkingCopy: LoadedSource;\n loadWorkingCopyEncoded: LoadedSource;\n render: RgbaBuffer;\n export: ExportResult;\n geometry: Geometry;\n unload: undefined;\n asset: undefined;\n abort: undefined;\n};\n\n/**\n * Minimal transport both sides need. Web Workers (`self`, `Worker`) and\n * Node's `MessagePort` satisfy it directly or through a small adapter.\n */\nexport interface Transport {\n postMessage(message: unknown, transfer?: ArrayBuffer[]): void;\n onMessage(handler: (message: unknown) => void): void;\n close?(): void;\n}\n\n/** Adapter for a `Worker` or `DedicatedWorkerGlobalScope`. */\nexport function webTransport(target: {\n postMessage(message: unknown, transfer?: Transferable[]): void;\n addEventListener(type: 'message', listener: (event: MessageEvent) => void): void;\n terminate?(): void;\n close?(): void;\n}): Transport {\n return {\n postMessage: (m, transfer) => target.postMessage(m, transfer ?? []),\n onMessage: (handler) => target.addEventListener('message', (e) => handler(e.data)),\n close: () => {\n target.terminate?.();\n target.close?.();\n },\n };\n}\n\n/** Buffers inside a message that can be transferred instead of copied. */\nexport function transferablesOf(value: unknown): ArrayBuffer[] {\n const out: ArrayBuffer[] = [];\n const visit = (v: unknown) => {\n if (\n v instanceof Uint8Array &&\n v.buffer instanceof ArrayBuffer &&\n v.byteOffset === 0 &&\n v.byteLength === v.buffer.byteLength\n ) {\n out.push(v.buffer);\n } else if (v && typeof v === 'object' && !(v instanceof Uint8Array)) {\n for (const inner of Object.values(v as Record<string, unknown>)) visit(inner);\n }\n };\n visit(value);\n return out;\n}\n"]}
1
+ {"version":3,"file":"worker-protocol.js","sourceRoot":"","sources":["../src/worker-protocol.ts"],"names":[],"mappings":"AAkEA,8DAA8D;AAC9D,MAAM,UAAU,YAAY,CAAC,MAK5B;IACC,OAAO;QACL,WAAW,EAAE,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,EAAE,QAAQ,IAAI,EAAE,CAAC;QACnE,SAAS,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,CAA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;gBAAE,KAAK,CAAC,KAAK,CAAC,CAAC;QAChF,CAAC;IACH,CAAC,CAAC;IACF,KAAK,CAAC,KAAK,CAAC,CAAC;IACb,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/**\n * Messages between `WorkerRenderer` (main thread) and `startSealpixelWorker`.\n * Buffers travel as transferables; everything else is structured-cloned.\n */\nimport type { RgbaBuffer } from '@sealpixel/wasm';\nimport type { Geometry } from './plan.js';\nimport type {\n ExportRequest,\n ExportResult,\n LoadedSource,\n RendererLoadOptions,\n RenderRequest,\n} from './renderer-core.js';\nimport type { SourceDescriptor } from './types.js';\n\nexport type WorkerRequest =\n | { id: number; type: 'init' }\n | { id: number; type: 'load'; bytes: Uint8Array; sourceId: string; options?: RendererLoadOptions }\n | { id: number; type: 'loadWorkingCopy'; workingCopy: RgbaBuffer; descriptor: SourceDescriptor }\n | { id: number; type: 'loadWorkingCopyEncoded'; bytes: Uint8Array; descriptor: SourceDescriptor }\n | { id: number; type: 'render'; req: Omit<RenderRequest, 'signal'> }\n | { id: number; type: 'export'; req: ExportRequest }\n | {\n id: number;\n type: 'geometry';\n log: RenderRequest['log'];\n target: 'workingCopy' | 'full';\n upTo?: number;\n }\n | { id: number; type: 'unload' }\n | { id: number; type: 'asset'; assetId: string; bytes: Uint8Array }\n | { id: number; type: 'abort'; target: number };\n\nexport type WorkerResponse =\n | { id: number; ok: true; result: unknown }\n | { id: number; ok: false; error: { name: string; message: string; details?: unknown } };\n\nexport type ResultOf = {\n init: { coreVersion: string; plugins: Record<string, number> };\n load: LoadedSource;\n loadWorkingCopy: LoadedSource;\n loadWorkingCopyEncoded: LoadedSource;\n render: RgbaBuffer;\n export: ExportResult;\n geometry: Geometry;\n unload: undefined;\n asset: undefined;\n abort: undefined;\n};\n\n/**\n * Minimal transport both sides need. Web Workers (`self`, `Worker`) and\n * Node's `MessagePort` satisfy it directly or through a small adapter.\n */\nexport interface Transport {\n postMessage(message: unknown, transfer?: ArrayBuffer[]): void;\n onMessage(handler: (message: unknown) => void): void;\n /**\n * Reports that the other side can no longer answer, for example a worker\n * script that failed or a message that could not be deserialized. Optional:\n * a transport without it never reports a failure.\n */\n onError?(handler: (reason: string) => void): void;\n close?(): void;\n}\n\n/** Adapter for a `Worker` or `DedicatedWorkerGlobalScope`. */\nexport function webTransport(target: {\n postMessage(message: unknown, transfer?: Transferable[]): void;\n addEventListener(type: string, listener: (event: MessageEvent) => void): void;\n terminate?(): void;\n close?(): void;\n}): Transport {\n return {\n postMessage: (m, transfer) => target.postMessage(m, transfer ?? []),\n onMessage: (handler) => target.addEventListener('message', (e) => handler(e.data)),\n onError: (handler) => {\n const report = (event: Event) => {\n const message = (event as { message?: unknown }).message;\n handler(typeof message === 'string' && message ? `${event.type}: ${message}` : event.type);\n };\n target.addEventListener('error', report);\n target.addEventListener('messageerror', report);\n },\n close: () => {\n target.terminate?.();\n target.close?.();\n },\n };\n}\n\n/** Buffers inside a message that can be transferred instead of copied. */\nexport function transferablesOf(value: unknown): ArrayBuffer[] {\n const out: ArrayBuffer[] = [];\n const visit = (v: unknown) => {\n if (\n v instanceof Uint8Array &&\n v.buffer instanceof ArrayBuffer &&\n v.byteOffset === 0 &&\n v.byteLength === v.buffer.byteLength\n ) {\n out.push(v.buffer);\n } else if (v && typeof v === 'object' && !(v instanceof Uint8Array)) {\n for (const inner of Object.values(v as Record<string, unknown>)) visit(inner);\n }\n };\n visit(value);\n return out;\n}\n"]}
@@ -8,6 +8,8 @@ export declare class WorkerRenderer implements Renderer {
8
8
  private readonly transport;
9
9
  private nextId;
10
10
  private readonly pending;
11
+ /** Set once the worker cannot answer any more. Every call then fails with it at once. */
12
+ private failure;
11
13
  /** Accepts a Web `Worker` or any `Transport`. */
12
14
  constructor(worker: Worker | Transport);
13
15
  init(): Promise<{
@@ -23,6 +25,8 @@ export declare class WorkerRenderer implements Renderer {
23
25
  unload(): Promise<void>;
24
26
  putAsset(id: string, bytes: Uint8Array): Promise<void>;
25
27
  dispose(): void;
28
+ /** Rejects every pending call with `error` and fails every later call with it. */
29
+ private fail;
26
30
  private call;
27
31
  private send;
28
32
  /**
@@ -5,10 +5,18 @@ export class WorkerRenderer {
5
5
  transport;
6
6
  nextId = 1;
7
7
  pending = new Map();
8
+ /** Set once the worker cannot answer any more. Every call then fails with it at once. */
9
+ failure = null;
8
10
  /** Accepts a Web `Worker` or any `Transport`. */
9
11
  constructor(worker) {
10
12
  this.transport = 'onMessage' in worker ? worker : webTransport(worker);
11
13
  this.transport.onMessage((message) => this.receive(message));
14
+ // Without this, a worker that fails leaves every pending call waiting forever.
15
+ this.transport.onError?.((reason) => {
16
+ if (this.failure)
17
+ return;
18
+ this.fail(new SealpixelError('KERNEL_FAILED', `the render worker failed (${reason})`));
19
+ });
12
20
  }
13
21
  init() {
14
22
  return this.call({ type: 'init' });
@@ -56,10 +64,17 @@ export class WorkerRenderer {
56
64
  await this.call({ type: 'asset', assetId: id, bytes });
57
65
  }
58
66
  dispose() {
67
+ if (this.failure?.name !== 'ABORTED') {
68
+ this.fail(new SealpixelError('ABORTED', 'renderer disposed'));
69
+ }
70
+ this.transport.close?.();
71
+ }
72
+ /** Rejects every pending call with `error` and fails every later call with it. */
73
+ fail(error) {
74
+ this.failure = error;
59
75
  for (const p of this.pending.values())
60
- p.reject(new SealpixelError('ABORTED', 'renderer disposed'));
76
+ p.reject(error);
61
77
  this.pending.clear();
62
- this.transport.close?.();
63
78
  }
64
79
  call(req) {
65
80
  const id = this.nextId++;
@@ -67,6 +82,10 @@ export class WorkerRenderer {
67
82
  }
68
83
  send(id, req) {
69
84
  return new Promise((resolve, reject) => {
85
+ if (this.failure) {
86
+ reject(this.failure);
87
+ return;
88
+ }
70
89
  this.pending.set(id, { resolve, reject });
71
90
  this.post(req);
72
91
  });
@@ -1 +1 @@
1
- {"version":3,"file":"worker-renderer.js","sourceRoot":"","sources":["../src/worker-renderer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAA2B,MAAM,aAAa,CAAC;AAItE,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5C,KAAK,CAAC,MAAM,CACV,IAAI,cAAc,CAChB,OAAO,CAAC,KAAK,CAAC,IAA0B,EACxC,OAAO,CAAC,KAAK,CAAC,OAAO,EACrB,OAAO,CAAC,KAAK,CAAC,OAAO,CACtB,CACF,CAAC;IACN,CAAC;CACF","sourcesContent":["import type { RgbaBuffer } from '@sealpixel/wasm';\nimport { SealpixelError, type SealpixelErrorCode } from './errors.js';\nimport type { Renderer } from './renderer.js';\nimport type { RendererLoadOptions, RenderRequest } from './renderer-core.js';\nimport type { SourceDescriptor } from './types.js';\nimport {\n type ResultOf,\n type Transport,\n type WorkerRequest,\n type WorkerResponse,\n webTransport,\n} from './worker-protocol.js';\n\n/** Distributive `Omit<R, 'id'>` over a union. */\ntype WithoutId<R> = R extends { id: number } ? Omit<R, 'id'> : never;\n\n/** Talks to a worker started with `startSealpixelWorker`. */\nexport class WorkerRenderer implements Renderer {\n private readonly transport: Transport;\n private nextId = 1;\n private readonly pending = new Map<\n number,\n { resolve: (v: unknown) => void; reject: (e: Error) => void }\n >();\n\n /** Accepts a Web `Worker` or any `Transport`. */\n constructor(worker: Worker | Transport) {\n this.transport = 'onMessage' in worker ? worker : webTransport(worker as Worker);\n this.transport.onMessage((message) => this.receive(message as WorkerResponse));\n }\n\n init() {\n return this.call<'init'>({ type: 'init' });\n }\n load(bytes: Uint8Array, id: string, options?: RendererLoadOptions) {\n return this.call<'load'>({\n type: 'load',\n bytes,\n sourceId: id,\n ...(options ? { options } : {}),\n });\n }\n loadWorkingCopy(workingCopy: RgbaBuffer, descriptor: SourceDescriptor) {\n return this.call<'loadWorkingCopy'>({ type: 'loadWorkingCopy', workingCopy, descriptor });\n }\n loadWorkingCopyEncoded(bytes: Uint8Array, descriptor: SourceDescriptor) {\n return this.call<'loadWorkingCopyEncoded'>({\n type: 'loadWorkingCopyEncoded',\n bytes,\n descriptor,\n });\n }\n async render(req: RenderRequest): Promise<RgbaBuffer> {\n const { signal, ...rest } = req;\n const id = this.nextId++;\n const onAbort = () => this.post({ id: this.nextId++, type: 'abort', target: id });\n signal?.addEventListener('abort', onAbort, { once: true });\n try {\n return (await this.send(id, { id, type: 'render', req: rest })) as RgbaBuffer;\n } finally {\n signal?.removeEventListener('abort', onAbort);\n }\n }\n export(req: Parameters<Renderer['export']>[0]) {\n return this.call<'export'>({ type: 'export', req });\n }\n geometry(req: Parameters<Renderer['geometry']>[0]) {\n return this.call<'geometry'>({ type: 'geometry', ...req });\n }\n async unload() {\n await this.call<'unload'>({ type: 'unload' });\n }\n async putAsset(id: string, bytes: Uint8Array) {\n await this.call<'asset'>({ type: 'asset', assetId: id, bytes });\n }\n dispose() {\n for (const p of this.pending.values())\n p.reject(new SealpixelError('ABORTED', 'renderer disposed'));\n this.pending.clear();\n this.transport.close?.();\n }\n\n private call<T extends WorkerRequest['type']>(\n req: WithoutId<Extract<WorkerRequest, { type: T }>>,\n ): Promise<ResultOf[T]> {\n const id = this.nextId++;\n return this.send(id, { ...req, id } as WorkerRequest) as Promise<ResultOf[T]>;\n }\n\n private send(id: number, req: WorkerRequest): Promise<unknown> {\n return new Promise((resolve, reject) => {\n this.pending.set(id, { resolve, reject });\n this.post(req);\n });\n }\n\n /**\n * Requests are structured-cloned, never transferred: callers keep ownership\n * of the bytes they pass in. Results travel back as transferables.\n */\n private post(req: WorkerRequest): void {\n this.transport.postMessage(req);\n }\n\n private receive(message: WorkerResponse): void {\n if (!message || typeof message !== 'object' || typeof message.id !== 'number') return;\n const entry = this.pending.get(message.id);\n if (!entry) return;\n this.pending.delete(message.id);\n if (message.ok) entry.resolve(message.result);\n else\n entry.reject(\n new SealpixelError(\n message.error.name as SealpixelErrorCode,\n message.error.message,\n message.error.details,\n ),\n );\n }\n}\n"]}
1
+ {"version":3,"file":"worker-renderer.js","sourceRoot":"","sources":["../src/worker-renderer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAA2B,MAAM,aAAa,CAAC;AAItE,OAAO,EAKL,YAAY,GACb,MAAM,sBAAsB,CA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AG,CAAC,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;OAGG;IACK,IAAI,CAAC,GAAkB;QAC7B,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;IAClC,CAAC;IAEO,OAAO,CAAC,OAAuB;QACrC,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,OAAO,CAAC,EAAE,KAAK,QAAQ;YAAE,OAAO;QACtF,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,KAAK;YAAE,OAAO;QACnB,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;QAChC,IAAI,OAAO,CAAC,EAAE;YAAE,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;;YAE5C,KAAK,CAAC,MAAM,CACV,IAAI,cAAc,CAChB,OAAO,CAAC,KAAK,CAAC,IAA0B,EACxC,OAAO,CAAC,KAAK,CAAC,OAAO,EACrB,OAAO,CAAC,KAAK,CAAC,OAAO,CACtB,CACF,CAAC;IACN,CAAC;CACF","sourcesContent":["import type { RgbaBuffer } from '@sealpixel/wasm';\nimport { SealpixelError, type SealpixelErrorCode } from './errors.js';\nimport type { Renderer } from './renderer.js';\nimport type { RendererLoadOptions, RenderRequest } from './renderer-core.js';\nimport type { SourceDescriptor } from './types.js';\nimport {\n type ResultOf,\n type Transport,\n type WorkerRequest,\n type WorkerResponse,\n webTransport,\n} from './worker-protocol.js';\n\n/** Distributive `Omit<R, 'id'>` over a union. */\ntype WithoutId<R> = R extends { id: number } ? Omit<R, 'id'> : never;\n\n/** Talks to a worker started with `startSealpixelWorker`. */\nexport class WorkerRenderer implements Renderer {\n private readonly transport: Transport;\n private nextId = 1;\n private readonly pending = new Map<\n number,\n { resolve: (v: unknown) => void; reject: (e: Error) => void }\n >();\n /** Set once the worker cannot answer any more. Every call then fails with it at once. */\n private failure: SealpixelError | null = null;\n\n /** Accepts a Web `Worker` or any `Transport`. */\n constructor(worker: Worker | Transport) {\n this.transport = 'onMessage' in worker ? worker : webTransport(worker as Worker);\n this.transport.onMessage((message) => this.receive(message as WorkerResponse));\n // Without this, a worker that fails leaves every pending call waiting forever.\n this.transport.onError?.((reason) => {\n if (this.failure) return;\n this.fail(new SealpixelError('KERNEL_FAILED', `the render worker failed (${reason})`));\n });\n }\n\n init() {\n return this.call<'init'>({ type: 'init' });\n }\n load(bytes: Uint8Array, id: string, options?: RendererLoadOptions) {\n return this.call<'load'>({\n type: 'load',\n bytes,\n sourceId: id,\n ...(options ? { options } : {}),\n });\n }\n loadWorkingCopy(workingCopy: RgbaBuffer, descriptor: SourceDescriptor) {\n return this.call<'loadWorkingCopy'>({ type: 'loadWorkingCopy', workingCopy, descriptor });\n }\n loadWorkingCopyEncoded(bytes: Uint8Array, descriptor: SourceDescriptor) {\n return this.call<'loadWorkingCopyEncoded'>({\n type: 'loadWorkingCopyEncoded',\n bytes,\n descriptor,\n });\n }\n async render(req: RenderRequest): Promise<RgbaBuffer> {\n const { signal, ...rest } = req;\n const id = this.nextId++;\n const onAbort = () => this.post({ id: this.nextId++, type: 'abort', target: id });\n signal?.addEventListener('abort', onAbort, { once: true });\n try {\n return (await this.send(id, { id, type: 'render', req: rest })) as RgbaBuffer;\n } finally {\n signal?.removeEventListener('abort', onAbort);\n }\n }\n export(req: Parameters<Renderer['export']>[0]) {\n return this.call<'export'>({ type: 'export', req });\n }\n geometry(req: Parameters<Renderer['geometry']>[0]) {\n return this.call<'geometry'>({ type: 'geometry', ...req });\n }\n async unload() {\n await this.call<'unload'>({ type: 'unload' });\n }\n async putAsset(id: string, bytes: Uint8Array) {\n await this.call<'asset'>({ type: 'asset', assetId: id, bytes });\n }\n dispose() {\n if (this.failure?.name !== 'ABORTED') {\n this.fail(new SealpixelError('ABORTED', 'renderer disposed'));\n }\n this.transport.close?.();\n }\n\n /** Rejects every pending call with `error` and fails every later call with it. */\n private fail(error: SealpixelError): void {\n this.failure = error;\n for (const p of this.pending.values()) p.reject(error);\n this.pending.clear();\n }\n\n private call<T extends WorkerRequest['type']>(\n req: WithoutId<Extract<WorkerRequest, { type: T }>>,\n ): Promise<ResultOf[T]> {\n const id = this.nextId++;\n return this.send(id, { ...req, id } as WorkerRequest) as Promise<ResultOf[T]>;\n }\n\n private send(id: number, req: WorkerRequest): Promise<unknown> {\n return new Promise((resolve, reject) => {\n if (this.failure) {\n reject(this.failure);\n return;\n }\n this.pending.set(id, { resolve, reject });\n this.post(req);\n });\n }\n\n /**\n * Requests are structured-cloned, never transferred: callers keep ownership\n * of the bytes they pass in. Results travel back as transferables.\n */\n private post(req: WorkerRequest): void {\n this.transport.postMessage(req);\n }\n\n private receive(message: WorkerResponse): void {\n if (!message || typeof message !== 'object' || typeof message.id !== 'number') return;\n const entry = this.pending.get(message.id);\n if (!entry) return;\n this.pending.delete(message.id);\n if (message.ok) entry.resolve(message.result);\n else\n entry.reject(\n new SealpixelError(\n message.error.name as SealpixelErrorCode,\n message.error.message,\n message.error.details,\n ),\n );\n }\n}\n"]}