castle-web-cli 0.4.212 → 0.4.213

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 (46) hide show
  1. package/dist/cover-bridge/play-cover-bridge.js +2 -0
  2. package/dist/externalSourcemaps.js +2 -1
  3. package/dist/ide.js +7 -2
  4. package/dist/playCover/bridge.d.ts +6 -0
  5. package/dist/playCover/bridge.js +159 -0
  6. package/dist/playCover/builtins.d.ts +29 -0
  7. package/dist/playCover/builtins.js +189 -0
  8. package/dist/playCover/capture.d.ts +53 -0
  9. package/dist/playCover/capture.js +419 -0
  10. package/dist/playCover/clone.d.ts +40 -0
  11. package/dist/playCover/clone.js +317 -0
  12. package/dist/playCover/engine.d.ts +37 -0
  13. package/dist/playCover/engine.js +76 -0
  14. package/dist/playCover/errors.d.ts +6 -0
  15. package/dist/playCover/errors.js +18 -0
  16. package/dist/playCover/images.d.ts +21 -0
  17. package/dist/playCover/images.js +180 -0
  18. package/dist/playCover/instrument.d.ts +49 -0
  19. package/dist/playCover/instrument.js +334 -0
  20. package/dist/playCover/protocol.d.ts +14 -0
  21. package/dist/playCover/protocol.js +139 -0
  22. package/dist/playCover/rasterize.d.ts +21 -0
  23. package/dist/playCover/rasterize.js +408 -0
  24. package/dist/playCover/resources.d.ts +31 -0
  25. package/dist/playCover/resources.js +823 -0
  26. package/dist/playCover/scratchCanvas.d.ts +4 -0
  27. package/dist/playCover/scratchCanvas.js +16 -0
  28. package/dist/playCover/textSamples.d.ts +36 -0
  29. package/dist/playCover/textSamples.js +412 -0
  30. package/dist/playCover/validate.d.ts +79 -0
  31. package/dist/playCover/validate.js +883 -0
  32. package/dist/playCover/verify.d.ts +56 -0
  33. package/dist/playCover/verify.js +578 -0
  34. package/dist/playCover/verifyRecord.d.ts +71 -0
  35. package/dist/playCover/verifyRecord.js +243 -0
  36. package/dist/playCoverGate.d.ts +4 -0
  37. package/dist/playCoverGate.js +57 -0
  38. package/dist/playCoverPlacement.d.ts +11 -0
  39. package/dist/playCoverPlacement.js +110 -0
  40. package/dist/serve.d.ts +1 -0
  41. package/dist/serve.js +35 -17
  42. package/dist/shell/assets/index-BPhS3Ysy.css +1 -0
  43. package/dist/shell/assets/{index-DzLbNBc7.js → index-CcJiCq02.js} +94 -92
  44. package/dist/shell/index.html +2 -2
  45. package/package.json +2 -2
  46. package/dist/shell/assets/index-BCrgYh76.css +0 -1
