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

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 (91) hide show
  1. package/LICENSE.md +2 -2
  2. package/dist/assets.d.ts +0 -1
  3. package/dist/assets.js.map +1 -1
  4. package/dist/canonical-json.d.ts +0 -1
  5. package/dist/canonical-json.js.map +1 -1
  6. package/dist/compile.d.ts +0 -1
  7. package/dist/compile.js.map +1 -1
  8. package/dist/embedded.d.ts +0 -1
  9. package/dist/embedded.js.map +1 -1
  10. package/dist/errors.d.ts +1 -2
  11. package/dist/errors.js.map +1 -1
  12. package/dist/external-kernel.d.ts +0 -1
  13. package/dist/external-kernel.js.map +1 -1
  14. package/dist/generated/geometry.d.ts +1 -2
  15. package/dist/generated/geometry.js.map +1 -1
  16. package/dist/generated/output.d.ts +0 -1
  17. package/dist/generated/output.js.map +1 -1
  18. package/dist/generated/plan.d.ts +18 -7
  19. package/dist/generated/plan.js.map +1 -1
  20. package/dist/history.d.ts +2 -1
  21. package/dist/history.js +5 -1
  22. package/dist/history.js.map +1 -1
  23. package/dist/image-size.d.ts +4 -3
  24. package/dist/image-size.js +5 -3
  25. package/dist/image-size.js.map +1 -1
  26. package/dist/index.d.ts +4 -4
  27. package/dist/index.js +2 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/inline-renderer.d.ts +4 -5
  30. package/dist/inline-renderer.js +7 -7
  31. package/dist/inline-renderer.js.map +1 -1
  32. package/dist/manifest.d.ts +127 -0
  33. package/dist/manifest.js +115 -0
  34. package/dist/manifest.js.map +1 -0
  35. package/dist/options.d.ts +0 -1
  36. package/dist/options.js.map +1 -1
  37. package/dist/plan.d.ts +0 -1
  38. package/dist/plan.js +1 -1
  39. package/dist/plan.js.map +1 -1
  40. package/dist/plugin.d.ts +0 -1
  41. package/dist/plugin.js.map +1 -1
  42. package/dist/registry.d.ts +0 -1
  43. package/dist/registry.js +10 -1
  44. package/dist/registry.js.map +1 -1
  45. package/dist/render.d.ts +21 -1
  46. package/dist/render.js +148 -12
  47. package/dist/render.js.map +1 -1
  48. package/dist/renderer-core.d.ts +24 -17
  49. package/dist/renderer-core.js +36 -22
  50. package/dist/renderer-core.js.map +1 -1
  51. package/dist/renderer.d.ts +5 -6
  52. package/dist/renderer.js.map +1 -1
  53. package/dist/session.d.ts +30 -50
  54. package/dist/session.js +142 -169
  55. package/dist/session.js.map +1 -1
  56. package/dist/types.d.ts +18 -3
  57. package/dist/types.js.map +1 -1
  58. package/dist/worker-protocol.d.ts +8 -8
  59. package/dist/worker-protocol.js.map +1 -1
  60. package/dist/worker-renderer.d.ts +4 -5
  61. package/dist/worker-renderer.js +15 -6
  62. package/dist/worker-renderer.js.map +1 -1
  63. package/dist/worker.d.ts +0 -1
  64. package/dist/worker.js +6 -6
  65. package/dist/worker.js.map +1 -1
  66. package/package.json +6 -6
  67. package/dist/assets.d.ts.map +0 -1
  68. package/dist/canonical-json.d.ts.map +0 -1
  69. package/dist/compile.d.ts.map +0 -1
  70. package/dist/embedded.d.ts.map +0 -1
  71. package/dist/errors.d.ts.map +0 -1
  72. package/dist/external-kernel.d.ts.map +0 -1
  73. package/dist/generated/geometry.d.ts.map +0 -1
  74. package/dist/generated/output.d.ts.map +0 -1
  75. package/dist/generated/plan.d.ts.map +0 -1
  76. package/dist/history.d.ts.map +0 -1
  77. package/dist/image-size.d.ts.map +0 -1
  78. package/dist/index.d.ts.map +0 -1
  79. package/dist/inline-renderer.d.ts.map +0 -1
  80. package/dist/options.d.ts.map +0 -1
  81. package/dist/plan.d.ts.map +0 -1
  82. package/dist/plugin.d.ts.map +0 -1
  83. package/dist/registry.d.ts.map +0 -1
  84. package/dist/render.d.ts.map +0 -1
  85. package/dist/renderer-core.d.ts.map +0 -1
  86. package/dist/renderer.d.ts.map +0 -1
  87. package/dist/session.d.ts.map +0 -1
  88. package/dist/types.d.ts.map +0 -1
  89. package/dist/worker-protocol.d.ts.map +0 -1
  90. package/dist/worker-renderer.d.ts.map +0 -1
  91. package/dist/worker.d.ts.map +0 -1
