@vielzeug/stage 0.0.0-stage → 26.11.23

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 +14 -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 +81 -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 +218 -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 +67 -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,218 @@
1
+ import { apply as e, invert as t, rectFromPoints as n } 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 requireFiniteMatrix(e) {
16
+ for (let t of e) if (!Number.isFinite(t)) throw new StageConfigError(`Stage matrix must contain only finite numbers, got ${t}.`);
17
+ }
18
+ // src/stage.ts
19
+ var r = {
20
+ cancelFrame: (e) => {
21
+ typeof cancelAnimationFrame == "function" ? cancelAnimationFrame(e) : clearTimeout(e);
22
+ },
23
+ now: () => performance.now(),
24
+ requestFrame: (e) => typeof requestAnimationFrame == "function" ? requestAnimationFrame(e) : setTimeout(() => e(performance.now()), 16)
25
+ };
26
+ function defaultCreateSurface(e, t) {
27
+ if (typeof OffscreenCanvas < "u") return new OffscreenCanvas(e, t);
28
+ if (typeof document < "u") {
29
+ let n = document.createElement("canvas");
30
+ return n.width = e, n.height = t, n;
31
+ }
32
+ throw new StageUnsupportedError("No canvas surface factory is available in this environment.");
33
+ }
34
+ function createStage(i, a) {
35
+ let { width: o, height: s } = a;
36
+ requireSize({
37
+ height: s,
38
+ width: o
39
+ }, "Stage"), requireDpr(a.dpr ?? 1, "Stage");
40
+ let c = a.scheduler ?? r, l = a.createSurface ?? defaultCreateSurface, u = a.background ?? null, d = new AbortController(), f = !1, p = o, m = s, h = a.dpr ?? 1, g = [
41
+ 1,
42
+ 0,
43
+ 0,
44
+ 1,
45
+ 0,
46
+ 0
47
+ ], _ = null, v = !1, y = [];
48
+ for (let e of a.layers) {
49
+ if (y.some((t) => t.id === e.id)) throw new StageConfigError(`Stage layer id "${e.id}" is already registered.`);
50
+ y.push({
51
+ ctx: null,
52
+ dirty: !0,
53
+ id: e.id,
54
+ paint: e.paint,
55
+ surface: null
56
+ });
57
+ }
58
+ let disposeSurface = (e) => {
59
+ e.surface && (e.surface.width = 0, e.surface.height = 0), e.surface = null, e.ctx = null;
60
+ }, ensureSurface = (e) => {
61
+ let t = Math.max(1, Math.round(p * h)), n = Math.max(1, Math.round(m * h));
62
+ if (!e.surface || e.surface.width !== t || e.surface.height !== n) {
63
+ disposeSurface(e), e.surface = l(t, n);
64
+ let r = e.surface.getContext("2d", { alpha: !0 });
65
+ if (r == null) throw new StageUnsupportedError(`Layer surface for "${e.id}" has no 2D context.`);
66
+ e.ctx = r, e.dirty = !0;
67
+ }
68
+ return e.ctx;
69
+ }, visibleRect = () => {
70
+ let r = t(g);
71
+ if (!r) return {
72
+ height: m,
73
+ width: p,
74
+ x: 0,
75
+ y: 0
76
+ };
77
+ let i = [
78
+ e(r, {
79
+ x: 0,
80
+ y: 0
81
+ }),
82
+ e(r, {
83
+ x: p,
84
+ y: 0
85
+ }),
86
+ e(r, {
87
+ x: 0,
88
+ y: m
89
+ }),
90
+ e(r, {
91
+ x: p,
92
+ y: m
93
+ })
94
+ ];
95
+ return n(i);
96
+ }, applyWorldTransform = (e) => {
97
+ let [t, n, r, i, a, o] = g;
98
+ e.setTransform(h * t, h * n, h * r, h * i, h * a, h * o);
99
+ }, renderFrame = (e) => {
100
+ if (v = !1, _ = null, f) return {
101
+ repainted: [],
102
+ time: e
103
+ };
104
+ let t = visibleRect(), n = {
105
+ dpr: h,
106
+ matrix: g,
107
+ time: e,
108
+ visibleRect: t
109
+ }, r = [];
110
+ for (let e of y) if (e.dirty) {
111
+ let t = ensureSurface(e);
112
+ 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);
113
+ }
114
+ let a = i.getContext("2d");
115
+ if (a) {
116
+ let e = Math.max(1, Math.round(p * h)), t = Math.max(1, Math.round(m * h)), n = Math.max(1, Math.round(i.width)), r = Math.max(1, Math.round(i.height));
117
+ a.setTransform(1, 0, 0, 1, 0, 0), a.clearRect(0, 0, n, r), u != null && (a.fillStyle = u, a.fillRect(0, 0, n, r));
118
+ for (let n of y) n.surface && a.drawImage(n.surface, 0, 0, e, t);
119
+ }
120
+ return {
121
+ repainted: r,
122
+ time: e
123
+ };
124
+ }, schedule = () => {
125
+ f || v || (v = !0, _ = c.requestFrame((e) => {
126
+ v && renderFrame(e);
127
+ }));
128
+ }, invalidateAll = () => {
129
+ for (let e of y) e.dirty = !0;
130
+ }, cancelFrame = () => {
131
+ _ != null && (c.cancelFrame(_), _ = null), v = !1;
132
+ }, dispose = () => {
133
+ if (!f) {
134
+ f = !0, cancelFrame();
135
+ for (let e of y) disposeSurface(e);
136
+ y.length = 0, d.abort();
137
+ }
138
+ };
139
+ i.width = Math.max(1, Math.round(p * h)), i.height = Math.max(1, Math.round(m * h));
140
+ let b = {
141
+ get canvas() {
142
+ return i;
143
+ },
144
+ get disposalSignal() {
145
+ return d.signal;
146
+ },
147
+ get disposed() {
148
+ return f;
149
+ },
150
+ [Symbol.dispose]: dispose,
151
+ dispose,
152
+ get dpr() {
153
+ return h;
154
+ },
155
+ get height() {
156
+ return m;
157
+ },
158
+ invalidate(e) {
159
+ if (!f) {
160
+ if (e == null) invalidateAll();
161
+ else {
162
+ let t = y.find((t) => t.id === e);
163
+ if (!t) throw new StageConfigError(`Unknown stage layer "${e}".`);
164
+ t.dirty = !0;
165
+ }
166
+ schedule();
167
+ }
168
+ },
169
+ get matrix() {
170
+ return g;
171
+ },
172
+ render(e) {
173
+ return f ? {
174
+ repainted: [],
175
+ time: e ?? c.now()
176
+ } : (cancelFrame(), renderFrame(e ?? c.now()));
177
+ },
178
+ resize(e, t) {
179
+ if (f) return;
180
+ requireSize(e, "Stage");
181
+ let n = t ?? h;
182
+ requireDpr(n, "Stage"), p = e.width, m = e.height, h = n, i.width = Math.max(1, Math.round(p * h)), i.height = Math.max(1, Math.round(m * h)), invalidateAll(), schedule();
183
+ },
184
+ setTransform(e) {
185
+ f || (requireFiniteMatrix(e), g = e, invalidateAll(), schedule());
186
+ },
187
+ async toBlob(e) {
188
+ if (f) throw new StageDisposedError("Cannot export a disposed stage.");
189
+ v && b.render();
190
+ let t = e?.type ?? "image/png";
191
+ if (typeof OffscreenCanvas < "u" && i instanceof OffscreenCanvas) {
192
+ let n = await i.convertToBlob({
193
+ quality: e?.quality,
194
+ type: t
195
+ });
196
+ if (!n) throw new StageUnsupportedError("Canvas blob export returned no data.");
197
+ return n;
198
+ }
199
+ let n = i;
200
+ if (typeof n.toBlob != "function") throw new StageUnsupportedError("This canvas does not support blob export.");
201
+ let r = await new Promise((r) => {
202
+ n.toBlob(r, t, e?.quality);
203
+ });
204
+ if (!r) throw new StageUnsupportedError("Canvas blob export returned no data.");
205
+ return r;
206
+ },
207
+ get visibleRect() {
208
+ return visibleRect();
209
+ },
210
+ get width() {
211
+ return p;
212
+ }
213
+ };
214
+ return b;
215
+ }
216
+ export { StageConfigError, StageDisposedError, StageError, StageUnsupportedError, createStage };
217
+
218
+ //# sourceMappingURL=stage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stage.js","names":["message","opts","size","context","dpr","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","rect","frame","repainted","screen","canvas","cw","ch","time","stage","layerId","l","resolvedDpr","nextDpr","next","type","blobOptions","blob","htmlCanvas","resolve"],"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, 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 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 type Point,\n type Rect,\n rectFromPoints,\n type Size,\n} from '@vielzeug/atlas';\nimport { requireDpr, requireFiniteMatrix, 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\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 toBlob: (options?: { type?: string; quality?: number }) => 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 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 (typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas) {\n // OffscreenCanvas (worker-rendered stages): promise-based export.\n const blob = await canvas.convertToBlob({ quality: blobOptions?.quality, type });\n if (!blob) throw new StageUnsupportedError('Canvas blob export returned no data.');\n return blob;\n }\n const htmlCanvas = canvas 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, blobOptions?.quality);\n });\n if (!blob) {\n throw new StageUnsupportedError('Canvas blob export returned no data.');\n }\n return blob;\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,MAAMA,GAASC,CAAI,GACnB,KAAK,OAAO,WAAW,MACvB,OAAO,eAAe,MAAM,WAAW,SAAS;CAClD;AACF,G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AAI,mBAAmB,iCAAiC;GAE5E,AAAIE,KAASyB,EAAM,OAAO;GAC1B,IAAMM,IAAOC,GAAa,QAAQ;GAClC,IAAI,OAAO,kBAAoB,OAAeX,aAAkB,iBAAiB;IAE/E,IAAMY,IAAO,MAAMZ,EAAO,cAAc;KAAE,SAASW,GAAa;KAAS;IAAK,CAAC;IAC/E,IAAI,CAACC,GAAM,MAAM,IAAI,sBAAsB,sCAAsC;IACjF,OAAOA;GACT;GACA,IAAMC,IAAab;GACnB,IAAI,OAAOa,EAAW,UAAW,YAC/B,MAAM,IAAI,sBAAsB,2CAA2C;GAE7E,IAAMD,IAAO,MAAM,IAAI,SAAsB,MAAY;IACvD,EAAW,OAAOE,GAASJ,GAAMC,GAAa,OAAO;GACvD,CAAC;GACD,IAAI,CAACC,GACH,MAAM,IAAI,sBAAsB,sCAAsC;GAExE,OAAOA;EACT;EACA,IAAI,cAAc;GAChB,OAAO,YAAY;EACrB;EACA,IAAI,QAAQ;GACV,OAAO7C;EACT;CACF;CACA,OAAOqC;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!==1){let e=new t.StageError(`Worker stage protocol ${String(n.protocol)} does not match 1.`);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:1,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,YAA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AAO,oBAAoB,UAAW,SAAS,EAC/C,IAAK,IAAMM,KAASV,EAAQ,OAAO,EAAGU,EAAM,OAAO,IAAIpB,EAAAA,mBAAmB,oCAAoC,CAAC,EAC/GU,EAAQ,MAAM,EACd,YAAY,IAAIV,EAAAA,mBAAmB,gDAAgD,CAAC,EACpFS,EAAW,MAAM,CANN,CAOb,EAEA,MAAO,CACL,eAAgBA,EAAW,OAC3B,QACA,IAAI,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 !== 1) {
30
+ let e = new i(`Worker stage protocol ${String(t.protocol)} does not match 1.`);
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: 1,
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,OAA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,IAAIiB,GAAI;KAAE;KAAQ;IAAQ,CAAC,GACnC,QAAQ;KAAE;KAAI,SAASC;KAAa,MAAM;IAAO,CAAC;GACpD,CAAC;EAEH;CACF;AACF"}
@@ -0,0 +1,67 @@
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
+ /** Version of the stage worker protocol. Bumped whenever the message shapes change. */
8
+ export declare const STAGE_WORKER_PROTOCOL = 1;
9
+ /** Init message posted to the worker with the transferred canvas. */
10
+ export interface StageWorkerInit {
11
+ background: string | null;
12
+ canvas: OffscreenCanvas;
13
+ dpr: number;
14
+ height: number;
15
+ protocol: number;
16
+ type: 'init';
17
+ width: number;
18
+ }
19
+ /** Commands the main thread sends to the worker. */
20
+ export type StageWorkerCommand = {
21
+ type: 'resize';
22
+ width: number;
23
+ height: number;
24
+ dpr: number;
25
+ } | {
26
+ type: 'matrix';
27
+ matrix: Matrix;
28
+ } | {
29
+ type: 'invalidate';
30
+ layerId?: string;
31
+ } | {
32
+ type: 'blob';
33
+ id: number;
34
+ options?: {
35
+ type?: string;
36
+ quality?: number;
37
+ };
38
+ }
39
+ /** Application payload forwarded verbatim to the worker-side `onScene` handler. */
40
+ | {
41
+ type: 'scene';
42
+ scene: unknown;
43
+ } | {
44
+ type: 'dispose';
45
+ };
46
+ /** Events the worker sends back to the main thread. */
47
+ export type StageWorkerEvent = {
48
+ type: 'ready';
49
+ protocol: number;
50
+ } | {
51
+ type: 'blob';
52
+ id: number;
53
+ ok: true;
54
+ blob: Blob;
55
+ } | {
56
+ type: 'blob';
57
+ id: number;
58
+ ok: false;
59
+ error: string;
60
+ kind?: StageWorkerErrorKind;
61
+ } | {
62
+ type: 'error';
63
+ error: string;
64
+ };
65
+ /** Coarse error taxonomy for failed blob exports, mapped back to typed errors main-side. */
66
+ export type StageWorkerErrorKind = 'disposed' | 'unsupported' | 'failed';
67
+ //# 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,uFAAuF;AACvF,eAAO,MAAM,qBAAqB,IAAI,CAAC;AAEvC,qEAAqE;AACrE,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,MAAM,EAAE,eAAe,CAAC;IACxB,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACf;AAED,oDAAoD;AACpD,MAAM,MAAM,kBAAkB,GAC1B;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAC9D;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAClC;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,GACxC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE;AAC7E,mFAAmF;GACjF;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,GACjC;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,CAAC;AAExB,uDAAuD;AACvD,MAAM,MAAM,gBAAgB,GACxB;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,GACnC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,IAAI,CAAA;CAAE,GAClD;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,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!==1){fail(new e.StageUnsupportedError(`Main thread protocol ${String(s.protocol)} does not match 1.`));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:1,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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serve.cjs","names":["StageUnsupportedError","createStage","StageDisposedError","require_errors","require_stage","stage","current","disposed","scope","error","message","setup","kind","event"],"sources":["../../src/worker/serve.ts"],"sourcesContent":["import { warn } from '../_dev.js';\nimport { StageDisposedError, StageUnsupportedError } from '../errors.js';\nimport type { Stage, StageLayerOptions } from '../stage.js';\nimport { createStage } from '../stage.js';\nimport type { StageWorkerCommand, StageWorkerErrorKind, StageWorkerInit } from './protocol.js';\nimport { STAGE_WORKER_PROTOCOL } from './protocol.js';\n\n/** The message scope available inside a worker (`self` in production). */\nexport type WorkerSelfScope = Readonly<{\n postMessage: (message: unknown) => 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 ServeStageSetup<Scene = unknown> = Readonly<{\n /** Layer painters; the worker owns them, the main thread never names layers. */\n layers: readonly StageLayerOptions[];\n /**\n * Called for each `scene` command forwarded from the main thread. The\n * handler owns repaints: call `stage.invalidate(layerId)` for the layers\n * the payload actually changed.\n */\n onScene?: ((scene: Scene, stage: Stage) => void) | undefined;\n /** Called on dispose; release anything the setup or `onScene` allocated. */\n onDispose?: (() => void) | undefined;\n}>;\n\nexport type StageServer = Readonly<{\n readonly stage: Stage | undefined;\n dispose: () => void;\n [Symbol.dispose]: () => void;\n}>;\n\n/**\n * Worker half of a worker-rendered stage: waits for the `init` message,\n * creates a `createStage` bound to the transferred `OffscreenCanvas`, and\n * services resize/transform/invalidate/scene/blob commands. Painters are\n * registered worker-side in `setup`; the main thread only names the layers.\n * `Scene` is the application payload type handled by `onScene`.\n */\nexport function serveStage<Scene = unknown>(\n scope: WorkerSelfScope,\n setup: (init: StageWorkerInit) => ServeStageSetup<Scene>,\n): StageServer {\n let stage: Stage | undefined;\n let current: ServeStageSetup<Scene> | undefined;\n let disposed = false;\n\n const fail = (error: unknown): void => {\n scope.postMessage({ error: String(error), type: 'error' });\n };\n\n const handle = (message: StageWorkerCommand | StageWorkerInit): void => {\n // After dispose the scope may still deliver queued messages (a scope\n // without removeEventListener cannot be fully detached).\n if (disposed) return;\n switch (message.type) {\n case 'init': {\n if (stage) {\n warn('Ignoring a second init message; the canvas was already transferred.');\n return;\n }\n if (message.protocol !== STAGE_WORKER_PROTOCOL) {\n fail(\n new StageUnsupportedError(\n `Main thread protocol ${String(message.protocol)} does not match ${STAGE_WORKER_PROTOCOL}.`,\n ),\n );\n return;\n }\n current = setup(message);\n stage = createStage(message.canvas, {\n background: message.background,\n dpr: message.dpr,\n height: message.height,\n layers: current.layers,\n width: message.width,\n });\n scope.postMessage({ protocol: STAGE_WORKER_PROTOCOL, type: 'ready' });\n return;\n }\n case 'resize': {\n stage?.resize({ height: message.height, width: message.width }, message.dpr);\n return;\n }\n case 'matrix': {\n stage?.setTransform(message.matrix);\n return;\n }\n case 'invalidate': {\n stage?.invalidate(message.layerId);\n return;\n }\n case 'scene': {\n if (stage) current?.onScene?.(message.scene as Scene, stage);\n return;\n }\n case 'blob': {\n if (!stage) {\n scope.postMessage({\n error: 'Stage is not initialized.',\n id: message.id,\n kind: 'failed',\n ok: false,\n type: 'blob',\n });\n return;\n }\n stage.render();\n void stage\n .toBlob(message.options)\n .then((blob) => {\n scope.postMessage({ blob, id: message.id, ok: true, type: 'blob' });\n })\n .catch((error: unknown) => {\n const kind: StageWorkerErrorKind =\n error instanceof StageDisposedError\n ? 'disposed'\n : error instanceof StageUnsupportedError\n ? 'unsupported'\n : 'failed';\n scope.postMessage({ error: String(error), id: message.id, kind, ok: false, type: 'blob' });\n });\n return;\n }\n case 'dispose': {\n shutdown();\n return;\n }\n default: {\n warn(`Ignoring unknown command \"${String((message as { type?: unknown }).type)}\" from main thread.`);\n }\n }\n };\n\n const onMessage = (event: { data: unknown }): void => {\n const message = event.data as (StageWorkerCommand | StageWorkerInit) & { type?: unknown };\n if (!message || typeof message !== 'object' || typeof message.type !== 'string') {\n warn('Ignoring unrecognized message from main thread.');\n return;\n }\n try {\n handle(message);\n } catch (error) {\n fail(error);\n }\n };\n\n const shutdown = (): void => {\n if (disposed) return;\n disposed = true;\n scope.removeEventListener?.('message', onMessage);\n stage?.dispose();\n stage = undefined;\n current?.onDispose?.();\n current = undefined;\n };\n\n scope.addEventListener('message', onMessage);\n\n return {\n dispose: shutdown,\n get stage() {\n return stage;\n },\n [Symbol.dispose]: shutdown,\n };\n}\n"],"mappings":"A,kFAwCA,SAAgB,WACd,EACA,EACa,CACb,IAAIK,EACAC,EACAC,EAAW,GAET,KAAQ,GAAyB,CACrCC,EAAM,YAAY,CAAE,MAAO,OAAOC,CAAK,EAAG,KAAM,OAAQ,CAAC,CAC3D,EAEM,OAAU,GAAwD,CAGtE,GAAI,GACJ,OAAQC,EAAQ,KAAhB,CACE,IAAK,OACH,GAAIL,EAEF,OAEF,GAAIK,EAAQ,WAAA,EAAoC,CAC9C,KACE,IAAIV,EAAAA,sBACF,wBAAwB,OAAOU,EAAQ,QAAQ,EAAE,mBACnD,CACF,EACA,MACF,CACA,EAAUC,EAAMD,CAAO,EACvB,EAAQT,EAAAA,YAAYS,EAAQ,OAAQ,CAClC,WAAYA,EAAQ,WACpB,IAAKA,EAAQ,IACb,OAAQA,EAAQ,OAChB,OAAQJ,EAAQ,OAChB,MAAOI,EAAQ,KACjB,CAAC,EACDF,EAAM,YAAY,CAAE,SAAA,EAAiC,KAAM,OAAQ,CAAC,EACpE,OAEF,IAAK,SACHH,GAAO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AEpC,CACL,QAAS,SACT,IAAI,OAAQ,CACV,OAAOH,CACT,GACC,OAAO,SAAU,QACpB,CACF,C"}
@@ -0,0 +1,38 @@
1
+ import type { Stage, StageLayerOptions } from '../stage.js';
2
+ import type { StageWorkerInit } from './protocol.js';
3
+ /** The message scope available inside a worker (`self` in production). */
4
+ export type WorkerSelfScope = Readonly<{
5
+ postMessage: (message: unknown) => void;
6
+ addEventListener: (type: 'message', listener: (event: {
7
+ data: unknown;
8
+ }) => void) => void;
9
+ removeEventListener?: (type: 'message', listener: (event: {
10
+ data: unknown;
11
+ }) => void) => void;
12
+ }>;
13
+ export type ServeStageSetup<Scene = unknown> = Readonly<{
14
+ /** Layer painters; the worker owns them, the main thread never names layers. */
15
+ layers: readonly StageLayerOptions[];
16
+ /**
17
+ * Called for each `scene` command forwarded from the main thread. The
18
+ * handler owns repaints: call `stage.invalidate(layerId)` for the layers
19
+ * the payload actually changed.
20
+ */
21
+ onScene?: ((scene: Scene, stage: Stage) => void) | undefined;
22
+ /** Called on dispose; release anything the setup or `onScene` allocated. */
23
+ onDispose?: (() => void) | undefined;
24
+ }>;
25
+ export type StageServer = Readonly<{
26
+ readonly stage: Stage | undefined;
27
+ dispose: () => void;
28
+ [Symbol.dispose]: () => void;
29
+ }>;
30
+ /**
31
+ * Worker half of a worker-rendered stage: waits for the `init` message,
32
+ * creates a `createStage` bound to the transferred `OffscreenCanvas`, and
33
+ * services resize/transform/invalidate/scene/blob commands. Painters are
34
+ * registered worker-side in `setup`; the main thread only names the layers.
35
+ * `Scene` is the application payload type handled by `onScene`.
36
+ */
37
+ export declare function serveStage<Scene = unknown>(scope: WorkerSelfScope, setup: (init: StageWorkerInit) => ServeStageSetup<Scene>): StageServer;
38
+ //# sourceMappingURL=serve.d.ts.map