@@ -0,0 +1,189 @@
1
+ // The built-ins the capture relies on, taken when the bridge loads -- before
2
+ // any deck script runs.
3
+ //
4
+ // Two layers. The CSP record (which font sources the page could not use)
5
+ // runs only on the captured primitives below: a null-prototype record, the
6
+ // native URL parser and its getters, and the violation event's own getters,
7
+ // all called through the captured Reflect.apply; string trimming uses the
8
+ // captured native trim too. Everything else the capture does (tokenizing
9
+ // CSS, walking the tree, embedding, drawing) uses ordinary built-ins, and
10
+ // assertBuiltinsIntact() checks, at the start of a capture, at its frame
11
+ // boundary and before its answer, that the ones it relies on -- the
12
+ // collection, array, string and RegExp methods, URL, getComputedStyle, the
13
+ // canvas 2D reads and writes and the XML serializer -- have not been
14
+ // replaced since load; a replaced one refuses the capture (BUILTINS_MODIFIED).
15
+ // It is not every built-in the capture calls, only those whose replacement
16
+ // could change what it reads or draws.
17
+ //
18
+ // That check guards against a deck -- or a library it loads -- patching a
19
+ // built-in in a way that would change what the capture reads. It is not a
20
+ // defense against a hostile deck: one that swaps a method and restores it
21
+ // between two checks is not caught, and the cover is the deck's own anyway.
22
+ // The list holds only methods the capture actually calls, so ordinary
23
+ // polyfills are not refused needlessly: core-js 3, zone.js and the common
24
+ // game libraries leave it untouched, and core-js 2 (babel-polyfill 6,
25
+ // @babel/polyfill 7) replaces String.prototype.trim, which is why trim is
26
+ // taken at load rather than watched. es6-shim replaces Set.prototype.has and
27
+ // add, which the capture does call, so a deck loading es6-shim is refused.
28
+ import { fail } from './errors.js';
29
+ const apply = Reflect.apply;
30
+ const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
31
+ const NativeURL = URL;
32
+ // Captured unbound on purpose: only ever called through the captured Reflect.apply.
33
+ // eslint-disable-next-line @typescript-eslint/unbound-method
34
+ const nativeTrim = String.prototype.trim;
35
+ const scope = globalThis;
36
+ const loadFetch = scope.fetch;
37
+ /** The fetch the page had at load: a deck's later wrapper never sees ours. */
38
+ export const nativeFetch = (input, init) => apply(loadFetch, scope, [input, init]);
39
+ /** String.prototype.trim as it was at load. */
40
+ export function trim(value) {
41
+ return apply(nativeTrim, value, []);
42
+ }
43
+ function getter(proto, name) {
44
+ // Captured unbound on purpose: only ever called through the captured Reflect.apply.
45
+ // eslint-disable-next-line @typescript-eslint/unbound-method
46
+ return getOwnPropertyDescriptor(proto, name)?.get;
47
+ }
48
+ const urlHref = getter(URL.prototype, 'href');
49
+ const urlProtocol = getter(URL.prototype, 'protocol');
50
+ const urlOrigin = getter(URL.prototype, 'origin');
51
+ function setter(proto, name) {
52
+ // Captured unbound on purpose: only ever called through the captured Reflect.apply.
53
+ // eslint-disable-next-line @typescript-eslint/unbound-method
54
+ return getOwnPropertyDescriptor(proto, name)?.set;
55
+ }
56
+ const urlSetHash = setter(URL.prototype, 'hash');
57
+ const urlSetUsername = setter(URL.prototype, 'username');
58
+ const urlSetPassword = setter(URL.prototype, 'password');
59
+ const violationProto = typeof SecurityPolicyViolationEvent === 'function'
60
+ ? SecurityPolicyViolationEvent.prototype
61
+ : null;
62
+ const violationGetters = violationProto
63
+ ? {
64
+ disposition: getter(violationProto, 'disposition'),
65
+ effectiveDirective: getter(violationProto, 'effectiveDirective'),
66
+ blockedURI: getter(violationProto, 'blockedURI'),
67
+ }
68
+ : null;
69
+ function read(get, target) {
70
+ return get ? apply(get, target, []) : undefined;
71
+ }
72
+ /** A violation's fields, read through the getters captured at load. */
73
+ export function violationFields(event) {
74
+ if (!violationGetters)
75
+ return null;
76
+ return {
77
+ disposition: read(violationGetters.disposition, event),
78
+ effectiveDirective: read(violationGetters.effectiveDirective, event),
79
+ blockedURI: read(violationGetters.blockedURI, event),
80
+ };
81
+ }
82
+ /** Parses with the native URL, normalized the way violation reports are. */
83
+ export function parseReportedUrl(raw, base) {
84
+ let url;
85
+ try {
86
+ url = new NativeURL(raw, base);
87
+ }
88
+ catch {
89
+ return null;
90
+ }
91
+ const protocol = String(read(urlProtocol, url));
92
+ const origin = String(read(urlOrigin, url));
93
+ if (urlSetHash)
94
+ apply(urlSetHash, url, ['']);
95
+ if (urlSetUsername)
96
+ apply(urlSetUsername, url, ['']);
97
+ if (urlSetPassword)
98
+ apply(urlSetPassword, url, ['']);
99
+ return { reported: String(read(urlHref, url)), protocol, origin };
100
+ }
101
+ /** A string-keyed record with no prototype: no method a deck can replace. */
102
+ export function newRecord() {
103
+ return Object.create(null);
104
+ }
105
+ // Entries that exist only in a browser (the unit tests load this in Node).
106
+ function browserOnly(entries) {
107
+ return typeof CanvasRenderingContext2D === 'function' ? entries() : [];
108
+ }
109
+ // Only what the capture calls after load (checked by grep when this list
110
+ // changes): Reflect.apply for the captured natives, Function.prototype.call
111
+ // in the canvas hooks, and the collection, array, string, RegExp, URL and
112
+ // style methods the capture code uses directly.
113
+ const WATCHED = [
114
+ [Reflect, 'apply'],
115
+ [Function.prototype, 'call'],
116
+ [Object, 'keys'],
117
+ [JSON, 'stringify'],
118
+ [Set.prototype, 'has'],
119
+ [Set.prototype, 'add'],
120
+ [Map.prototype, 'get'],
121
+ [Map.prototype, 'set'],
122
+ [Map.prototype, 'has'],
123
+ [Map.prototype, 'delete'],
124
+ [WeakMap.prototype, 'get'],
125
+ [WeakMap.prototype, 'set'],
126
+ [WeakMap.prototype, 'has'],
127
+ [Array.prototype, 'push'],
128
+ [Array.prototype, 'filter'],
129
+ [Array.prototype, 'some'],
130
+ [Array.prototype, 'every'],
131
+ [Array.prototype, 'map'],
132
+ [Array.prototype, 'join'],
133
+ [Array.prototype, 'includes'],
134
+ [Array.prototype, 'slice'],
135
+ [Array.prototype, Symbol.iterator],
136
+ [String.prototype, 'slice'],
137
+ [String.prototype, 'indexOf'],
138
+ [String.prototype, 'includes'],
139
+ [String.prototype, 'startsWith'],
140
+ [String.prototype, 'endsWith'],
141
+ [String.prototype, 'toLowerCase'],
142
+ [String.prototype, 'split'],
143
+ [String.prototype, 'replace'],
144
+ [RegExp.prototype, 'test'],
145
+ [RegExp.prototype, 'exec'],
146
+ [RegExp.prototype, Symbol.replace],
147
+ [RegExp.prototype, Symbol.split],
148
+ [scope, 'URL'],
149
+ [URL.prototype, 'href'],
150
+ [URL.prototype, 'origin'],
151
+ [URL.prototype, 'protocol'],
152
+ [scope, 'getComputedStyle'],
153
+ // Drawing and reading back the copy, and serializing it for the SVG image.
154
+ // (Not toBlob, which the capture also calls: zone.js's canvas patch
155
+ // replaces it, and Angular-style decks would all be refused.)
156
+ ...browserOnly(() => [
157
+ [CanvasRenderingContext2D.prototype, 'drawImage'],
158
+ [CanvasRenderingContext2D.prototype, 'getImageData'],
159
+ [CanvasRenderingContext2D.prototype, 'putImageData'],
160
+ [HTMLCanvasElement.prototype, 'toDataURL'],
161
+ [scope, 'XMLSerializer'],
162
+ [XMLSerializer.prototype, 'serializeToString'],
163
+ ]),
164
+ ];
165
+ function slot(target, key) {
166
+ const descriptor = getOwnPropertyDescriptor(target, key);
167
+ // Compared by identity only, never called.
168
+ // eslint-disable-next-line @typescript-eslint/unbound-method
169
+ return descriptor ? (descriptor.get ?? descriptor.value) : undefined;
170
+ }
171
+ const loaded = [];
172
+ /**
173
+ * Takes the watched built-ins as they are now. Called once the bridge has
174
+ * installed its own hooks (the canvas 2D wrappers are among the watched
175
+ * slots) and before any deck script runs.
176
+ */
177
+ export function snapshotBuiltins() {
178
+ for (let index = 0; index < WATCHED.length; index++)
179
+ loaded[index] = slot(...WATCHED[index]);
180
+ }
181
+ /** Refuses the capture if a watched built-in was replaced since load. */
182
+ export function assertBuiltinsIntact() {
183
+ for (let index = 0; index < WATCHED.length; index++) {
184
+ const [target, key] = WATCHED[index];
185
+ if (slot(target, key) !== loaded[index]) {
186
+ fail('BUILTINS_MODIFIED', `the page replaced a built-in the capture uses (${String(key)})`);
187
+ }
188
+ }
189
+ }
@@ -0,0 +1,53 @@
1
+ import { type EmbeddedResources } from './resources.js';
2
+ import { type CoverPacket } from './clone.js';
3
+ interface FrameGuard {
4
+ observer: MutationObserver;
5
+ mutations: number;
6
+ fingerprint: number;
7
+ canvases: {
8
+ canvas: HTMLCanvasElement;
9
+ revision: number;
10
+ width: number;
11
+ height: number;
12
+ }[];
13
+ }
14
+ export interface CaptureSession {
15
+ source: Element;
16
+ resources: EmbeddedResources;
17
+ freeze: HTMLStyleElement;
18
+ released: boolean;
19
+ armed: boolean;
20
+ captured: boolean;
21
+ batchesWithoutRender: number;
22
+ /** Browser animation frames seen while armed: none means the browser paused this frame. */
23
+ nativeTicks: number;
24
+ nativeTickId: number | undefined;
25
+ /** The end-of-frame observer waiting to run for the current frame. */
26
+ frameEnd: ResizeObserver | null;
27
+ guard: FrameGuard | null;
28
+ armTimer: number | undefined;
29
+ fallbackNativeId: number | undefined;
30
+ settle: {
31
+ resolve: (packet: CoverPacket) => void;
32
+ reject: (error: Error) => void;
33
+ } | null;
34
+ }
35
+ /**
36
+ * Rejects if anything the copy depends on moved after it was made: a DOM or
37
+ * style mutation, a canvas write or resize, or a change in computed style,
38
+ * geometry or scrolling. Detected, never waited out.
39
+ */
40
+ export declare function assertFrameUnchanged(session: CaptureSession): void;
41
+ /** Resolves with the copy made at the end of the deck's next frame. */
42
+ export declare function captureNextFrame(session: CaptureSession, timeoutMs: number): Promise<CoverPacket>;
43
+ /**
44
+ * Validates the card and embeds its resources, then pauses CSS animation and
45
+ * gives the pause two frames to paint. The returned session holds the deck's
46
+ * animation until `releaseCapture`, which every caller must reach.
47
+ */
48
+ export declare function prepareCapture(source: Element, signal: AbortSignal, onSession?: (session: CaptureSession) => void): Promise<CaptureSession>;
49
+ /** Undoes everything a session holds. Safe to call more than once. */
50
+ export declare function releaseCapture(session: CaptureSession): void;
51
+ /** Releases whatever capture is in progress (cancel, timeout, pagehide). */
52
+ export declare function releaseActiveCapture(): void;
53
+ export {};
@@ -0,0 +1,419 @@
1
+ // One Play cover capture, start to finish: prepare (validate the card, embed
2
+ // its images and fonts, pause CSS animation), wait for the end of the deck's
3
+ // next animation frame, copy the card synchronously right there -- WebGL
4
+ // buffers included, before the browser presents and clears them -- and then
5
+ // release the deck so it runs on.
6
+ //
7
+ // Adapted from the visual-snapshot prototype's serializer (see instrument.ts
8
+ // for provenance and the one deliberate difference: the capture boundary is
9
+ // the end of the frame's whole callback batch). The stale-frame guard, the
10
+ // synchronous WebGL-to-DOM copy and the always-release rule are the
11
+ // prototype's, unchanged in substance.
12
+ import { fail, CoverCaptureError } from './errors.js';
13
+ import { canvasRevisions, canvasWriteBatch, contexts, currentBatchId, freezeAnimationFrames, hasScheduledAnimationFrame, natives, resumeAnimationFrames, setBatchEndListener, setWriteTracking, } from './instrument.js';
14
+ import { preloadResources } from './resources.js';
15
+ import { serializeCard } from './clone.js';
16
+ import { visibleSnapshotElements } from './validate.js';
17
+ import { collectWebKitRefusedEffects } from './verifyRecord.js';
18
+ import { refuseWebKitCapture, refuseWebKitEffects, runningInWebKit } from './engine.js';
19
+ let activeSession = null;
20
+ function visibleCanvases(root) {
21
+ return visibleSnapshotElements(root).filter((element) => element instanceof HTMLCanvasElement);
22
+ }
23
+ // Visible WebGL canvases whose buffer the browser clears once it presents it.
24
+ function nonPersistentWebgl(root) {
25
+ return visibleCanvases(root).filter((canvas) => {
26
+ const tracked = contexts.get(canvas);
27
+ if (tracked?.kind !== 'webgl')
28
+ return false;
29
+ const gl = tracked.context;
30
+ return gl.getContextAttributes()?.preserveDrawingBuffer !== true;
31
+ });
32
+ }
33
+ function hashText(hash, text) {
34
+ let next = hash;
35
+ for (let index = 0; index < text.length; index++) {
36
+ next ^= text.charCodeAt(index);
37
+ next = Math.imul(next, 16777619);
38
+ }
39
+ return next >>> 0;
40
+ }
41
+ function frameFingerprint(root) {
42
+ let hash = 2166136261;
43
+ const add = (value) => {
44
+ hash = hashText(hash, String(value));
45
+ };
46
+ for (const element of visibleSnapshotElements(root)) {
47
+ const rect = element.getBoundingClientRect();
48
+ add(element.namespaceURI);
49
+ add(element.localName);
50
+ add(`${rect.x},${rect.y},${rect.width},${rect.height},${element.scrollLeft},${element.scrollTop}`);
51
+ if (element instanceof HTMLInputElement && ['checkbox', 'radio'].includes(element.type))
52
+ add(element.checked);
53
+ for (const pseudo of [null, '::before', '::after']) {
54
+ const style = getComputedStyle(element, pseudo);
55
+ // A pseudo-element with no content generates no box and paints nothing;
56
+ // walking its ~350 properties would only make the guard slower. One that
57
+ // gains content changes `content`, which is still read here.
58
+ if (pseudo && (style.content === 'none' || style.content === 'normal')) {
59
+ add(style.content);
60
+ continue;
61
+ }
62
+ for (const property of style) {
63
+ add(property);
64
+ add(style.getPropertyValue(property));
65
+ add(style.getPropertyPriority(property));
66
+ }
67
+ }
68
+ }
69
+ add(getComputedStyle(document.body).backgroundColor);
70
+ return hash;
71
+ }
72
+ function startFrameGuard(session) {
73
+ const root = session.source;
74
+ const observer = new MutationObserver((records) => {
75
+ if (session.guard)
76
+ session.guard.mutations += records.length;
77
+ });
78
+ observer.observe(root, { subtree: true, attributes: true, childList: true, characterData: true });
79
+ for (let ancestor = root.parentElement; ancestor; ancestor = ancestor.parentElement) {
80
+ observer.observe(ancestor, { attributes: true });
81
+ }
82
+ observer.observe(document.head, {
83
+ subtree: true,
84
+ attributes: true,
85
+ childList: true,
86
+ characterData: true,
87
+ });
88
+ session.guard = {
89
+ observer,
90
+ mutations: 0,
91
+ fingerprint: frameFingerprint(root),
92
+ canvases: visibleCanvases(root).map((canvas) => ({
93
+ canvas,
94
+ revision: canvasRevisions.get(canvas) ?? 0,
95
+ width: canvas.width,
96
+ height: canvas.height,
97
+ })),
98
+ };
99
+ }
100
+ /**
101
+ * Rejects if anything the copy depends on moved after it was made: a DOM or
102
+ * style mutation, a canvas write or resize, or a change in computed style,
103
+ * geometry or scrolling. Detected, never waited out.
104
+ */
105
+ export function assertFrameUnchanged(session) {
106
+ const guard = session.guard;
107
+ if (!session.captured || !guard)
108
+ fail('CAPTURE_NOT_COMPLETED', 'the frame guard starts at the capture boundary');
109
+ guard.mutations += guard.observer.takeRecords().length;
110
+ if (guard.mutations !== 0) {
111
+ fail('FRAME_CHANGED_AFTER_CAPTURE', 'observed a DOM/style mutation after the synchronous copy');
112
+ }
113
+ for (const baseline of guard.canvases) {
114
+ if ((canvasRevisions.get(baseline.canvas) ?? 0) !== baseline.revision ||
115
+ baseline.canvas.width !== baseline.width ||
116
+ baseline.canvas.height !== baseline.height) {
117
+ fail('FRAME_CHANGED_AFTER_CAPTURE', 'observed a canvas write or resize after the synchronous copy');
118
+ }
119
+ }
120
+ if (frameFingerprint(session.source) !== guard.fingerprint) {
121
+ fail('FRAME_CHANGED_AFTER_CAPTURE', 'computed style, geometry, or scrolling changed after the synchronous copy');
122
+ }
123
+ }
124
+ function webglPixelsToDataUrl(pixels, width, height) {
125
+ const surface = document.createElement('canvas');
126
+ surface.width = width;
127
+ surface.height = height;
128
+ const context = Reflect.apply(natives.getContext, surface, ['2d']);
129
+ const flipped = new Uint8ClampedArray(pixels.length);
130
+ const stride = width * 4;
131
+ for (let row = 0; row < height; row++) {
132
+ flipped.set(pixels.subarray(row * stride, (row + 1) * stride), (height - row - 1) * stride);
133
+ }
134
+ context.putImageData(new ImageData(flipped, width, height), 0, 0);
135
+ const dataUrl = surface.toDataURL('image/png');
136
+ surface.width = 0;
137
+ surface.height = 0;
138
+ return dataUrl;
139
+ }
140
+ // Reads a WebGL default framebuffer at the end of its render. Only valid for
141
+ // this synchronous turn: a non-persistent buffer is promised for nothing more.
142
+ function readWebglFrame(canvas) {
143
+ const tracked = contexts.get(canvas);
144
+ if (tracked?.kind !== 'webgl')
145
+ fail('WEBGL_CONTEXT_NOT_TRACKED', 'install the capture before creating the WebGL context');
146
+ const gl = tracked.context;
147
+ if (gl.isContextLost())
148
+ fail('WEBGL_CONTEXT_LOST', 'cannot capture a lost context');
149
+ gl.finish();
150
+ if (gl.getParameter(gl.FRAMEBUFFER_BINDING) !== null) {
151
+ fail('WEBGL_NONDEFAULT_FRAMEBUFFER', 'bind the default framebuffer');
152
+ }
153
+ if (tracked.requestedType === 'webgl2') {
154
+ const gl2 = gl;
155
+ if (gl2.getParameter(gl2.READ_FRAMEBUFFER_BINDING) !== null) {
156
+ fail('WEBGL_NONDEFAULT_READ_FRAMEBUFFER', 'bind the default read framebuffer');
157
+ }
158
+ }
159
+ const width = gl.drawingBufferWidth;
160
+ const height = gl.drawingBufferHeight;
161
+ if (!width || !height)
162
+ fail('WEBGL_EMPTY_BUFFER', 'drawing buffer has no pixels');
163
+ const pixels = new Uint8Array(width * height * 4);
164
+ gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
165
+ const error = gl.getError();
166
+ if (error !== gl.NO_ERROR)
167
+ fail('WEBGL_READBACK_FAILED', `gl.readPixels error ${error}`);
168
+ for (let alpha = 3; alpha < pixels.length; alpha += 4) {
169
+ if (pixels[alpha] !== 255) {
170
+ fail('WEBGL_TRANSPARENCY_UNSUPPORTED', 'only opaque WebGL default framebuffers are supported');
171
+ }
172
+ }
173
+ const frame = {
174
+ dataUrl: webglPixelsToDataUrl(pixels, width, height),
175
+ width,
176
+ height,
177
+ valid: true,
178
+ };
179
+ queueMicrotask(() => {
180
+ frame.valid = false;
181
+ });
182
+ return frame;
183
+ }
184
+ function readVisibleWebgl(root) {
185
+ const frames = new Map();
186
+ for (const canvas of visibleCanvases(root)) {
187
+ if (contexts.get(canvas)?.kind === 'webgl')
188
+ frames.set(canvas, readWebglFrame(canvas));
189
+ }
190
+ return frames;
191
+ }
192
+ function clearArm(session) {
193
+ session.armed = false;
194
+ if (session.nativeTickId !== undefined)
195
+ natives.cancelAnimationFrame(session.nativeTickId);
196
+ session.nativeTickId = undefined;
197
+ setBatchEndListener(null);
198
+ session.frameEnd?.disconnect();
199
+ session.frameEnd = null;
200
+ if (session.armTimer !== undefined)
201
+ window.clearTimeout(session.armTimer);
202
+ session.armTimer = undefined;
203
+ if (session.fallbackNativeId !== undefined)
204
+ natives.cancelAnimationFrame(session.fallbackNativeId);
205
+ session.fallbackNativeId = undefined;
206
+ }
207
+ function completeCapture(session) {
208
+ const settle = session.settle;
209
+ clearArm(session);
210
+ freezeAnimationFrames();
211
+ try {
212
+ startFrameGuard(session);
213
+ // Deliberately no await between reading the WebGL buffers and the copy.
214
+ const frames = readVisibleWebgl(session.source);
215
+ const { budget, fontCss, fontFamilies } = session.resources;
216
+ const packet = serializeCard(session.source, budget, fontCss, fontFamilies, frames);
217
+ session.captured = true;
218
+ settle?.resolve(packet);
219
+ }
220
+ catch (error) {
221
+ settle?.reject(error instanceof Error ? error : new Error(String(error)));
222
+ }
223
+ }
224
+ // A frame is capturable when every visible non-persistent WebGL canvas was
225
+ // drawn during it -- otherwise that buffer is already presented and cleared.
226
+ // Also: not resized since that draw. Setting width or height clears the
227
+ // buffer, so a deck that resizes its canvas in its own ResizeObserver and draws
228
+ // on the next frame (three.js's setSize pattern) holds an empty buffer at this
229
+ // boundary -- solid black under alpha:false, which would otherwise pass as a
230
+ // picture. Such a frame is skipped, and the next one captured.
231
+ function frameRendered(session) {
232
+ const batch = currentBatchId();
233
+ return nonPersistentWebgl(session.source).every((canvas) => {
234
+ const write = canvasWriteBatch.get(canvas);
235
+ return (write !== undefined &&
236
+ write.batch === batch &&
237
+ write.width === canvas.width &&
238
+ write.height === canvas.height);
239
+ });
240
+ }
241
+ function onFrameEnd(session) {
242
+ session.frameEnd?.disconnect();
243
+ session.frameEnd = null;
244
+ if (!session.armed)
245
+ return;
246
+ if (!frameRendered(session)) {
247
+ session.batchesWithoutRender++;
248
+ return;
249
+ }
250
+ completeCapture(session);
251
+ }
252
+ // The last animation callback of the frame has returned, but whatever it
253
+ // queued as microtasks -- the rest of an async render loop -- has not run yet.
254
+ // A fresh ResizeObserver's first notification is delivered later in the same
255
+ // rendering update: after every animation callback AND the microtask checkpoint
256
+ // that follows each one, and before the frame is painted and presented, so a
257
+ // non-persistent WebGL buffer still holds what was drawn. That is the capture
258
+ // boundary. (A plain queueMicrotask would run ahead of any render loop more
259
+ // than one await deep.)
260
+ //
261
+ // What the stale-frame guard can still see from here: it is checked in the
262
+ // microtasks right after this callback, with animation frames held, so it
263
+ // catches a microtask queued by the capture's own turn that writes to the card
264
+ // (DOM, style, canvas pixels or size). It cannot see a ResizeObserver the deck
265
+ // registered later in this delivery, a timer, or anything else that runs after
266
+ // that check -- by then the copy is inert data and what the page does next is
267
+ // not part of it.
268
+ function onBatchEnd(session) {
269
+ if (!session.armed || session.frameEnd)
270
+ return;
271
+ const observer = new ResizeObserver(() => onFrameEnd(session));
272
+ session.frameEnd = observer;
273
+ observer.observe(document.documentElement);
274
+ }
275
+ /** Resolves with the copy made at the end of the deck's next frame. */
276
+ export function captureNextFrame(session, timeoutMs) {
277
+ if (session.released)
278
+ fail('CAPTURE_CANCELED', 'the capture was released');
279
+ return new Promise((resolve, reject) => {
280
+ session.settle = { resolve, reject };
281
+ session.armed = true;
282
+ setBatchEndListener(() => onBatchEnd(session));
283
+ if (!hasScheduledAnimationFrame() && nonPersistentWebgl(session.source).length === 0) {
284
+ // Static HTML, Canvas 2D or persistent WebGL with no animation callback
285
+ // to follow: one native paint boundary, then the stale-frame guard. Not
286
+ // a claim that the deck finished rendering anything.
287
+ session.fallbackNativeId = natives.requestAnimationFrame(() => {
288
+ session.fallbackNativeId = undefined;
289
+ if (session.armed)
290
+ completeCapture(session);
291
+ });
292
+ }
293
+ countNativeTicks(session);
294
+ session.armTimer = window.setTimeout(() => {
295
+ clearArm(session);
296
+ reject(armTimeoutError(session, timeoutMs));
297
+ }, timeoutMs);
298
+ });
299
+ }
300
+ // Browsers stop animation frames for a frame that is hidden or scrolled out of
301
+ // view (Safari does it to an offscreen iframe). Counting the browser's own
302
+ // frames while armed is how a timeout tells "the browser paused this deck" from
303
+ // "the deck drew nothing".
304
+ function countNativeTicks(session) {
305
+ const tick = () => {
306
+ session.nativeTicks++;
307
+ if (session.armed)
308
+ session.nativeTickId = natives.requestAnimationFrame(tick);
309
+ };
310
+ session.nativeTickId = natives.requestAnimationFrame(tick);
311
+ }
312
+ function notVisible(detail) {
313
+ return new CoverCaptureError('FRAME_NOT_VISIBLE', `${detail} (visibilityState=${document.visibilityState})`);
314
+ }
315
+ function armTimeoutError(session, timeoutMs) {
316
+ if (session.nativeTicks === 0)
317
+ return notVisible(`the browser ran no animation frames in ${timeoutMs} ms`);
318
+ if (session.batchesWithoutRender > 0) {
319
+ return new CoverCaptureError('WEBGL_NOT_RENDERED_THIS_FRAME', 'no frame drew every visible WebGL canvas');
320
+ }
321
+ return new CoverCaptureError('APPLICATION_FRAME_TIMEOUT', `the browser ran ${session.nativeTicks} frames but the deck completed none`);
322
+ }
323
+ const PAUSE_PAINT_TIMEOUT_MS = 3_000;
324
+ function waitNativeFrames() {
325
+ return new Promise((resolve, reject) => {
326
+ const timer = window.setTimeout(() => reject(notVisible(`the browser ran no animation frames in ${PAUSE_PAINT_TIMEOUT_MS} ms`)), PAUSE_PAINT_TIMEOUT_MS);
327
+ natives.requestAnimationFrame(() => natives.requestAnimationFrame(() => {
328
+ window.clearTimeout(timer);
329
+ resolve();
330
+ }));
331
+ });
332
+ }
333
+ /**
334
+ * Validates the card and embeds its resources, then pauses CSS animation and
335
+ * gives the pause two frames to paint. The returned session holds the deck's
336
+ * animation until `releaseCapture`, which every caller must reach.
337
+ */
338
+ export async function prepareCapture(source, signal, onSession) {
339
+ if (activeSession)
340
+ fail('CAPTURE_BUSY', 'release the previous capture first');
341
+ if (document.visibilityState === 'hidden')
342
+ throw notVisible('the deck page is hidden');
343
+ // WebKit draws some shadows wrong in ways the check cannot see, so it is
344
+ // not trusted with any: refused before anything is fetched or frozen.
345
+ refuseWebKitCapture();
346
+ if (runningInWebKit())
347
+ refuseWebKitEffects(collectWebKitRefusedEffects(source));
348
+ if (document.compatMode !== 'CSS1Compat') {
349
+ fail('QUIRKS_MODE_DOCUMENT', 'the deck document renders in quirks mode');
350
+ }
351
+ const resources = await preloadResources(source, signal);
352
+ if (signal.aborted)
353
+ fail('CAPTURE_CANCELED', 'the capture was canceled');
354
+ if (activeSession)
355
+ fail('CAPTURE_BUSY', 'release the previous capture first');
356
+ const freeze = document.createElement('style');
357
+ freeze.setAttribute('data-castle-cover-freeze', '');
358
+ freeze.textContent =
359
+ '*,*::before,*::after{animation-play-state:paused!important;transition:none!important;caret-color:transparent!important}';
360
+ document.head.append(freeze);
361
+ const session = {
362
+ source,
363
+ resources,
364
+ freeze,
365
+ released: false,
366
+ armed: false,
367
+ captured: false,
368
+ batchesWithoutRender: 0,
369
+ nativeTicks: 0,
370
+ nativeTickId: undefined,
371
+ frameEnd: null,
372
+ guard: null,
373
+ armTimer: undefined,
374
+ fallbackNativeId: undefined,
375
+ settle: null,
376
+ };
377
+ activeSession = session;
378
+ setWriteTracking(true);
379
+ // Handed over the moment it holds the freeze, so its owner can release it
380
+ // even while this is still waiting for the pause to paint.
381
+ onSession?.(session);
382
+ try {
383
+ await waitNativeFrames();
384
+ }
385
+ catch (error) {
386
+ releaseCapture(session);
387
+ throw error;
388
+ }
389
+ if (session.released || signal.aborted) {
390
+ releaseCapture(session);
391
+ fail('CAPTURE_CANCELED', 'the capture was canceled');
392
+ }
393
+ return session;
394
+ }
395
+ /** Undoes everything a session holds. Safe to call more than once. */
396
+ export function releaseCapture(session) {
397
+ // A second release is a no-op, and must be: by then another capture may own
398
+ // the batch listener, the write tracking and the RAF hold.
399
+ if (session.released)
400
+ return;
401
+ const wasArmed = session.armed;
402
+ const settle = session.settle;
403
+ clearArm(session);
404
+ session.released = true;
405
+ session.guard?.observer.disconnect();
406
+ session.freeze.remove();
407
+ if (activeSession === session) {
408
+ activeSession = null;
409
+ setWriteTracking(false);
410
+ }
411
+ resumeAnimationFrames();
412
+ if (wasArmed)
413
+ settle?.reject(new CoverCaptureError('CAPTURE_CANCELED', 'the capture was released before a frame completed'));
414
+ }
415
+ /** Releases whatever capture is in progress (cancel, timeout, pagehide). */
416
+ export function releaseActiveCapture() {
417
+ if (activeSession)
418
+ releaseCapture(activeSession);
419
+ }