@@ -1,6 +1,6 @@
1
1
  import type { RgbaBuffer } from '@sealpixel/wasm';
2
2
  import type { Geometry } from './plan.js';
3
- import type { ExportRequest, ExportResult, LoadedSource, RenderRequest } from './renderer-core.js';
3
+ import type { ExportRequest, ExportResult, LoadedSource, RendererLoadOptions, RenderRequest } from './renderer-core.js';
4
4
  import type { SourceDescriptor } from './types.js';
5
5
  /**
6
6
  * What the session talks to. Implemented by `InlineRenderer` (same thread)
@@ -11,14 +11,14 @@ export interface Renderer {
11
11
  coreVersion: string;
12
12
  plugins: Record<string, number>;
13
13
  }>;
14
- load(bytes: Uint8Array, id: string): Promise<LoadedSource>;
15
- loadProxy(proxy: RgbaBuffer, descriptor: SourceDescriptor): Promise<LoadedSource>;
16
- loadProxyEncoded(bytes: Uint8Array, descriptor: SourceDescriptor): Promise<LoadedSource>;
14
+ load(bytes: Uint8Array, id: string, options?: RendererLoadOptions): Promise<LoadedSource>;
15
+ loadWorkingCopy(workingCopy: RgbaBuffer, descriptor: SourceDescriptor): Promise<LoadedSource>;
16
+ loadWorkingCopyEncoded(bytes: Uint8Array, descriptor: SourceDescriptor): Promise<LoadedSource>;
17
17
  render(req: RenderRequest): Promise<RgbaBuffer>;
18
18
  export(req: ExportRequest): Promise<ExportResult>;
19
19
  geometry(req: {
20
20
  log: RenderRequest['log'];
21
- target: 'proxy' | 'full';
21
+ target: 'workingCopy' | 'full';
22
22
  upTo?: number;
23
23
  }): Promise<Geometry>;
24
24
  unload(): Promise<void>;
@@ -26,4 +26,3 @@ export interface Renderer {
26
26
  putAsset(id: string, bytes: Uint8Array): Promise<void>;
27
27
  dispose(): void;
28
28
  }
29
- //# sourceMappingURL=renderer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"renderer.js","sourceRoot":"","sources":["../src/renderer.ts"],"names":[],"mappings":""}
1
+ {"version":3,"file":"renderer.js","sourceRoot":"","sources":["../src/renderer.ts"],"names":[],"mappings":"","sourcesContent":["import 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\n/**\n * What the session talks to. Implemented by `InlineRenderer` (same thread)\n * and `WorkerRenderer` (message protocol to a worker running `startSealpixelWorker`).\n */\nexport interface Renderer {\n init(): Promise<{ coreVersion: string; plugins: Record<string, number> }>;\n load(bytes: Uint8Array, id: string, options?: RendererLoadOptions): Promise<LoadedSource>;\n loadWorkingCopy(workingCopy: RgbaBuffer, descriptor: SourceDescriptor): Promise<LoadedSource>;\n loadWorkingCopyEncoded(bytes: Uint8Array, descriptor: SourceDescriptor): Promise<LoadedSource>;\n render(req: RenderRequest): Promise<RgbaBuffer>;\n export(req: ExportRequest): Promise<ExportResult>;\n geometry(req: {\n log: RenderRequest['log'];\n target: 'workingCopy' | 'full';\n upTo?: number;\n }): Promise<Geometry>;\n unload(): Promise<void>;\n /** Stores a verified asset for kernels that reference it by id. */\n putAsset(id: string, bytes: Uint8Array): Promise<void>;\n dispose(): void;\n}\n"]}
package/dist/session.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Headless editor session. Owns the edit log (as `History`), the derived
3
3
  * document, and a renderer. Every state change schedules a debounced preview
4
- * render on the proxy; stale results are discarded by version.
4
+ * render on the working copy; stale results are discarded by version.
5
5
  */
6
6
  import type { RgbaBuffer } from '@sealpixel/wasm';
