@vielzeug/stage 0.0.0-stage → 26.11.24

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 (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +53 -2
  3. package/dist/_dev.cjs +2 -0
  4. package/dist/_dev.cjs.map +1 -0
  5. package/dist/_dev.d.ts +2 -0
  6. package/dist/_dev.d.ts.map +1 -0
  7. package/dist/_dev.js +5 -0
  8. package/dist/_dev.js.map +1 -0
  9. package/dist/_validate.cjs +2 -0
  10. package/dist/_validate.cjs.map +1 -0
  11. package/dist/_validate.d.ts +3 -0
  12. package/dist/_validate.d.ts.map +1 -0
  13. package/dist/_validate.js +20 -0
  14. package/dist/_validate.js.map +1 -0
  15. package/dist/errors.cjs +2 -0
  16. package/dist/errors.cjs.map +1 -0
  17. package/dist/errors.d.ts +12 -0
  18. package/dist/errors.d.ts.map +1 -0
  19. package/dist/errors.js +9 -0
  20. package/dist/errors.js.map +1 -0
  21. package/dist/index.cjs +1 -0
  22. package/dist/index.d.ts +3 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +3 -0
  25. package/dist/stage.cjs +2 -0
  26. package/dist/stage.cjs.map +1 -0
  27. package/dist/stage.d.ts +101 -0
  28. package/dist/stage.d.ts.map +1 -0
  29. package/dist/stage.iife.js +2 -0
  30. package/dist/stage.iife.js.map +1 -0
  31. package/dist/stage.js +256 -0
  32. package/dist/stage.js.map +1 -0
  33. package/dist/worker/index.cjs +1 -0
  34. package/dist/worker/index.d.ts +3 -0
  35. package/dist/worker/index.d.ts.map +1 -0
  36. package/dist/worker/index.js +3 -0
  37. package/dist/worker/main.cjs +2 -0
  38. package/dist/worker/main.cjs.map +1 -0
  39. package/dist/worker/main.d.ts +45 -0
  40. package/dist/worker/main.d.ts.map +1 -0
  41. package/dist/worker/main.js +114 -0
  42. package/dist/worker/main.js.map +1 -0
  43. package/dist/worker/protocol.d.ts +65 -0
  44. package/dist/worker/protocol.d.ts.map +1 -0
  45. package/dist/worker/serve.cjs +2 -0
  46. package/dist/worker/serve.cjs.map +1 -0
  47. package/dist/worker/serve.d.ts +38 -0
  48. package/dist/worker/serve.d.ts.map +1 -0
  49. package/dist/worker/serve.js +99 -0
  50. package/dist/worker/serve.js.map +1 -0
  51. package/package.json +63 -4
package/dist/stage.js ADDED
@@ -0,0 +1,256 @@
1
+ import { apply as e, invert as t, multiply as n, rectFromPoints as r, scale as i, scaleOf as a, translate as o } from "@vielzeug/atlas";
2
+ // src/errors.ts
3
+ var StageError = class extends Error {
4
+ constructor(e, t) {
5
+ super(e, t), this.name = new.target.name, Object.setPrototypeOf(this, new.target.prototype);
6
+ }
7
+ }, StageConfigError = class extends StageError {}, StageUnsupportedError = class extends StageError {}, StageDisposedError = class extends StageError {};
8
+ // src/_validate.ts
9
+ function requireSize(e, t) {
10
+ if (!Number.isFinite(e.width) || e.width <= 0 || !Number.isFinite(e.height) || e.height <= 0) throw new StageConfigError(`${t} size must be positive finite numbers, got ${e.width}x${e.height}.`);
11
+ }
12
+ function requireDpr(e, t) {
13
+ if (!Number.isFinite(e) || e <= 0) throw new StageConfigError(`${t} dpr must be a positive finite number, got ${e}.`);
14
+ }
15
+ function requireRect(e, t) {
16
+ if (!Number.isFinite(e.x) || !Number.isFinite(e.y) || !Number.isFinite(e.width) || e.width <= 0 || !Number.isFinite(e.height) || e.height <= 0) throw new StageConfigError(`${t} region must have finite coordinates and positive finite size, got ${e.width}x${e.height} at ${e.x},${e.y}.`);
17
+ }
18
+ function requireScale(e, t) {
19
+ if (!Number.isFinite(e) || e <= 0) throw new StageConfigError(`${t} scale must be a positive finite number, got ${e}.`);
20
+ }
21
+ function requireFiniteMatrix(e) {
22
+ for (let t of e) if (!Number.isFinite(t)) throw new StageConfigError(`Stage matrix must contain only finite numbers, got ${t}.`);
23
+ }
24
+ // src/stage.ts
25
+ var s = {
26
+ cancelFrame: (e) => {
27
+ typeof cancelAnimationFrame == "function" ? cancelAnimationFrame(e) : clearTimeout(e);
28
+ },
29
+ now: () => performance.now(),
30
+ requestFrame: (e) => typeof requestAnimationFrame == "function" ? requestAnimationFrame(e) : setTimeout(() => e(performance.now()), 16)
31
+ };
32
+ function defaultCreateSurface(e, t) {
33
+ if (typeof OffscreenCanvas < "u") return new OffscreenCanvas(e, t);
34
+ if (typeof document < "u") {
35
+ let n = document.createElement("canvas");
36
+ return n.width = e, n.height = t, n;
37
+ }
38
+ throw new StageUnsupportedError("No canvas surface factory is available in this environment.");
39
+ }
40
+ function createStage(c, l) {
41
+ let { width: u, height: d } = l;
42
+ requireSize({
43
+ height: d,
44
+ width: u
45
+ }, "Stage"), requireDpr(l.dpr ?? 1, "Stage");
46
+ let f = l.scheduler ?? s, p = l.createSurface ?? defaultCreateSurface, m = l.background ?? null, h = new AbortController(), g = !1, _ = u, v = d, y = l.dpr ?? 1, b = [
47
+ 1,
48
+ 0,
49
+ 0,
50
+ 1,
51
+ 0,
52
+ 0
53
+ ], x = null, S = !1, C = [];
54
+ for (let e of l.layers) {
55
+ if (C.some((t) => t.id === e.id)) throw new StageConfigError(`Stage layer id "${e.id}" is already registered.`);
56
+ C.push({
57
+ ctx: null,
58
+ dirty: !0,
59
+ id: e.id,
60
+ paint: e.paint,
61
+ surface: null
62
+ });
63
+ }
64
+ let disposeSurface = (e) => {
65
+ e.surface && (e.surface.width = 0, e.surface.height = 0), e.surface = null, e.ctx = null;
66
+ }, ensureSurface = (e) => {
67
+ let t = Math.max(1, Math.round(_ * y)), n = Math.max(1, Math.round(v * y));
68
+ if (!e.surface || e.surface.width !== t || e.surface.height !== n) {
69
+ disposeSurface(e), e.surface = p(t, n);
70
+ let r = e.surface.getContext("2d", { alpha: !0 });
71
+ if (r == null) throw new StageUnsupportedError(`Layer surface for "${e.id}" has no 2D context.`);
72
+ e.ctx = r, e.dirty = !0;
73
+ }
74
+ return e.ctx;
75
+ }, visibleRect = () => {
76
+ let n = t(b);
77
+ if (!n) return {
78
+ height: v,
79
+ width: _,
80
+ x: 0,
81
+ y: 0
82
+ };
83
+ let i = [
84
+ e(n, {
85
+ x: 0,
86
+ y: 0
87
+ }),
88
+ e(n, {
89
+ x: _,
90
+ y: 0
91
+ }),
92
+ e(n, {
93
+ x: 0,
94
+ y: v
95
+ }),
96
+ e(n, {
97
+ x: _,
98
+ y: v
99
+ })
100
+ ];
101
+ return r(i);
102
+ }, applyWorldTransform = (e) => {
103
+ let [t, n, r, i, a, o] = b;
104
+ e.setTransform(y * t, y * n, y * r, y * i, y * a, y * o);
105
+ }, surfaceToBlob = async (e, t, n) => {
106
+ if (typeof OffscreenCanvas < "u" && e instanceof OffscreenCanvas) {
107
+ let r = await e.convertToBlob({
108
+ quality: n,
109
+ type: t
110
+ });
111
+ if (!r) throw new StageUnsupportedError("Canvas blob export returned no data.");
112
+ return r;
113
+ }
114
+ let r = e;
115
+ if (typeof r.toBlob != "function") throw new StageUnsupportedError("This canvas does not support blob export.");
116
+ let i = await new Promise((e) => {
117
+ r.toBlob(e, t, n);
118
+ });
119
+ if (!i) throw new StageUnsupportedError("Canvas blob export returned no data.");
120
+ return i;
121
+ }, exportRegion = async (e, t) => {
122
+ let r = e.region ?? visibleRect();
123
+ requireRect(r, "Export");
124
+ let s = e.scale ?? y * a(b);
125
+ requireScale(s, "Export");
126
+ let c = Math.max(1, Math.round(r.width * s)), l = Math.max(1, Math.round(r.height * s)), u = n(i(s), o(-r.x, -r.y)), d = {
127
+ dpr: 1,
128
+ matrix: u,
129
+ time: f.now(),
130
+ visibleRect: r
131
+ }, h = [];
132
+ try {
133
+ let n = p(c, l);
134
+ h.push(n);
135
+ let r = n.getContext("2d", { alpha: !0 });
136
+ if (r == null) throw new StageUnsupportedError("Export surface has no 2D context.");
137
+ r.setTransform(1, 0, 0, 1, 0, 0), r.clearRect(0, 0, c, l), m != null && (r.fillStyle = m, r.fillRect(0, 0, c, l));
138
+ for (let e of C) {
139
+ let t = p(c, l);
140
+ h.push(t);
141
+ let n = t.getContext("2d", { alpha: !0 });
142
+ if (n == null) throw new StageUnsupportedError(`Layer surface for "${e.id}" has no 2D context.`);
143
+ n.setTransform(1, 0, 0, 1, 0, 0), n.clearRect(0, 0, c, l);
144
+ let [i, a, o, s, f, m] = u;
145
+ n.setTransform(i, a, o, s, f, m), e.paint(n, d), r.drawImage(t, 0, 0, c, l);
146
+ }
147
+ return await surfaceToBlob(n, t, e.quality);
148
+ } finally {
149
+ for (let e of h) e.width = 0, e.height = 0;
150
+ }
151
+ }, renderFrame = (e) => {
152
+ if (S = !1, x = null, g) return {
153
+ repainted: [],
154
+ time: e
155
+ };
156
+ let t = visibleRect(), n = {
157
+ dpr: y,
158
+ matrix: b,
159
+ time: e,
160
+ visibleRect: t
161
+ }, r = [];
162
+ for (let e of C) if (e.dirty) {
163
+ let t = ensureSurface(e);
164
+ t.setTransform(1, 0, 0, 1, 0, 0), t.clearRect(0, 0, e.surface?.width ?? 0, e.surface?.height ?? 0), applyWorldTransform(t), e.paint(t, n), e.dirty = !1, r.push(e.id);
165
+ }
166
+ let i = c.getContext("2d");
167
+ if (i) {
168
+ let e = Math.max(1, Math.round(_ * y)), t = Math.max(1, Math.round(v * y)), n = Math.max(1, Math.round(c.width)), r = Math.max(1, Math.round(c.height));
169
+ i.setTransform(1, 0, 0, 1, 0, 0), i.clearRect(0, 0, n, r), m != null && (i.fillStyle = m, i.fillRect(0, 0, n, r));
170
+ for (let n of C) n.surface && i.drawImage(n.surface, 0, 0, e, t);
171
+ }
172
+ return {
173
+ repainted: r,
174
+ time: e
175
+ };
176
+ }, schedule = () => {
177
+ g || S || (S = !0, x = f.requestFrame((e) => {
178
+ S && renderFrame(e);
179
+ }));
180
+ }, invalidateAll = () => {
181
+ for (let e of C) e.dirty = !0;
182
+ }, cancelFrame = () => {
183
+ x != null && (f.cancelFrame(x), x = null), S = !1;
184
+ }, dispose = () => {
185
+ if (!g) {
186
+ g = !0, cancelFrame();
187
+ for (let e of C) disposeSurface(e);
188
+ C.length = 0, h.abort();
189
+ }
190
+ };
191
+ c.width = Math.max(1, Math.round(_ * y)), c.height = Math.max(1, Math.round(v * y));
192
+ let w = {
193
+ get canvas() {
194
+ return c;
195
+ },
196
+ get disposalSignal() {
197
+ return h.signal;
198
+ },
199
+ get disposed() {
200
+ return g;
201
+ },
202
+ [Symbol.dispose]: dispose,
203
+ dispose,
204
+ get dpr() {
205
+ return y;
206
+ },
207
+ get height() {
208
+ return v;
209
+ },
210
+ invalidate(e) {
211
+ if (!g) {
212
+ if (e == null) invalidateAll();
213
+ else {
214
+ let t = C.find((t) => t.id === e);
215
+ if (!t) throw new StageConfigError(`Unknown stage layer "${e}".`);
216
+ t.dirty = !0;
217
+ }
218
+ schedule();
219
+ }
220
+ },
221
+ get matrix() {
222
+ return b;
223
+ },
224
+ render(e) {
225
+ return g ? {
226
+ repainted: [],
227
+ time: e ?? f.now()
228
+ } : (cancelFrame(), renderFrame(e ?? f.now()));
229
+ },
230
+ resize(e, t) {
231
+ if (g) return;
232
+ requireSize(e, "Stage");
233
+ let n = t ?? y;
234
+ requireDpr(n, "Stage"), _ = e.width, v = e.height, y = n, c.width = Math.max(1, Math.round(_ * y)), c.height = Math.max(1, Math.round(v * y)), invalidateAll(), schedule();
235
+ },
236
+ setTransform(e) {
237
+ g || (requireFiniteMatrix(e), b = e, invalidateAll(), schedule());
238
+ },
239
+ async toBlob(e) {
240
+ if (g) throw new StageDisposedError("Cannot export a disposed stage.");
241
+ S && w.render();
242
+ let t = e?.type ?? "image/png";
243
+ return e?.region != null || e?.scale != null ? await exportRegion(e, t) : await surfaceToBlob(c, t, e?.quality);
244
+ },
245
+ get visibleRect() {
246
+ return visibleRect();
247
+ },
248
+ get width() {
249
+ return _;
250
+ }
251
+ };
252
+ return w;
253
+ }
254
+ export { StageConfigError, StageDisposedError, StageError, StageUnsupportedError, createStage };
255
+
256
+ //# sourceMappingURL=stage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stage.js","names":["scaleMatrix","message","opts","size","context","dpr","rect","scale","value","matrix","DEFAULT_SCHEDULER","handle","callback","width","height","el","initialWidth","initialHeight","options","scheduler","createSurface","background","controller","disposed","frameHandle","pending","layers","layer","pw","ph","ctx","inv","invert","corners","apply","rectFromPoints","a","b","c","d","e","f","surface","blob","htmlCanvas","resolve","type","quality","region","exportScale","scaleOf","exportMatrix","multiply","translate","frame","scratch","output","outCtx","repainted","screen","canvas","cw","ch","time","stage","layerId","l","resolvedDpr","nextDpr","next","blobOptions"],"sources":["../src/errors.ts","../src/_validate.ts","../src/stage.ts"],"sourcesContent":["export class StageError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class StageConfigError extends StageError {}\n\n/** A required browser capability (e.g. canvas blob export) is missing. */\nexport class StageUnsupportedError extends StageError {}\n\n/** The stage (or its worker) was disposed before a pending request settled. */\nexport class StageDisposedError extends StageError {}\n","/** Shared input validation for the main-thread and worker stage halves. */\n\nimport type { Matrix, Rect, Size } from '@vielzeug/atlas';\nimport { StageConfigError } from './errors.js';\n\n/** @internal */\nexport function requireSize(size: Size, context: string): void {\n if (!Number.isFinite(size.width) || size.width <= 0 || !Number.isFinite(size.height) || size.height <= 0) {\n throw new StageConfigError(`${context} size must be positive finite numbers, got ${size.width}x${size.height}.`);\n }\n}\n\n/** @internal */\nexport function requireDpr(dpr: number, context: string): void {\n if (!Number.isFinite(dpr) || dpr <= 0) {\n throw new StageConfigError(`${context} dpr must be a positive finite number, got ${dpr}.`);\n }\n}\n\n/** @internal */\nexport function requireRect(rect: Rect, context: string): void {\n if (\n !Number.isFinite(rect.x) ||\n !Number.isFinite(rect.y) ||\n !Number.isFinite(rect.width) ||\n rect.width <= 0 ||\n !Number.isFinite(rect.height) ||\n rect.height <= 0\n ) {\n throw new StageConfigError(\n `${context} region must have finite coordinates and positive finite size, got ${rect.width}x${rect.height} at ${rect.x},${rect.y}.`,\n );\n }\n}\n\n/** @internal */\nexport function requireScale(scale: number, context: string): void {\n if (!Number.isFinite(scale) || scale <= 0) {\n throw new StageConfigError(`${context} scale must be a positive finite number, got ${scale}.`);\n }\n}\n\n/** @internal */\nexport function requireFiniteMatrix(matrix: Matrix): void {\n for (const value of matrix) {\n if (!Number.isFinite(value)) {\n throw new StageConfigError(`Stage matrix must contain only finite numbers, got ${value}.`);\n }\n }\n}\n","import {\n apply,\n type FrameScheduler,\n invert,\n type Matrix,\n multiply,\n type Point,\n type Rect,\n rectFromPoints,\n type Size,\n scale as scaleMatrix,\n scaleOf,\n translate,\n} from '@vielzeug/atlas';\nimport { requireDpr, requireFiniteMatrix, requireRect, requireScale, requireSize } from './_validate.js';\nimport { StageConfigError, StageDisposedError, StageUnsupportedError } from './errors.js';\n\n/** A backing surface a layer paints into. `OffscreenCanvas` on workers. */\nexport type StageSurface = {\n width: number;\n height: number;\n getContext: (type: '2d', attributes?: CanvasRenderingContext2DSettings) => unknown;\n};\n\n/** Factory for layer backing surfaces; injectable for tests and workers. */\nexport type CreateSurface = (width: number, height: number) => StageSurface;\n\nexport type PaintContext = Readonly<{\n /** World→screen matrix (DPR already applied to the context transform). */\n matrix: Matrix;\n /** Visible world-space rect for culling. */\n visibleRect: Rect;\n /** Device pixel ratio in effect. */\n dpr: number;\n /** Frame timestamp from the scheduler. */\n time: number;\n}>;\n\nexport type StageLayerOptions = Readonly<{\n id: string;\n paint: (ctx: CanvasRenderingContext2D, frame: PaintContext) => void;\n}>;\n\nexport type StageOptions = Readonly<{\n dpr?: number;\n /** Layers are fixed at creation, bottom-first; hide one by returning early from its paint. */\n layers: readonly StageLayerOptions[];\n /** Reuses the atlas camera scheduler contract; defaults to `requestAnimationFrame`. */\n scheduler?: FrameScheduler;\n createSurface?: CreateSurface;\n /** Background color cleared under the layers; defaults to transparent. */\n background?: string | null;\n}>;\n\n/** Options for `toBlob()`: blob encoding plus an optional world-space crop and pixel density. */\nexport type StageBlobOptions = Readonly<{\n /** Blob MIME type; defaults to `image/png`. */\n type?: string;\n /** Encoder quality for lossy types. */\n quality?: number;\n /**\n * World-space rect to export; defaults to the current visible rect. The\n * export re-paints every layer against the region transform, so cost is a\n * full repaint, not a blit of the cached composite.\n */\n region?: Rect;\n /**\n * Export pixels per world unit. Defaults to the current device pixels per\n * world unit (`dpr × matrix scale`), which matches the on-screen density.\n */\n scale?: number;\n}>;\n\nexport type StageFrameInfo = Readonly<{\n /** Layer ids that were repainted for this frame. */\n repainted: readonly string[];\n time: number;\n}>;\n\n/**\n * The control surface both stage modes share: a main-thread `Stage` and a\n * `WorkerStage` client are interchangeable wherever only control is needed.\n */\nexport type StageController = Readonly<{\n /** Resize the CSS size and DPR; reallocates backing surfaces and invalidates all. */\n resize: (size: Size, dpr?: number) => void;\n /** Set the world→screen matrix; invalidates all layers. */\n setTransform: (matrix: Matrix) => void;\n /** Mark one layer dirty (omit to mark all); schedules a frame. */\n invalidate: (layerId?: string) => void;\n /**\n * Export the current frame as a blob. With `region`/`scale`, layers are\n * re-painted into scratch surfaces at the requested crop and density;\n * the live viewport is untouched.\n */\n toBlob: (options?: StageBlobOptions) => Promise<Blob>;\n dispose: () => void;\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n [Symbol.dispose]: () => void;\n}>;\n\nexport type Stage = StageController &\n Readonly<{\n readonly canvas: HTMLCanvasElement | OffscreenCanvas;\n readonly width: number;\n readonly height: number;\n readonly dpr: number;\n /** Current world→screen matrix (CSS pixels, without DPR). */\n readonly matrix: Matrix;\n readonly visibleRect: Rect;\n /** Run any pending repaint/composite synchronously; defaults `time` to the scheduler clock. */\n render: (time?: number) => StageFrameInfo;\n }>;\n\nconst DEFAULT_SCHEDULER: FrameScheduler = {\n // Workers may lack requestAnimationFrame; fall back to a timer there.\n cancelFrame: (handle) => {\n if (typeof cancelAnimationFrame === 'function') cancelAnimationFrame(handle);\n else clearTimeout(handle);\n },\n now: () => performance.now(),\n requestFrame: (callback) =>\n typeof requestAnimationFrame === 'function'\n ? requestAnimationFrame(callback)\n : (setTimeout(() => callback(performance.now()), 16) as unknown as number),\n};\n\nfunction defaultCreateSurface(width: number, height: number): StageSurface {\n if (typeof OffscreenCanvas !== 'undefined') {\n return new OffscreenCanvas(width, height) as unknown as StageSurface;\n }\n if (typeof document !== 'undefined') {\n const el = document.createElement('canvas');\n el.width = width;\n el.height = height;\n return el;\n }\n throw new StageUnsupportedError('No canvas surface factory is available in this environment.');\n}\n\ntype LayerRecord = {\n id: string;\n paint: (ctx: CanvasRenderingContext2D, frame: PaintContext) => void;\n surface: StageSurface | null;\n ctx: CanvasRenderingContext2D | null;\n dirty: boolean;\n};\n\n/**\n * Creates a retained-mode 2D stage: ordered layers, each with a cached\n * backing surface, repainted only when dirty and composited to the canvas\n * every scheduled frame. Paint callbacks draw in world units; the stage\n * applies the world→screen matrix and DPR to the context transform. The\n * caller owns the canvas CSS size; the stage only sizes the backing store.\n */\nexport function createStage(\n canvas: HTMLCanvasElement | OffscreenCanvas,\n options: StageOptions & Readonly<{ width: number; height: number }>,\n): Stage {\n const { width: initialWidth, height: initialHeight } = options;\n requireSize({ height: initialHeight, width: initialWidth }, 'Stage');\n requireDpr(options.dpr ?? 1, 'Stage');\n const scheduler = options.scheduler ?? DEFAULT_SCHEDULER;\n const createSurface = options.createSurface ?? defaultCreateSurface;\n const background = options.background ?? null;\n\n const controller = new AbortController();\n let disposed = false;\n let width = initialWidth;\n let height = initialHeight;\n let dpr = options.dpr ?? 1;\n let matrix: Matrix = [1, 0, 0, 1, 0, 0];\n let frameHandle: number | null = null;\n let pending = false;\n\n const layers: LayerRecord[] = [];\n for (const opts of options.layers) {\n if (layers.some((layer) => layer.id === opts.id)) {\n throw new StageConfigError(`Stage layer id \"${opts.id}\" is already registered.`);\n }\n layers.push({ ctx: null, dirty: true, id: opts.id, paint: opts.paint, surface: null });\n }\n\n const disposeSurface = (layer: LayerRecord): void => {\n if (layer.surface) {\n // Release backing-store memory for both canvas flavours.\n layer.surface.width = 0;\n layer.surface.height = 0;\n }\n layer.surface = null;\n layer.ctx = null;\n };\n\n const ensureSurface = (layer: LayerRecord): CanvasRenderingContext2D => {\n const pw = Math.max(1, Math.round(width * dpr));\n const ph = Math.max(1, Math.round(height * dpr));\n if (!layer.surface || layer.surface.width !== pw || layer.surface.height !== ph) {\n disposeSurface(layer);\n layer.surface = createSurface(pw, ph);\n const ctx = layer.surface.getContext('2d', { alpha: true });\n if (ctx == null) {\n throw new StageUnsupportedError(`Layer surface for \"${layer.id}\" has no 2D context.`);\n }\n layer.ctx = ctx as CanvasRenderingContext2D;\n layer.dirty = true;\n }\n return layer.ctx as CanvasRenderingContext2D;\n };\n\n const visibleRect = (): Rect => {\n const inv = invert(matrix);\n if (!inv) return { height, width, x: 0, y: 0 };\n const corners: [Point, Point, Point, Point] = [\n apply(inv, { x: 0, y: 0 }),\n apply(inv, { x: width, y: 0 }),\n apply(inv, { x: 0, y: height }),\n apply(inv, { x: width, y: height }),\n ];\n return rectFromPoints(corners);\n };\n\n const applyWorldTransform = (ctx: CanvasRenderingContext2D): void => {\n const [a, b, c, d, e, f] = matrix;\n ctx.setTransform(dpr * a, dpr * b, dpr * c, dpr * d, dpr * e, dpr * f);\n };\n\n /** Rasterize a surface (live canvas or scratch) into a blob; shared by both export paths. */\n const surfaceToBlob = async (surface: StageSurface, type: string, quality?: number): Promise<Blob> => {\n if (typeof OffscreenCanvas !== 'undefined' && surface instanceof OffscreenCanvas) {\n // OffscreenCanvas (worker-rendered stages): promise-based export.\n const blob = await surface.convertToBlob({ quality, type });\n if (!blob) throw new StageUnsupportedError('Canvas blob export returned no data.');\n return blob;\n }\n const htmlCanvas = surface as unknown as HTMLCanvasElement;\n if (typeof htmlCanvas.toBlob !== 'function') {\n throw new StageUnsupportedError('This canvas does not support blob export.');\n }\n const blob = await new Promise<Blob | null>((resolve) => {\n htmlCanvas.toBlob(resolve, type, quality);\n });\n if (!blob) {\n throw new StageUnsupportedError('Canvas blob export returned no data.');\n }\n return blob;\n };\n\n /**\n * Region/scale export: layer caches are keyed to the live viewport\n * transform, so the requested crop cannot blit the cached composite. Every\n * layer is re-painted into scratch surfaces against the export transform\n * `translate(-region) × scale` (dpr 1; `scale` maps world units to export\n * pixels) and composited into a scratch output surface. The live frame,\n * caches, and dirty flags are untouched; the cost is a full repaint.\n */\n const exportRegion = async (options: StageBlobOptions, type: string): Promise<Blob> => {\n const region = options.region ?? visibleRect();\n requireRect(region, 'Export');\n // Default density matches the on-screen one: device pixels per world unit.\n const exportScale = options.scale ?? dpr * scaleOf(matrix);\n requireScale(exportScale, 'Export');\n const pw = Math.max(1, Math.round(region.width * exportScale));\n const ph = Math.max(1, Math.round(region.height * exportScale));\n const exportMatrix = multiply(scaleMatrix(exportScale), translate(-region.x, -region.y));\n const frame: PaintContext = { dpr: 1, matrix: exportMatrix, time: scheduler.now(), visibleRect: region };\n const scratch: StageSurface[] = [];\n try {\n const output = createSurface(pw, ph);\n scratch.push(output);\n const outCtx = output.getContext('2d', { alpha: true }) as CanvasRenderingContext2D | null;\n if (outCtx == null) {\n throw new StageUnsupportedError('Export surface has no 2D context.');\n }\n outCtx.setTransform(1, 0, 0, 1, 0, 0);\n outCtx.clearRect(0, 0, pw, ph);\n if (background != null) {\n outCtx.fillStyle = background;\n outCtx.fillRect(0, 0, pw, ph);\n }\n for (const layer of layers) {\n const surface = createSurface(pw, ph);\n scratch.push(surface);\n const ctx = surface.getContext('2d', { alpha: true }) as CanvasRenderingContext2D | null;\n if (ctx == null) {\n throw new StageUnsupportedError(`Layer surface for \"${layer.id}\" has no 2D context.`);\n }\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.clearRect(0, 0, pw, ph);\n const [a, b, c, d, e, f] = exportMatrix;\n ctx.setTransform(a, b, c, d, e, f);\n layer.paint(ctx, frame);\n outCtx.drawImage(surface as unknown as CanvasImageSource, 0, 0, pw, ph);\n }\n return await surfaceToBlob(output, type, options.quality);\n } finally {\n for (const surface of scratch) {\n surface.width = 0;\n surface.height = 0;\n }\n }\n };\n\n const renderFrame = (time: number): StageFrameInfo => {\n pending = false;\n frameHandle = null;\n if (disposed) return { repainted: [], time };\n\n const rect = visibleRect();\n const frame: PaintContext = { dpr, matrix, time, visibleRect: rect };\n const repainted: string[] = [];\n\n for (const layer of layers) {\n if (layer.dirty) {\n const ctx = ensureSurface(layer);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.clearRect(0, 0, layer.surface?.width ?? 0, layer.surface?.height ?? 0);\n applyWorldTransform(ctx);\n layer.paint(ctx, frame);\n layer.dirty = false;\n repainted.push(layer.id);\n }\n }\n\n const screen = canvas.getContext('2d');\n if (screen) {\n const pw = Math.max(1, Math.round(width * dpr));\n const ph = Math.max(1, Math.round(height * dpr));\n const cw = Math.max(1, Math.round(canvas.width));\n const ch = Math.max(1, Math.round(canvas.height));\n screen.setTransform(1, 0, 0, 1, 0, 0);\n screen.clearRect(0, 0, cw, ch);\n if (background != null) {\n screen.fillStyle = background;\n screen.fillRect(0, 0, cw, ch);\n }\n for (const layer of layers) {\n if (layer.surface) {\n // Composite the cached layer at native pixels; canvas is sized pw x ph.\n screen.drawImage(layer.surface as unknown as CanvasImageSource, 0, 0, pw, ph);\n }\n }\n }\n return { repainted, time };\n };\n\n const schedule = (): void => {\n if (disposed || pending) return;\n pending = true;\n frameHandle = scheduler.requestFrame((time) => {\n if (pending) renderFrame(time);\n });\n };\n\n const invalidateAll = (): void => {\n for (const layer of layers) layer.dirty = true;\n };\n\n const cancelFrame = (): void => {\n if (frameHandle != null) {\n scheduler.cancelFrame(frameHandle);\n frameHandle = null;\n }\n pending = false;\n };\n\n const dispose = (): void => {\n if (disposed) return;\n disposed = true;\n cancelFrame();\n for (const layer of layers) disposeSurface(layer);\n layers.length = 0;\n controller.abort();\n };\n\n canvas.width = Math.max(1, Math.round(width * dpr));\n canvas.height = Math.max(1, Math.round(height * dpr));\n\n const stage: Stage = {\n get canvas() {\n return canvas;\n },\n get disposalSignal() {\n return controller.signal;\n },\n get disposed() {\n return disposed;\n },\n [Symbol.dispose]: dispose,\n dispose,\n get dpr() {\n return dpr;\n },\n get height() {\n return height;\n },\n invalidate(layerId) {\n if (disposed) return;\n if (layerId == null) {\n invalidateAll();\n } else {\n const layer = layers.find((l) => l.id === layerId);\n if (!layer) throw new StageConfigError(`Unknown stage layer \"${layerId}\".`);\n layer.dirty = true;\n }\n schedule();\n },\n get matrix() {\n return matrix;\n },\n render(time) {\n if (disposed) return { repainted: [], time: time ?? scheduler.now() };\n cancelFrame();\n return renderFrame(time ?? scheduler.now());\n },\n resize(size, nextDpr) {\n if (disposed) return;\n requireSize(size, 'Stage');\n const resolvedDpr = nextDpr ?? dpr;\n requireDpr(resolvedDpr, 'Stage');\n width = size.width;\n height = size.height;\n dpr = resolvedDpr;\n canvas.width = Math.max(1, Math.round(width * dpr));\n canvas.height = Math.max(1, Math.round(height * dpr));\n // Resizing clears the canvas backing store, so every layer repaints.\n invalidateAll();\n schedule();\n },\n setTransform(next) {\n if (disposed) return;\n requireFiniteMatrix(next);\n matrix = next;\n invalidateAll();\n schedule();\n },\n async toBlob(blobOptions) {\n if (disposed) throw new StageDisposedError('Cannot export a disposed stage.');\n // Export must capture the current frame, not the last painted one.\n if (pending) stage.render();\n const type = blobOptions?.type ?? 'image/png';\n if (blobOptions?.region != null || blobOptions?.scale != null) {\n return await exportRegion(blobOptions, type);\n }\n return await surfaceToBlob(canvas, type, blobOptions?.quality);\n },\n get visibleRect() {\n return visibleRect();\n },\n get width() {\n return width;\n },\n };\n return stage;\n}\n"],"mappings":";;AAAA,IAAa,aAAb,cAAgC,MAAM;CACpC,YAAY,GAAiB,GAAqB;EAGhD,AAFA,MAAMC,GAASC,CAAI,GACnB,KAAK,OAAO,WAAW,MACvB,OAAO,eAAe,MAAM,WAAW,SAAS;CAClD;AACF,GAEa,mBAAb,cAAsC,WAAW,CAAC,GAGrC,wBAAb,cAA2C,WAAW,CAAC,GAG1C,qBAAb,cAAwC,WAAW,CAAC;;ACRpD,SAAgB,YAAY,GAAY,GAAuB;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ACA,MAAM,OAAO,GAAa;GACxB,IAAI9C,GAAU,MAAM,IAAI,mBAAmB,iCAAiC;GAE5E,AAAIE,KAASuC,EAAM,OAAO;GAC1B,IAAMlB,IAAOwB,GAAa,QAAQ;GAIlC,OAHIA,GAAa,UAAU,QAAQA,GAAa,SAAS,OAChD,MAAM,aAAaA,GAAaxB,CAAI,IAEtC,MAAM,cAAcc,GAAQd,GAAMwB,GAAa,OAAO;EAC/D;EACA,IAAI,cAAc;GAChB,OAAO,YAAY;EACrB;EACA,IAAI,QAAQ;GACV,OAAOzD;EACT;CACF;CACA,OAAOmD;AACT"}
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./main.cjs"),t=require("./serve.cjs");exports.createWorkerStage=e.createWorkerStage,exports.serveStage=t.serveStage;
@@ -0,0 +1,3 @@
1
+ export { createWorkerStage, type WorkerScope, type WorkerStage, type WorkerStageOptions } from './main.js';
2
+ export { type ServeStageSetup, type StageServer, serveStage, type WorkerSelfScope } from './serve.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/worker/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,KAAK,WAAW,EAAE,KAAK,WAAW,EAAE,KAAK,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAC3G,OAAO,EAAE,KAAK,eAAe,EAAE,KAAK,WAAW,EAAE,UAAU,EAAE,KAAK,eAAe,EAAE,MAAM,YAAY,CAAC"}
@@ -0,0 +1,3 @@
1
+ import { createWorkerStage as e } from "./main.js";
2
+ import { serveStage as t } from "./serve.js";
3
+ export { e as createWorkerStage, t as serveStage };
@@ -0,0 +1,2 @@
1
+ require("../_dev.cjs");const e=require("../_validate.cjs"),t=require("../errors.cjs");function reportWorkerError(e){let n=new t.StageError(`Worker stage error: ${e}`),r=globalThis.reportError;typeof r==`function`?r(n):queueMicrotask(()=>{throw n})}function createWorkerStage(n,r,i){let{width:a,height:o}=i;e.requireSize({height:o,width:a},`Worker stage`);let s=i.dpr??1;if(e.requireDpr(s,`Worker stage`),typeof n.transferControlToOffscreen!=`function`)throw new t.StageUnsupportedError(`This canvas cannot be transferred to a worker (transferControlToOffscreen).`);let c=new AbortController,l=new Map,u=1,d=!1,f=n.transferControlToOffscreen(),command=e=>{d||r.postMessage(e)},resolveReady=()=>{},rejectReady=()=>{},p=new Promise((e,t)=>{resolveReady=e,rejectReady=t});p.catch(()=>{});let onMessage=e=>{let n=e.data;if(n&&typeof n==`object`&&typeof n.type==`string`){if(n.type===`ready`){if(n.protocol!==2){let e=new t.StageError(`Worker stage protocol ${String(n.protocol)} does not match 2.`);rejectReady(e),dispose();return}resolveReady()}else if(n.type===`blob`){let e=l.get(n.id);if(!e){`${String(n.id)}`;return}l.delete(n.id),n.ok?e.resolve(n.blob):n.kind===`disposed`?e.reject(new t.StageDisposedError(`Worker blob export failed: ${n.error}`)):n.kind===`unsupported`?e.reject(new t.StageUnsupportedError(`Worker blob export failed: ${n.error}`)):e.reject(new t.StageError(`Worker blob export failed: ${n.error}`))}else n.type===`error`?reportWorkerError(n.error):`${String(n.type)}`}};r.addEventListener(`message`,onMessage),r.postMessage({background:i.background??null,canvas:f,dpr:s,height:o,protocol:2,type:`init`,width:a},[f]);let dispose=()=>{if(!d){d=!0,r.postMessage({type:`dispose`}),r.removeEventListener(`message`,onMessage);for(let e of l.values())e.reject(new t.StageDisposedError(`Stage disposed before blob export.`));l.clear(),rejectReady(new t.StageDisposedError(`Stage disposed before the worker became ready.`)),c.abort()}};return{disposalSignal:c.signal,dispose,get disposed(){return d},invalidate(e){command({layerId:e,type:`invalidate`})},ready:p,resize(t,n){e.requireSize(t,`Worker stage`);let r=n??s;e.requireDpr(r,`Worker stage`),command({dpr:r,type:`resize`,...t})},[Symbol.dispose]:dispose,sendScene(e){command({scene:e,type:`scene`})},setTransform(t){e.requireFiniteMatrix(t),command({matrix:t,type:`matrix`})},async toBlob(e){if(d)throw new t.StageDisposedError(`Cannot export a disposed stage.`);let n=u++;return await new Promise((t,r)=>{l.set(n,{reject:r,resolve:t}),command({id:n,options:e,type:`blob`})})}}}exports.createWorkerStage=createWorkerStage;
2
+ //# sourceMappingURL=main.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.cjs","names":["StageError","StageUnsupportedError","StageDisposedError","require__validate","require_errors","error","message","globalReportError","options","dpr","canvas","controller","pending","nextBlobId","disposed","offscreen","worker","cmd","ready","resolve","reject","event","entry","size","resolvedDpr","nextDpr","matrix","id","blobOptions"],"sources":["../../src/worker/main.ts"],"sourcesContent":["import type { Matrix, Size } from '@vielzeug/atlas';\nimport { warn } from '../_dev.js';\nimport { requireDpr, requireFiniteMatrix, requireSize } from '../_validate.js';\nimport { StageDisposedError, StageError, StageUnsupportedError } from '../errors.js';\nimport type { StageController } from '../stage.js';\nimport type { StageWorkerCommand, StageWorkerEvent } from './protocol.js';\nimport { STAGE_WORKER_PROTOCOL } from './protocol.js';\n\n/**\n * The message scope a worker stage talks to (a `Worker` in production).\n * Declared with method syntax so the DOM `Worker`'s overloaded `postMessage`\n * remains assignable.\n */\nexport type WorkerScope = Readonly<{\n postMessage(message: unknown, transfer?: Transferable[]): void;\n addEventListener(type: 'message', listener: (event: { data: unknown }) => void): void;\n removeEventListener(type: 'message', listener: (event: { data: unknown }) => void): void;\n}>;\n\nexport type WorkerStageOptions = Readonly<{\n dpr?: number;\n /** Background color cleared under the layers; defaults to transparent. */\n background?: string | null;\n}>;\n\n/**\n * Main-thread half of a worker-rendered stage. `Scene` is the application\n * payload type accepted by `sendScene` and delivered to the worker-side\n * `onScene` handler. The creator owns the worker: terminate it through\n * `disposalSignal` when the stage is disposed.\n */\nexport type WorkerStage<Scene = unknown> = StageController &\n Readonly<{\n /** Resolves when the worker acknowledges init with a matching `ready`; rejects on a protocol mismatch. */\n readonly ready: Promise<void>;\n /** Forward an application payload to the worker-side `onScene` handler; the handler decides what to invalidate. */\n sendScene: (scene: Scene) => void;\n }>;\n\n/** Surface a worker error like an uncaught error, matching main-thread painter behaviour. */\nfunction reportWorkerError(message: string): void {\n const error = new StageError(`Worker stage error: ${message}`);\n const globalReportError = (globalThis as { reportError?: (err: Error) => void }).reportError;\n if (typeof globalReportError === 'function') globalReportError(error);\n else\n queueMicrotask(() => {\n throw error;\n });\n}\n\n/**\n * Creates the main-thread half of a worker-rendered stage: transfers the\n * canvas to `worker` exactly once via `transferControlToOffscreen` and\n * forwards resize/transform/invalidate/scene commands. Blob requests are\n * correlated by id; disposal rejects pending requests with\n * `StageDisposedError`. Invalid size/DPR/matrix input throws `StageConfigError`\n * here, the same as `createStage`.\n */\nexport function createWorkerStage<Scene = unknown>(\n canvas: HTMLCanvasElement,\n worker: WorkerScope,\n options: WorkerStageOptions & Readonly<{ width: number; height: number }>,\n): WorkerStage<Scene> {\n const { width, height } = options;\n requireSize({ height, width }, 'Worker stage');\n const dpr = options.dpr ?? 1;\n requireDpr(dpr, 'Worker stage');\n if (typeof canvas.transferControlToOffscreen !== 'function') {\n throw new StageUnsupportedError('This canvas cannot be transferred to a worker (transferControlToOffscreen).');\n }\n const controller = new AbortController();\n const pending = new Map<number, { reject: (err: Error) => void; resolve: (blob: Blob) => void }>();\n let nextBlobId = 1;\n let disposed = false;\n\n const offscreen = canvas.transferControlToOffscreen();\n const command = (cmd: StageWorkerCommand): void => {\n if (!disposed) worker.postMessage(cmd);\n };\n\n let resolveReady: () => void = () => {};\n let rejectReady: (err: Error) => void = () => {};\n const ready = new Promise<void>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n // A stage disposed before the worker ever answered should not leave an\n // unhandled rejection in fire-and-forget usage.\n ready.catch(() => {});\n\n const onMessage = (event: { data: unknown }): void => {\n const message = event.data as StageWorkerEvent & { type?: string };\n if (!message || typeof message !== 'object' || typeof message.type !== 'string') {\n warn(`Ignoring unrecognized message from worker.`);\n return;\n }\n if (message.type === 'ready') {\n if (message.protocol !== STAGE_WORKER_PROTOCOL) {\n // A stale cached worker: fail loudly and tear the stage down.\n const error = new StageError(\n `Worker stage protocol ${String(message.protocol)} does not match ${STAGE_WORKER_PROTOCOL}.`,\n );\n rejectReady(error);\n dispose();\n return;\n }\n resolveReady();\n return;\n }\n if (message.type === 'blob') {\n const entry = pending.get(message.id);\n if (!entry) {\n warn(`Ignoring blob response for unknown request id ${String(message.id)}.`);\n return;\n }\n pending.delete(message.id);\n if (message.ok) entry.resolve(message.blob);\n else if (message.kind === 'disposed')\n entry.reject(new StageDisposedError(`Worker blob export failed: ${message.error}`));\n else if (message.kind === 'unsupported')\n entry.reject(new StageUnsupportedError(`Worker blob export failed: ${message.error}`));\n else entry.reject(new StageError(`Worker blob export failed: ${message.error}`));\n return;\n }\n if (message.type === 'error') {\n reportWorkerError(message.error);\n return;\n }\n warn(`Ignoring unknown message type \"${String((message as { type?: unknown }).type)}\" from worker.`);\n };\n worker.addEventListener('message', onMessage);\n\n worker.postMessage(\n {\n background: options.background ?? null,\n canvas: offscreen,\n dpr,\n height,\n protocol: STAGE_WORKER_PROTOCOL,\n type: 'init',\n width,\n },\n [offscreen],\n );\n\n const dispose = (): void => {\n if (disposed) return;\n disposed = true;\n worker.postMessage({ type: 'dispose' });\n worker.removeEventListener('message', onMessage);\n for (const entry of pending.values()) entry.reject(new StageDisposedError('Stage disposed before blob export.'));\n pending.clear();\n rejectReady(new StageDisposedError('Stage disposed before the worker became ready.'));\n controller.abort();\n };\n\n return {\n disposalSignal: controller.signal,\n dispose,\n get disposed() {\n return disposed;\n },\n invalidate(layerId) {\n command({ layerId, type: 'invalidate' });\n },\n ready,\n resize(size: Size, nextDpr?: number) {\n requireSize(size, 'Worker stage');\n const resolvedDpr = nextDpr ?? dpr;\n requireDpr(resolvedDpr, 'Worker stage');\n command({ dpr: resolvedDpr, type: 'resize', ...size });\n },\n [Symbol.dispose]: dispose,\n sendScene(scene: Scene) {\n command({ scene, type: 'scene' });\n },\n setTransform(matrix: Matrix) {\n requireFiniteMatrix(matrix);\n command({ matrix, type: 'matrix' });\n },\n async toBlob(blobOptions) {\n if (disposed) throw new StageDisposedError('Cannot export a disposed stage.');\n const id = nextBlobId++;\n const blob = await new Promise<Blob>((resolve, reject) => {\n pending.set(id, { reject, resolve });\n command({ id, options: blobOptions, type: 'blob' });\n });\n return blob;\n },\n };\n}\n"],"mappings":"A,sFAwCA,SAAS,kBAAkB,EAAuB,CAChD,IAAMK,EAAQ,IAAIL,EAAAA,WAAW,uBAAuBM,GAAS,EACvDC,EAAqB,WAAsD,YAC7E,OAAOA,GAAsB,WAAYA,EAAkBF,CAAK,EAElE,mBAAqB,CACnB,MAAMA,CACR,CAAC,CACL,CAUA,SAAgB,kBACd,EACA,EACA,EACoB,CACpB,GAAM,CAAE,QAAO,UAAWG,EAC1BL,EAAA,YAAY,CAAE,SAAQ,OAAM,EAAG,cAAc,EAC7C,IAAMM,EAAMD,EAAQ,KAAO,EAE3B,GADAL,EAAA,WAAWM,EAAK,cAAc,EAC1B,OAAOC,EAAO,4BAA+B,WAC/C,MAAM,IAAIT,EAAAA,sBAAsB,6EAA6E,EAE/G,IAAMU,EAAa,IAAI,gBACjBC,EAAU,IAAI,IAChBC,EAAa,EACbC,EAAW,GAETC,EAAYL,EAAO,2BAA2B,EAC9C,QAAW,GAAkC,CAC5CI,GAAUE,EAAO,YAAYC,CAAG,CACvC,EAEI,iBAAiC,CAAC,EAClC,gBAA0C,CAAC,EACzCC,EAAQ,IAAI,SAAe,EAAS,IAAW,CACnD,aAAeC,EACf,YAAcC,CAChB,CAAC,EAGDF,EAAM,UAAY,CAAC,CAAC,EAEpB,IAAM,UAAa,GAAmC,CACpD,IAAMZ,EAAUe,EAAM,KACtB,GAAKf,GAAW,OAAOA,GAAY,UAAY,OAAOA,EAAQ,MAAS,SAIvE,IAAIA,EAAQ,OAAS,QAAS,CAC5B,GAAIA,EAAQ,WAAA,EAAoC,CAE9C,IAAMD,EAAQ,IAAIL,EAAAA,WAChB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I,UAAW,CACb,OAAOG,CACT,EACA,WAAW,EAAS,CAClB,QAAQ,CAAE,UAAS,KAAM,YAAa,CAAC,CACzC,EACA,QACA,OAAO,EAAY,EAAkB,CACnCX,EAAA,YAAYoB,EAAM,cAAc,EAChC,IAAMC,EAAcC,GAAWhB,EAC/BN,EAAA,WAAWqB,EAAa,cAAc,EACtC,QAAQ,CAAE,IAAKA,EAAa,KAAM,SAAU,GAAGD,CAAK,CAAC,CACvD,GACC,OAAO,SAAU,QAClB,UAAU,EAAc,CACtB,QAAQ,CAAE,QAAO,KAAM,OAAQ,CAAC,CAClC,EACA,aAAa,EAAgB,CAC3BpB,EAAA,oBAAoBuB,CAAM,EAC1B,QAAQ,CAAE,SAAQ,KAAM,QAAS,CAAC,CACpC,EACA,MAAM,OAAO,EAAa,CACxB,GAAIZ,EAAU,MAAM,IAAIZ,EAAAA,mBAAmB,iCAAiC,EAC5E,IAAMyB,EAAK,IAKX,OAAO,MAJY,IAAI,SAAe,EAAS,IAAW,CACxDf,EAAQ,IAAIe,EAAI,CAAE,SAAQ,SAAQ,CAAC,EACnC,QAAQ,CAAE,KAAI,QAASC,EAAa,KAAM,MAAO,CAAC,CACpD,CAAC,CAEH,CACF,CACF,C"}
@@ -0,0 +1,45 @@
1
+ import type { StageController } from '../stage.js';
2
+ /**
3
+ * The message scope a worker stage talks to (a `Worker` in production).
4
+ * Declared with method syntax so the DOM `Worker`'s overloaded `postMessage`
5
+ * remains assignable.
6
+ */
7
+ export type WorkerScope = Readonly<{
8
+ postMessage(message: unknown, transfer?: Transferable[]): void;
9
+ addEventListener(type: 'message', listener: (event: {
10
+ data: unknown;
11
+ }) => void): void;
12
+ removeEventListener(type: 'message', listener: (event: {
13
+ data: unknown;
14
+ }) => void): void;
15
+ }>;
16
+ export type WorkerStageOptions = Readonly<{
17
+ dpr?: number;
18
+ /** Background color cleared under the layers; defaults to transparent. */
19
+ background?: string | null;
20
+ }>;
21
+ /**
22
+ * Main-thread half of a worker-rendered stage. `Scene` is the application
23
+ * payload type accepted by `sendScene` and delivered to the worker-side
24
+ * `onScene` handler. The creator owns the worker: terminate it through
25
+ * `disposalSignal` when the stage is disposed.
26
+ */
27
+ export type WorkerStage<Scene = unknown> = StageController & Readonly<{
28
+ /** Resolves when the worker acknowledges init with a matching `ready`; rejects on a protocol mismatch. */
29
+ readonly ready: Promise<void>;
30
+ /** Forward an application payload to the worker-side `onScene` handler; the handler decides what to invalidate. */
31
+ sendScene: (scene: Scene) => void;
32
+ }>;
33
+ /**
34
+ * Creates the main-thread half of a worker-rendered stage: transfers the
35
+ * canvas to `worker` exactly once via `transferControlToOffscreen` and
36
+ * forwards resize/transform/invalidate/scene commands. Blob requests are
37
+ * correlated by id; disposal rejects pending requests with
38
+ * `StageDisposedError`. Invalid size/DPR/matrix input throws `StageConfigError`
39
+ * here, the same as `createStage`.
40
+ */
41
+ export declare function createWorkerStage<Scene = unknown>(canvas: HTMLCanvasElement, worker: WorkerScope, options: WorkerStageOptions & Readonly<{
42
+ width: number;
43
+ height: number;
44
+ }>): WorkerStage<Scene>;
45
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../../src/worker/main.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAInD;;;;GAIG;AACH,MAAM,MAAM,WAAW,GAAG,QAAQ,CAAC;IACjC,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,YAAY,EAAE,GAAG,IAAI,CAAC;IAC/D,gBAAgB,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE;QAAE,IAAI,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,GAAG,IAAI,CAAC;IACtF,mBAAmB,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE;QAAE,IAAI,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,GAAG,IAAI,CAAC;CAC1F,CAAC,CAAC;AAEH,MAAM,MAAM,kBAAkB,GAAG,QAAQ,CAAC;IACxC,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,0EAA0E;IAC1E,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B,CAAC,CAAC;AAEH;;;;;GAKG;AACH,MAAM,MAAM,WAAW,CAAC,KAAK,GAAG,OAAO,IAAI,eAAe,GACxD,QAAQ,CAAC;IACP,0GAA0G;IAC1G,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9B,mHAAmH;IACnH,SAAS,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CACnC,CAAC,CAAC;AAaL;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,GAAG,OAAO,EAC/C,MAAM,EAAE,iBAAiB,EACzB,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,kBAAkB,GAAG,QAAQ,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,GACxE,WAAW,CAAC,KAAK,CAAC,CAgIpB"}
@@ -0,0 +1,114 @@
1
+ import "../_dev.js";
2
+ import { requireDpr as e, requireFiniteMatrix as t, requireSize as n } from "../_validate.js";
3
+ import { StageDisposedError as r, StageError as i, StageUnsupportedError as a } from "../errors.js";
4
+ // src/worker/main.ts
5
+ function reportWorkerError(e) {
6
+ let t = new i(`Worker stage error: ${e}`), n = globalThis.reportError;
7
+ typeof n == "function" ? n(t) : queueMicrotask(() => {
8
+ throw t;
9
+ });
10
+ }
11
+ function createWorkerStage(o, s, c) {
12
+ let { width: l, height: u } = c;
13
+ n({
14
+ height: u,
15
+ width: l
16
+ }, "Worker stage");
17
+ let d = c.dpr ?? 1;
18
+ if (e(d, "Worker stage"), typeof o.transferControlToOffscreen != "function") throw new a("This canvas cannot be transferred to a worker (transferControlToOffscreen).");
19
+ let f = new AbortController(), p = /* @__PURE__ */ new Map(), m = 1, h = !1, g = o.transferControlToOffscreen(), command = (e) => {
20
+ h || s.postMessage(e);
21
+ }, resolveReady = () => {}, rejectReady = () => {}, _ = new Promise((e, t) => {
22
+ resolveReady = e, rejectReady = t;
23
+ });
24
+ _.catch(() => {});
25
+ let onMessage = (e) => {
26
+ let t = e.data;
27
+ if (t && typeof t == "object" && typeof t.type == "string") {
28
+ if (t.type === "ready") {
29
+ if (t.protocol !== 2) {
30
+ let e = new i(`Worker stage protocol ${String(t.protocol)} does not match 2.`);
31
+ rejectReady(e), dispose();
32
+ return;
33
+ }
34
+ resolveReady();
35
+ } else if (t.type === "blob") {
36
+ let e = p.get(t.id);
37
+ if (!e) {
38
+ `${String(t.id)}`;
39
+ return;
40
+ }
41
+ p.delete(t.id), t.ok ? e.resolve(t.blob) : t.kind === "disposed" ? e.reject(new r(`Worker blob export failed: ${t.error}`)) : t.kind === "unsupported" ? e.reject(new a(`Worker blob export failed: ${t.error}`)) : e.reject(new i(`Worker blob export failed: ${t.error}`));
42
+ } else t.type === "error" ? reportWorkerError(t.error) : `${String(t.type)}`;
43
+ }
44
+ };
45
+ s.addEventListener("message", onMessage), s.postMessage({
46
+ background: c.background ?? null,
47
+ canvas: g,
48
+ dpr: d,
49
+ height: u,
50
+ protocol: 2,
51
+ type: "init",
52
+ width: l
53
+ }, [g]);
54
+ let dispose = () => {
55
+ if (!h) {
56
+ h = !0, s.postMessage({ type: "dispose" }), s.removeEventListener("message", onMessage);
57
+ for (let e of p.values()) e.reject(new r("Stage disposed before blob export."));
58
+ p.clear(), rejectReady(new r("Stage disposed before the worker became ready.")), f.abort();
59
+ }
60
+ };
61
+ return {
62
+ disposalSignal: f.signal,
63
+ dispose,
64
+ get disposed() {
65
+ return h;
66
+ },
67
+ invalidate(e) {
68
+ command({
69
+ layerId: e,
70
+ type: "invalidate"
71
+ });
72
+ },
73
+ ready: _,
74
+ resize(t, r) {
75
+ n(t, "Worker stage");
76
+ let i = r ?? d;
77
+ e(i, "Worker stage"), command({
78
+ dpr: i,
79
+ type: "resize",
80
+ ...t
81
+ });
82
+ },
83
+ [Symbol.dispose]: dispose,
84
+ sendScene(e) {
85
+ command({
86
+ scene: e,
87
+ type: "scene"
88
+ });
89
+ },
90
+ setTransform(e) {
91
+ t(e), command({
92
+ matrix: e,
93
+ type: "matrix"
94
+ });
95
+ },
96
+ async toBlob(e) {
97
+ if (h) throw new r("Cannot export a disposed stage.");
98
+ let t = m++;
99
+ return await new Promise((n, r) => {
100
+ p.set(t, {
101
+ reject: r,
102
+ resolve: n
103
+ }), command({
104
+ id: t,
105
+ options: e,
106
+ type: "blob"
107
+ });
108
+ });
109
+ }
110
+ };
111
+ }
112
+ export { createWorkerStage };
113
+
114
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.js","names":["error","StageError","message","globalReportError","options","dpr","requireDpr","canvas","StageUnsupportedError","controller","pending","nextBlobId","disposed","offscreen","worker","cmd","ready","resolve","reject","event","entry","StageDisposedError","size","resolvedDpr","nextDpr","requireFiniteMatrix","matrix","id","blobOptions"],"sources":["../../src/worker/main.ts"],"sourcesContent":["import type { Matrix, Size } from '@vielzeug/atlas';\nimport { warn } from '../_dev.js';\nimport { requireDpr, requireFiniteMatrix, requireSize } from '../_validate.js';\nimport { StageDisposedError, StageError, StageUnsupportedError } from '../errors.js';\nimport type { StageController } from '../stage.js';\nimport type { StageWorkerCommand, StageWorkerEvent } from './protocol.js';\nimport { STAGE_WORKER_PROTOCOL } from './protocol.js';\n\n/**\n * The message scope a worker stage talks to (a `Worker` in production).\n * Declared with method syntax so the DOM `Worker`'s overloaded `postMessage`\n * remains assignable.\n */\nexport type WorkerScope = Readonly<{\n postMessage(message: unknown, transfer?: Transferable[]): void;\n addEventListener(type: 'message', listener: (event: { data: unknown }) => void): void;\n removeEventListener(type: 'message', listener: (event: { data: unknown }) => void): void;\n}>;\n\nexport type WorkerStageOptions = Readonly<{\n dpr?: number;\n /** Background color cleared under the layers; defaults to transparent. */\n background?: string | null;\n}>;\n\n/**\n * Main-thread half of a worker-rendered stage. `Scene` is the application\n * payload type accepted by `sendScene` and delivered to the worker-side\n * `onScene` handler. The creator owns the worker: terminate it through\n * `disposalSignal` when the stage is disposed.\n */\nexport type WorkerStage<Scene = unknown> = StageController &\n Readonly<{\n /** Resolves when the worker acknowledges init with a matching `ready`; rejects on a protocol mismatch. */\n readonly ready: Promise<void>;\n /** Forward an application payload to the worker-side `onScene` handler; the handler decides what to invalidate. */\n sendScene: (scene: Scene) => void;\n }>;\n\n/** Surface a worker error like an uncaught error, matching main-thread painter behaviour. */\nfunction reportWorkerError(message: string): void {\n const error = new StageError(`Worker stage error: ${message}`);\n const globalReportError = (globalThis as { reportError?: (err: Error) => void }).reportError;\n if (typeof globalReportError === 'function') globalReportError(error);\n else\n queueMicrotask(() => {\n throw error;\n });\n}\n\n/**\n * Creates the main-thread half of a worker-rendered stage: transfers the\n * canvas to `worker` exactly once via `transferControlToOffscreen` and\n * forwards resize/transform/invalidate/scene commands. Blob requests are\n * correlated by id; disposal rejects pending requests with\n * `StageDisposedError`. Invalid size/DPR/matrix input throws `StageConfigError`\n * here, the same as `createStage`.\n */\nexport function createWorkerStage<Scene = unknown>(\n canvas: HTMLCanvasElement,\n worker: WorkerScope,\n options: WorkerStageOptions & Readonly<{ width: number; height: number }>,\n): WorkerStage<Scene> {\n const { width, height } = options;\n requireSize({ height, width }, 'Worker stage');\n const dpr = options.dpr ?? 1;\n requireDpr(dpr, 'Worker stage');\n if (typeof canvas.transferControlToOffscreen !== 'function') {\n throw new StageUnsupportedError('This canvas cannot be transferred to a worker (transferControlToOffscreen).');\n }\n const controller = new AbortController();\n const pending = new Map<number, { reject: (err: Error) => void; resolve: (blob: Blob) => void }>();\n let nextBlobId = 1;\n let disposed = false;\n\n const offscreen = canvas.transferControlToOffscreen();\n const command = (cmd: StageWorkerCommand): void => {\n if (!disposed) worker.postMessage(cmd);\n };\n\n let resolveReady: () => void = () => {};\n let rejectReady: (err: Error) => void = () => {};\n const ready = new Promise<void>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n // A stage disposed before the worker ever answered should not leave an\n // unhandled rejection in fire-and-forget usage.\n ready.catch(() => {});\n\n const onMessage = (event: { data: unknown }): void => {\n const message = event.data as StageWorkerEvent & { type?: string };\n if (!message || typeof message !== 'object' || typeof message.type !== 'string') {\n warn(`Ignoring unrecognized message from worker.`);\n return;\n }\n if (message.type === 'ready') {\n if (message.protocol !== STAGE_WORKER_PROTOCOL) {\n // A stale cached worker: fail loudly and tear the stage down.\n const error = new StageError(\n `Worker stage protocol ${String(message.protocol)} does not match ${STAGE_WORKER_PROTOCOL}.`,\n );\n rejectReady(error);\n dispose();\n return;\n }\n resolveReady();\n return;\n }\n if (message.type === 'blob') {\n const entry = pending.get(message.id);\n if (!entry) {\n warn(`Ignoring blob response for unknown request id ${String(message.id)}.`);\n return;\n }\n pending.delete(message.id);\n if (message.ok) entry.resolve(message.blob);\n else if (message.kind === 'disposed')\n entry.reject(new StageDisposedError(`Worker blob export failed: ${message.error}`));\n else if (message.kind === 'unsupported')\n entry.reject(new StageUnsupportedError(`Worker blob export failed: ${message.error}`));\n else entry.reject(new StageError(`Worker blob export failed: ${message.error}`));\n return;\n }\n if (message.type === 'error') {\n reportWorkerError(message.error);\n return;\n }\n warn(`Ignoring unknown message type \"${String((message as { type?: unknown }).type)}\" from worker.`);\n };\n worker.addEventListener('message', onMessage);\n\n worker.postMessage(\n {\n background: options.background ?? null,\n canvas: offscreen,\n dpr,\n height,\n protocol: STAGE_WORKER_PROTOCOL,\n type: 'init',\n width,\n },\n [offscreen],\n );\n\n const dispose = (): void => {\n if (disposed) return;\n disposed = true;\n worker.postMessage({ type: 'dispose' });\n worker.removeEventListener('message', onMessage);\n for (const entry of pending.values()) entry.reject(new StageDisposedError('Stage disposed before blob export.'));\n pending.clear();\n rejectReady(new StageDisposedError('Stage disposed before the worker became ready.'));\n controller.abort();\n };\n\n return {\n disposalSignal: controller.signal,\n dispose,\n get disposed() {\n return disposed;\n },\n invalidate(layerId) {\n command({ layerId, type: 'invalidate' });\n },\n ready,\n resize(size: Size, nextDpr?: number) {\n requireSize(size, 'Worker stage');\n const resolvedDpr = nextDpr ?? dpr;\n requireDpr(resolvedDpr, 'Worker stage');\n command({ dpr: resolvedDpr, type: 'resize', ...size });\n },\n [Symbol.dispose]: dispose,\n sendScene(scene: Scene) {\n command({ scene, type: 'scene' });\n },\n setTransform(matrix: Matrix) {\n requireFiniteMatrix(matrix);\n command({ matrix, type: 'matrix' });\n },\n async toBlob(blobOptions) {\n if (disposed) throw new StageDisposedError('Cannot export a disposed stage.');\n const id = nextBlobId++;\n const blob = await new Promise<Blob>((resolve, reject) => {\n pending.set(id, { reject, resolve });\n command({ id, options: blobOptions, type: 'blob' });\n });\n return blob;\n },\n };\n}\n"],"mappings":";;;;AAwCA,SAAS,kBAAkB,GAAuB;CAChD,IAAMA,IAAQ,IAAIC,EAAW,uBAAuBC,GAAS,GACvDC,IAAqB,WAAsD;CACjF,AAAI,OAAOA,KAAsB,aAAYA,EAAkBH,CAAK,IAElE,qBAAqB;EACnB,MAAMA;CACR,CAAC;AACL;AAUA,SAAgB,kBACd,GACA,GACA,GACoB;CACpB,IAAM,EAAE,UAAO,cAAWI;CAC1B,EAAY;EAAE;EAAQ;CAAM,GAAG,cAAc;CAC7C,IAAMC,IAAMD,EAAQ,OAAO;CAE3B,IADAE,EAAWD,GAAK,cAAc,GAC1B,OAAOE,EAAO,8BAA+B,YAC/C,MAAM,IAAIC,EAAsB,6EAA6E;CAE/G,IAAMC,IAAa,IAAI,gBAAgB,GACjCC,oBAAU,IAAI,IAA6E,GAC7FC,IAAa,GACbC,IAAW,IAETC,IAAYN,EAAO,2BAA2B,GAC9C,WAAW,MAAkC;EACjD,AAAKK,KAAUE,EAAO,YAAYC,CAAG;CACvC,GAEI,qBAAiC,CAAC,GAClC,oBAA0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AsB;EAC1B,IAAI,IACJ;GAEA,AAFA,IAAW,IACXC,EAAO,YAAY,EAAE,MAAM,UAAU,CAAC,GACtCA,EAAO,oBAAoB,WAAW,SAAS;GAC/C,KAAK,IAAMM,KAASV,EAAQ,OAAO,GAAG,EAAM,OAAO,IAAIW,EAAmB,oCAAoC,CAAC;GAG/G,AAFAX,EAAQ,MAAM,GACd,YAAY,IAAIW,EAAmB,gDAAgD,CAAC,GACpFZ,EAAW,MAAM;EANN;CAOb;CAEA,OAAO;EACL,gBAAgBA,EAAW;EAC3B;EACA,IAAI,WAAW;GACb,OAAOG;EACT;EACA,WAAW,GAAS;GAClB,QAAQ;IAAE;IAAS,MAAM;GAAa,CAAC;EACzC;EACA;EACA,OAAO,GAAY,GAAkB;GACnC,EAAYU,GAAM,cAAc;GAChC,IAAMC,IAAcC,KAAWnB;GAE/B,AADAC,EAAWiB,GAAa,cAAc,GACtC,QAAQ;IAAE,KAAKA;IAAa,MAAM;IAAU,GAAGD;GAAK,CAAC;EACvD;GACC,OAAO,UAAU;EAClB,UAAU,GAAc;GACtB,QAAQ;IAAE;IAAO,MAAM;GAAQ,CAAC;EAClC;EACA,aAAa,GAAgB;GAE3B,AADAG,EAAoBC,CAAM,GAC1B,QAAQ;IAAE;IAAQ,MAAM;GAAS,CAAC;EACpC;EACA,MAAM,OAAO,GAAa;GACxB,IAAId,GAAU,MAAM,IAAIS,EAAmB,iCAAiC;GAC5E,IAAMM,IAAK;GAKX,OAAO,MAJY,IAAI,SAAe,GAAS,MAAW;IAExD,AADAjB,EAAQ,IAAIiB,GAAI;KAAE;KAAQ;IAAQ,CAAC,GACnC,QAAQ;KAAE;KAAI,SAASC;KAAa,MAAM;IAAO,CAAC;GACpD,CAAC;EAEH;CACF;AACF"}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Internal worker message shapes. Not part of the public surface: both halves
3
+ * always ship from the same package build, so only the init/ready handshake
4
+ * carries the protocol version to catch a stale cached worker.
5
+ */
6
+ import type { Matrix } from '@vielzeug/atlas';
7
+ import type { StageBlobOptions } from '../stage.js';
8
+ /** Version of the stage worker protocol. Bumped whenever the message shapes change. */
9
+ export declare const STAGE_WORKER_PROTOCOL = 2;
10
+ /** Init message posted to the worker with the transferred canvas. */
11
+ export interface StageWorkerInit {
12
+ background: string | null;
13
+ canvas: OffscreenCanvas;
14
+ dpr: number;
15
+ height: number;
16
+ protocol: number;
17
+ type: 'init';
18
+ width: number;
19
+ }
20
+ /** Commands the main thread sends to the worker. */
21
+ export type StageWorkerCommand = {
22
+ type: 'resize';
23
+ width: number;
24
+ height: number;
25
+ dpr: number;
26
+ } | {
27
+ type: 'matrix';
28
+ matrix: Matrix;
29
+ } | {
30
+ type: 'invalidate';
31
+ layerId?: string;
32
+ } | {
33
+ type: 'blob';
34
+ id: number;
35
+ options?: StageBlobOptions;
36
+ }
37
+ /** Application payload forwarded verbatim to the worker-side `onScene` handler. */
38
+ | {
39
+ type: 'scene';
40
+ scene: unknown;
41
+ } | {
42
+ type: 'dispose';
43
+ };
44
+ /** Events the worker sends back to the main thread. */
45
+ export type StageWorkerEvent = {
46
+ type: 'ready';
47
+ protocol: number;
48
+ } | {
49
+ type: 'blob';
50
+ id: number;
51
+ ok: true;
52
+ blob: Blob;
53
+ } | {
54
+ type: 'blob';
55
+ id: number;
56
+ ok: false;
57
+ error: string;
58
+ kind?: StageWorkerErrorKind;
59
+ } | {
60
+ type: 'error';
61
+ error: string;
62
+ };
63
+ /** Coarse error taxonomy for failed blob exports, mapped back to typed errors main-side. */
64
+ export type StageWorkerErrorKind = 'disposed' | 'unsupported' | 'failed';
65
+ //# sourceMappingURL=protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../../src/worker/protocol.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,a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EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,oBAAoB,CAAA;CAAE,GACnF;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAErC,4FAA4F;AAC5F,MAAM,MAAM,oBAAoB,GAAG,UAAU,GAAG,aAAa,GAAG,QAAQ,CAAC"}
@@ -0,0 +1,2 @@
1
+ require("../_dev.cjs");const e=require("../errors.cjs"),t=require("../stage.cjs");function serveStage(n,r){let i,a,o=!1,fail=e=>{n.postMessage({error:String(e),type:`error`})},handle=s=>{if(!o)switch(s.type){case`init`:if(i)return;if(s.protocol!==2){fail(new e.StageUnsupportedError(`Main thread protocol ${String(s.protocol)} does not match 2.`));return}a=r(s),i=t.createStage(s.canvas,{background:s.background,dpr:s.dpr,height:s.height,layers:a.layers,width:s.width}),n.postMessage({protocol:2,type:`ready`});return;case`resize`:i?.resize({height:s.height,width:s.width},s.dpr);return;case`matrix`:i?.setTransform(s.matrix);return;case`invalidate`:i?.invalidate(s.layerId);return;case`scene`:i&&a?.onScene?.(s.scene,i);return;case`blob`:if(!i){n.postMessage({error:`Stage is not initialized.`,id:s.id,kind:`failed`,ok:!1,type:`blob`});return}i.render(),i.toBlob(s.options).then(e=>{n.postMessage({blob:e,id:s.id,ok:!0,type:`blob`})}).catch(t=>{let r=t instanceof e.StageDisposedError?`disposed`:t instanceof e.StageUnsupportedError?`unsupported`:`failed`;n.postMessage({error:String(t),id:s.id,kind:r,ok:!1,type:`blob`})});return;case`dispose`:shutdown();return;default:`${String(s.type)}`}},onMessage=e=>{let t=e.data;if(t&&typeof t==`object`&&typeof t.type==`string`)try{handle(t)}catch(e){fail(e)}},shutdown=()=>{o||(o=!0,n.removeEventListener?.(`message`,onMessage),i?.dispose(),i=void 0,a?.onDispose?.(),a=void 0)};return n.addEventListener(`message`,onMessage),{dispose:shutdown,get stage(){return i},[Symbol.dispose]:shutdown}}exports.serveStage=serveStage;
2
+ //# sourceMappingURL=serve.cjs.map