7
7
  import { type AssetResolver } from './assets.js';
@@ -25,6 +25,16 @@ export interface SessionOptions {
25
25
  plugins: readonly AnyPlugin[];
26
26
  /** Defaults to an `InlineRenderer` built from `plugins`. Pass a `WorkerRenderer` in browsers. */
27
27
  renderer?: Renderer;
28
+ /**
29
+ * How much of the original stays in the browser. Default 16 megapixels and
30
+ * 50e6 bytes, enough for a camera JPEG of 60 megapixels. An image above
31
+ * `maxClientMegapixels` is not resident: the preview works on a working
32
+ * copy, and `export` fails with `NOT_RESIDENT`: the host renders the
33
+ * original elsewhere. An image above
34
+ * `maxClientBytes` does not load at all (`TOO_LARGE`). The megapixel limit
35
+ * reaches the renderer with every load, so a shared worker follows the
36
+ * session that loads into it.
37
+ */
28
38
  limits?: {
29
39
  maxClientMegapixels?: number;
30
40
  maxClientBytes?: number;
@@ -34,19 +44,12 @@ export interface SessionOptions {
34
44
  enabled?: boolean;
35
45
  };
36
46
  /**
37
- * Server rendering: `endpoint` accepts the `@sealpixel/server` contract. Used
38
- * by `requestServerRender`, by `download({ via: 'server' })`, and by the
39
- * `server` proxy strategy for images above the client limits.
47
+ * The preview image. The session always decodes the original in WebAssembly
48
+ * and downscales it itself. `maxSide` is the longest side for the default
49
+ * renderer. Default 2048. A `renderer` passed in uses its own setting.
40
50
  */
41
- server?: {
42
- endpoint: string;
43
- fetch?: typeof fetch;
44
- headers?: Record<string, string>;
45
- };
46
- /** How to obtain the preview for images above the client limits. Default `auto`. */
47
- proxy?: {
51
+ workingCopy?: {
48
52
  maxSide?: number;
49
- strategy?: 'auto' | 'wasm' | 'server';
50
53
  };
51
54
  /** Fonts and images referenced by the log. Defaults to the plugins' declarations with relative urls. */
52
55
  assets?: AssetResolver;
@@ -90,15 +93,20 @@ export interface ExportOptions {
90
93
  }
91
94
  export interface DownloadOptions extends Partial<ExportOptions> {
92
95
  filename?: string;
93
- /** `auto` renders locally when the image is resident, otherwise on the server. */
94
- via?: 'auto' | 'local' | 'server';
95
96
  }
96
97
  export interface EditorSession {
97
98
  readonly registry: Registry;
99
+ /**
100
+ * Loads an image, optionally resuming a saved state. On failure the session
101
+ * stays on the previous image: the state and the renderer keep describing
102
+ * it. When a newer `load` starts before this one finishes, this one rejects
103
+ * with `ABORTED` and the newer one wins.
104
+ */
98
105
  load(source: LoadSource, options?: LoadOptions): Promise<SourceDescriptor>;
99
106
  dispatch(op: Operation): void;
100
107
  undo(): void;
101
108
  redo(): void;
109
+ /** Moves to `index`, clamped to the log. A non-finite index, such as `NaN`, changes nothing. */
102
110
  timeTravel(index: number): void;
103
111
  canUndo(): boolean;
104
112
  canRedo(): boolean;
@@ -124,7 +132,7 @@ export interface EditorSession {
124
132
  */
125
133
  setPreviewTransform(transform: ((log: EditLog) => EditLog) | null): void;
126
134
  /**
127
- * Renders a proxy-sized image from the current log, transformed, and returns
135
+ * Renders a working-copy-sized image from the current log, transformed, and returns
128
136
  * it without touching the stage, the state or the history. Tools use it to
129
137
  * show what an edit the user has not made yet would look like: the filter
130
138
  * tool renders its thumbnails from the log with the filter removed, so a
@@ -142,47 +150,19 @@ export interface EditorSession {
142
150
  id?: string;
143
151
  url?: string;
144
152
  }): Promise<AssetDeclaration>;
153
+ /**
154
+ * Renders the full resolution in the browser. Throws `NOT_RESIDENT` when the
155
+ * image is above `maxClientMegapixels`: the host then renders the original
156
+ * elsewhere, from the log that `getEditLog()` returns.
157
+ */
145
158
  export(options: ExportOptions): Promise<ExportResult>;
159
+ /** Exports like `export` and hands the file to `saveFile`. */
146
160
  download(options?: DownloadOptions): Promise<{
147
161
  filename: string;
148
- result: ExportResult | ServerRenderResult;
162
+ result: ExportResult;
149
163
  }>;
150
- /**
151
- * Renders on the server from the original bytes (inline) or a host-provided
152
- * source reference. With `destination: 's3'` the server stores the object and
153
- * returns its key and presigned url; otherwise the bytes come back.
154
- */
155
- requestServerRender(options: ServerRenderOptions): Promise<ServerRenderResult>;
156
164
  dispose(): void;
157
165
  }
158
- export interface ServerRenderOptions extends ExportOptions {
159
- /** Defaults to the loaded bytes sent inline. Hosts that uploaded the original pass its reference. */
160
- source?: {
161
- kind: 's3';
162
- bucket?: string;
163
- key: string;
164
- } | {
165
- kind: 'url';
166
- url: string;
167
- };
168
- destination?: 's3' | 'response';
169
- endpoint?: string;
170
- }
171
- export interface ServerRenderResult {
172
- /** Present for `destination: 'response'`. */
173
- bytes?: Uint8Array;
174
- /** Present for `destination: 's3'`. */
175
- url?: string | null;
176
- objectKey?: string;
177
- bucket?: string;
178
- hash: string;
179
- width: number;
180
- height: number;
181
- mimeType: OutputOptions['format'];
182
- cached: boolean;
183
- jobKey: string;
184
- }
185
166
  export declare function createEditorSession(options: SessionOptions): EditorSession;
186
167
  /** Default `saveFile`: an `<a download>` click, with the share sheet as a fallback on iOS Safari. */
187
168
  export declare function browserSaveFile(bytes: Uint8Array, filename: string, mimeType: string): Promise<void>;
188
- //# sourceMappingURL=session.d.ts.map
package/dist/session.js CHANGED
@@ -2,9 +2,10 @@ import { webCryptoSha256, withAssets } from './assets.js';
2
2
  import { compile } from './compile.js';
3
3
  import { SealpixelError } from './errors.js';
4
4
  import * as hist from './history.js';
5
- import { readImageSize } from './image-size.js';
6
5
  import { InlineRenderer } from './inline-renderer.js';
7
6
  import { createRegistry } from './registry.js';
7
+ const hashMismatch = () => new SealpixelError('SOURCE_MISMATCH', 'the saved edit log belongs to a different image (hash differs)');
8
+ const supersededError = () => new SealpixelError('ABORTED', 'a newer load() replaced this one');
8
9
  const EXT = {
9
10
  'image/png': 'png',
10
11
  'image/jpeg': 'jpg',
@@ -13,29 +14,29 @@ const EXT = {
13
14
  export function createEditorSession(options) {
14
15
  const registry = createRegistry(options.plugins);
15
16
  const maxClientMegapixels = options.limits?.maxClientMegapixels ?? 16;
16
- const maxClientBytes = options.limits?.maxClientBytes ?? 20e6;
17
+ const maxClientBytes = options.limits?.maxClientBytes ?? 50e6;
17
18
  const renderer = options.renderer ??
18
19
  new InlineRenderer({
19
20
  plugins: options.plugins,
20
21
  maxClientMegapixels,
21
- proxyMaxSide: options.proxy?.maxSide ?? 2048,
22
+ workingCopyMaxSide: options.workingCopy?.maxSide ?? 2048,
22
23
  });
23
24
  // A renderer handed in by the host outlives this session: hosts reuse it across sessions.
24
25
  const ownsRenderer = options.renderer === undefined;
25
- const proxyStrategy = options.proxy?.strategy ?? 'auto';
26
26
  const debounceMs = options.preview?.debounceMs ?? 80;
27
27
  const previewEnabled = options.preview?.enabled ?? true;
28
28
  const listeners = new Set();
29
+ const emptyHistory = () => hist.createHistory({
30
+ version: 1,
31
+ source: { id: '', width: 1, height: 1 },
32
+ plugins: registry.pluginVersions(),
33
+ ops: [],
34
+ });
29
35
  let state = {
30
36
  status: 'empty',
31
37
  source: null,
32
38
  resident: false,
33
- history: hist.createHistory({
34
- version: 1,
35
- source: { id: '', width: 1, height: 1 },
36
- plugins: registry.pluginVersions(),
37
- ops: [],
38
- }),
39
+ history: emptyHistory(),
39
40
  document: registry.initialDocument(),
40
41
  version: 0,
41
42
  preview: null,
@@ -43,8 +44,16 @@ export function createEditorSession(options) {
43
44
  error: null,
44
45
  };
45
46
  let previewTransform = null;
46
- /** Original bytes, kept for server renders and the server proxy strategy. */
47
- let originalBytes = null;
47
+ /**
48
+ * The image that `state.source` describes and the renderer holds, with its
49
+ * original bytes to restore the renderer after a failed load. Changes only
50
+ * together with `state.source`.
51
+ */
52
+ let committed = null;
53
+ /** Increments on every `load`. A load that sees a newer one gives up. */
54
+ let loadGeneration = 0;
55
+ /** Serializes the part of `load` that switches the renderer. */
56
+ let loadQueue = Promise.resolve();
48
57
  /** Bytes of assets added through `addAsset`, re-put after a renderer reload. */
49
58
  const localAssets = new Map();
50
59
  const resolver = options.assets
@@ -108,15 +117,21 @@ export function createEditorSession(options) {
108
117
  const log = previewTransform ? previewTransform(base) : base;
109
118
  try {
110
119
  const [image, geometry, viewGeometry] = await Promise.all([
111
- withAssets(() => renderer.render({ log, target: 'proxy', signal: controller.signal }), resolver, (id, bytes) => renderer.putAsset(id, bytes)),
120
+ withAssets(() => renderer.render({ log, target: 'workingCopy', signal: controller.signal }), resolver, (id, bytes) => renderer.putAsset(id, bytes)),
112
121
  // Geometry always describes the real output, even when a preview
113
122
  // transform shows something else on the stage.
114
- renderer.geometry({ log: base, target: 'proxy' }),
123
+ renderer.geometry({ log: base, target: 'workingCopy' }),
115
124
  // The stage needs the geometry of what it shows to keep the view steady.
116
- previewTransform ? renderer.geometry({ log, target: 'proxy' }) : null,
125
+ previewTransform ? renderer.geometry({ log, target: 'workingCopy' }) : null,
117
126
  ]);
118
- if (disposed || controller.signal.aborted || version !== state.version)
127
+ if (disposed || controller.signal.aborted || version !== state.version) {
128
+ // With previews disabled no later render clears `inflight`, so a stale
129
+ // result has to, or `whenIdle` never resolves.
130
+ if (inflight?.controller === controller)
131
+ inflight = null;
132
+ settleIdle();
119
133
  return null;
134
+ }
120
135
  const preview = { image, geometry, viewGeometry: viewGeometry ?? geometry, version };
121
136
  inflight = null;
122
137
  set({ preview, previewPending: false, error: null });
@@ -127,8 +142,10 @@ export function createEditorSession(options) {
127
142
  if (inflight?.controller === controller)
128
143
  inflight = null;
129
144
  const e = SealpixelError.from(error);
130
- if (e.name === 'ABORTED' || version !== state.version)
145
+ if (e.name === 'ABORTED' || version !== state.version) {
146
+ settleIdle();
131
147
  return null;
148
+ }
132
149
  set({ previewPending: false, error: e });
133
150
  settleIdle();
134
151
  return null;
@@ -141,7 +158,7 @@ export function createEditorSession(options) {
141
158
  const log = transform(hist.current(state.history));
142
159
  return withAssets(() => renderer.render({
143
160
  log,
144
- target: 'proxy',
161
+ target: 'workingCopy',
145
162
  ...(options?.signal ? { signal: options.signal } : {}),
146
163
  }), resolver, (id, bytes) => renderer.putAsset(id, bytes));
147
164
  }
@@ -163,45 +180,11 @@ export function createEditorSession(options) {
163
180
  return { bytes: new Uint8Array(await source.arrayBuffer()), name };
164
181
  }
165
182
  /**
166
- * Decodes client-side when the image is within the limits or the strategy
167
- * says so; otherwise asks the server for a deterministic proxy.
183
+ * Decodes the original in WebAssembly. The renderer keeps the full image
184
+ * only within `maxClientMegapixels`; the preview always uses the working copy.
168
185
  */
169
- async function loadInto(bytes, id) {
170
- const megapixels = estimateMegapixels(bytes);
171
- const useServer = proxyStrategy === 'server' ||
172
- (proxyStrategy === 'auto' &&
173
- megapixels !== null &&
174
- megapixels > maxClientMegapixels &&
175
- options.server !== undefined);
176
- if (useServer && options.server) {
177
- const res = await serverFetch({
178
- source: { kind: 'inline', base64: toBase64(bytes) },
179
- mode: 'proxy',
180
- proxyMaxSide: options.proxy?.maxSide ?? 2048,
181
- sourceId: id,
182
- });
183
- const descriptor = JSON.parse(res.headers.get('x-sealpixel-descriptor') ?? '{}');
184
- const proxyPng = new Uint8Array(await res.arrayBuffer());
185
- return renderer.loadProxyEncoded(proxyPng, { ...descriptor, id });
186
- }
187
- return renderer.load(bytes, id);
188
- }
189
- async function serverFetch(body, endpoint = options.server?.endpoint) {
190
- if (!endpoint)
191
- throw new SealpixelError('NOT_CONFIGURED', 'no server endpoint configured');
192
- const doFetch = options.server?.fetch ?? fetch;
193
- const res = await doFetch(endpoint, {
194
- method: 'POST',
195
- headers: { 'content-type': 'application/json', ...(options.server?.headers ?? {}) },
196
- body: JSON.stringify(body),
197
- });
198
- if (!res.ok) {
199
- const detail = (await res
200
- .json()
201
- .catch(() => ({ error: 'SERVER_ERROR', message: `HTTP ${res.status}` })));
202
- throw new SealpixelError(detail.error ?? 'SERVER_ERROR', String(detail.message ?? `HTTP ${res.status}`), detail.details);
203
- }
204
- return res;
186
+ function loadInto(bytes, id) {
187
+ return renderer.load(bytes, id, { maxClientMegapixels });
205
188
  }
206
189
  function resolveSavedState(saved) {
207
190
  const wrapped = saved;
@@ -210,9 +193,59 @@ export function createEditorSession(options) {
210
193
  const index = typeof wrapped?.index === 'number' ? wrapped.index : undefined;
211
194
  return { log, index };
212
195
  }
196
+ /** Runs `task` after every renderer switch that started before it. */
197
+ function exclusive(task) {
198
+ const run = loadQueue.then(task);
199
+ loadQueue = run.catch(() => { });
200
+ return run;
201
+ }
202
+ /**
203
+ * Puts the committed image back into the renderer after a load switched it
204
+ * and then failed. If that fails too, the session drops to `empty`: a state
205
+ * that names an image the renderer does not hold renders wrong pixels.
206
+ */
207
+ async function restoreCommitted() {
208
+ // Nothing committed: the state is `empty` and nothing renders.
209
+ if (!committed)
210
+ return;
211
+ try {
212
+ await loadInto(committed.bytes, committed.id);
213
+ }
214
+ catch {
215
+ committed = null;
216
+ set({
217
+ status: 'empty',
218
+ source: null,
219
+ resident: false,
220
+ history: emptyHistory(),
221
+ document: registry.initialDocument(),
222
+ version: state.version + 1,
223
+ preview: null,
224
+ });
225
+ }
226
+ }
227
+ /** History for a saved state resumed on a freshly loaded image. Throws `SOURCE_MISMATCH`. */
228
+ function savedHistory(saved, descriptor, index) {
229
+ const { log } = saved;
230
+ if (log.source.hash !== undefined && log.source.hash !== descriptor.hash) {
231
+ throw hashMismatch();
232
+ }
233
+ if (log.source.width !== descriptor.width || log.source.height !== descriptor.height) {
234
+ throw new SealpixelError('SOURCE_MISMATCH', `the saved edit log expects ${log.source.width}x${log.source.height}, image is ${descriptor.width}x${descriptor.height}`);
235
+ }
236
+ return hist.createHistory({
237
+ ...log,
238
+ source: {
239
+ ...log.source,
240
+ hash: descriptor.hash ?? log.source.hash,
241
+ },
242
+ }, index ?? saved.index ?? log.ops.length);
243
+ }
213
244
  const session = {
214
245
  registry,
215
246
  async load(source, loadOptions = {}) {
247
+ const generation = ++loadGeneration;
248
+ const superseded = () => generation !== loadGeneration;
216
249
  if (timer)
217
250
  clearTimeout(timer);
218
251
  timer = null;
@@ -221,54 +254,68 @@ export function createEditorSession(options) {
221
254
  set({ status: 'loading', error: null, preview: null, previewPending: false });
222
255
  try {
223
256
  const { bytes, name } = await readBytes(source);
257
+ if (superseded())
258
+ throw supersededError();
224
259
  if (bytes.byteLength > maxClientBytes) {
225
260
  throw new SealpixelError('TOO_LARGE', `${bytes.byteLength} bytes exceed the client limit of ${maxClientBytes}`);
226
261
  }
227
262
  const id = loadOptions.id ?? (name ? name.replace(/\.[^.]+$/, '') : 'image');
228
- originalBytes = bytes;
229
- const loaded = await loadInto(bytes, id);
230
- const descriptor = loaded.descriptor;
231
- let history;
232
- if (loadOptions.editLog !== undefined) {
233
- const { log, index } = resolveSavedState(loadOptions.editLog);
234
- if (log.source.hash !== undefined && log.source.hash !== descriptor.hash) {
235
- throw new SealpixelError('SOURCE_MISMATCH', 'the saved edit log belongs to a different image (hash differs)');
263
+ // Validate what can be validated before the renderer switches.
264
+ const saved = loadOptions.editLog === undefined ? null : resolveSavedState(loadOptions.editLog);
265
+ if (saved?.log.source.hash !== undefined) {
266
+ if (saved.log.source.hash !== (await webCryptoSha256(bytes)))
267
+ throw hashMismatch();
268
+ if (superseded())
269
+ throw supersededError();
270
+ }
271
+ return await exclusive(async () => {
272
+ if (superseded())
273
+ throw supersededError();
274
+ const loaded = await loadInto(bytes, id);
275
+ // The renderer holds the new image now. Until the state commits to
276
+ // it, any failure puts the renderer back on the committed image.
277
+ try {
278
+ if (superseded())
279
+ throw supersededError();
280
+ const descriptor = loaded.descriptor;
281
+ const history = saved
282
+ ? savedHistory(saved, descriptor, loadOptions.index)
283
+ : hist.createHistory({
284
+ version: 1,
285
+ source: descriptor,
286
+ plugins: registry.pluginVersions(),
287
+ ops: [],
288
+ });
289
+ const document = compile(hist.current(history), registry);
290
+ committed = { bytes, id };
291
+ set({
292
+ status: 'ready',
293
+ source: descriptor,
294
+ resident: loaded.resident,
295
+ history,
296
+ document,
297
+ version: state.version + 1,
298
+ preview: null,
299
+ error: null,
300
+ });
301
+ schedulePreview();
302
+ return descriptor;
236
303
  }
237
- if (log.source.width !== descriptor.width || log.source.height !== descriptor.height) {
238
- throw new SealpixelError('SOURCE_MISMATCH', `the saved edit log expects ${log.source.width}x${log.source.height}, image is ${descriptor.width}x${descriptor.height}`);
304
+ catch (error) {
305
+ await restoreCommitted();
306
+ throw error;
239
307
  }
240
- history = hist.createHistory({
241
- ...log,
242
- source: {
243
- ...log.source,
244
- hash: descriptor.hash ?? log.source.hash,
245
- },
246
- }, loadOptions.index ?? index ?? log.ops.length);
247
- }
248
- else {
249
- history = hist.createHistory({
250
- version: 1,
251
- source: descriptor,
252
- plugins: registry.pluginVersions(),
253
- ops: [],
254
- });
255
- }
256
- set({
257
- status: 'ready',
258
- source: descriptor,
259
- resident: loaded.resident,
260
- history,
261
- document: compile(hist.current(history), registry),
262
- version: state.version + 1,
263
- preview: null,
264
- error: null,
265
308
  });
266
- schedulePreview();
267
- return descriptor;
268
309
  }
269
310
  catch (error) {
270
311
  const e = SealpixelError.from(error);
271
- set({ status: state.source ? 'ready' : 'empty', error: e });
312
+ // Only the newest load reports into the state. It waits for the
313
+ // renderer switches ahead of it, so the state never says `ready` while
314
+ // an older load still holds the renderer on another image.
315
+ await exclusive(async () => {
316
+ if (!superseded())
317
+ set({ status: state.source ? 'ready' : 'empty', error: e });
318
+ });
272
319
  throw e;
273
320
  }
274
321
  },
@@ -357,7 +404,7 @@ export function createEditorSession(options) {
357
404
  async export(exportOptions) {
358
405
  ensureReady();
359
406
  if (!state.resident) {
360
- throw new SealpixelError('NOT_RESIDENT', 'full-resolution pixels are not client-side; use requestServerRender');
407
+ throw new SealpixelError('NOT_RESIDENT', `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()`);
361
408
  }
362
409
  const log = state.history.log;
363
410
  const upTo = exportOptions.upTo ?? state.history.index;
@@ -377,8 +424,6 @@ export function createEditorSession(options) {
377
424
  async download(downloadOptions = {}) {
378
425
  ensureReady();
379
426
  const output = downloadOptions.output ?? { format: 'image/png' };
380
- const via = downloadOptions.via ?? 'auto';
381
- const useServer = via === 'server' || (via === 'auto' && !state.resident);
382
427
  const exportOptions = {
383
428
  output,
384
429
  ...(downloadOptions.embedEditLog === undefined
@@ -387,67 +432,12 @@ export function createEditorSession(options) {
387
432
  ...(downloadOptions.upTo === undefined ? {} : { upTo: downloadOptions.upTo }),
388
433
  };
389
434
  const save = options.saveFile ?? browserSaveFile;
390
- if (useServer) {
391
- const result = await session.requestServerRender({
392
- ...exportOptions,
393
- destination: 'response',
394
- });
395
- const filename = downloadOptions.filename ??
396
- `${state.source?.id ?? 'image'}-${result.hash.slice(0, 8)}.${EXT[output.format]}`;
397
- await save(result.bytes, filename, result.mimeType);
398
- return { filename, result };
399
- }
400
435
  const result = await session.export(exportOptions);
401
436
  const filename = downloadOptions.filename ??
402
437
  `${state.source?.id ?? 'image'}-${result.hash.slice(0, 8)}.${EXT[output.format]}`;
403
438
  await save(result.bytes, filename, result.mimeType);
404
439
  return { filename, result };
405
440
  },
406
- async requestServerRender(renderOptions) {
407
- ensureReady();
408
- const endpoint = renderOptions.endpoint ?? options.server?.endpoint;
409
- if (!endpoint)
410
- throw new SealpixelError('NOT_CONFIGURED', 'no server endpoint configured');
411
- const source = renderOptions.source ??
412
- (originalBytes ? { kind: 'inline', base64: toBase64(originalBytes) } : null);
413
- if (!source)
414
- throw new SealpixelError('NO_SOURCE', 'original bytes are not available; pass a source reference');
415
- const destination = renderOptions.destination ?? 'response';
416
- const body = {
417
- source,
418
- editLog: state.history.log,
419
- output: renderOptions.output,
420
- upTo: renderOptions.upTo ?? state.history.index,
421
- ...(renderOptions.embedEditLog ? { embedEditLog: true } : {}),
422
- destination: { kind: destination },
423
- };
424
- const res = await serverFetch(body, endpoint);
425
- if (destination === 's3') {
426
- const job = (await res.json());
427
- return {
428
- url: job.url,
429
- objectKey: job.objectKey,
430
- bucket: job.bucket,
431
- hash: job.hash,
432
- width: job.width,
433
- height: job.height,
434
- mimeType: job.mimeType,
435
- cached: job.cached,
436
- jobKey: job.key,
437
- };
438
- }
439
- const bytes = new Uint8Array(await res.arrayBuffer());
440
- return {
441
- bytes,
442
- hash: res.headers.get('x-sealpixel-hash') ?? '',
443
- width: state.preview?.geometry.logicalOut.width ?? 0,
444
- height: state.preview?.geometry.logicalOut.height ?? 0,
445
- mimeType: res.headers.get('content-type') ??
446
- renderOptions.output.format,
447
- cached: res.headers.get('x-sealpixel-cached') === 'true',
448
- jobKey: res.headers.get('x-sealpixel-job') ?? '',
449
- };
450
- },
451
441
  dispose() {
452
442
  disposed = true;
453
443
  if (timer)
@@ -493,21 +483,4 @@ export async function browserSaveFile(bytes, filename, mimeType) {
493
483
  setTimeout(() => URL.revokeObjectURL(url), 10_000);
494
484
  }
495
485
  }
496
- function estimateMegapixels(bytes) {
497
- try {
498
- const { width, height } = readImageSize(bytes);
499
- return (width * height) / 1e6;
500
- }
501
- catch {
502
- return null;
503
- }
504
- }
505
- function toBase64(bytes) {
506
- if (typeof Buffer !== 'undefined')
507
- return Buffer.from(bytes).toString('base64');
508
- let bin = '';
509
- for (let i = 0; i < bytes.length; i += 0x8000)
510
- bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
511
- return btoa(bin);
512
- }
513
486
  //# sourceMappingURL=session.js.map