castle-web-cli 0.4.211 → 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 (49) hide show
  1. package/dist/cover-bridge/play-cover-bridge.js +2 -0
  2. package/dist/externalSourcemaps.d.ts +29 -0
  3. package/dist/externalSourcemaps.js +163 -0
  4. package/dist/fontFaceImports.d.ts +7 -0
  5. package/dist/fontFaceImports.js +129 -0
  6. package/dist/ide.js +7 -2
  7. package/dist/playCover/bridge.d.ts +6 -0
  8. package/dist/playCover/bridge.js +159 -0
  9. package/dist/playCover/builtins.d.ts +29 -0
  10. package/dist/playCover/builtins.js +189 -0
  11. package/dist/playCover/capture.d.ts +53 -0
  12. package/dist/playCover/capture.js +419 -0
  13. package/dist/playCover/clone.d.ts +40 -0
  14. package/dist/playCover/clone.js +317 -0
  15. package/dist/playCover/engine.d.ts +37 -0
  16. package/dist/playCover/engine.js +76 -0
  17. package/dist/playCover/errors.d.ts +6 -0
  18. package/dist/playCover/errors.js +18 -0
  19. package/dist/playCover/images.d.ts +21 -0
  20. package/dist/playCover/images.js +180 -0
  21. package/dist/playCover/instrument.d.ts +49 -0
  22. package/dist/playCover/instrument.js +334 -0
  23. package/dist/playCover/protocol.d.ts +14 -0
  24. package/dist/playCover/protocol.js +139 -0
  25. package/dist/playCover/rasterize.d.ts +21 -0
  26. package/dist/playCover/rasterize.js +408 -0
  27. package/dist/playCover/resources.d.ts +31 -0
  28. package/dist/playCover/resources.js +823 -0
  29. package/dist/playCover/scratchCanvas.d.ts +4 -0
  30. package/dist/playCover/scratchCanvas.js +16 -0
  31. package/dist/playCover/textSamples.d.ts +36 -0
  32. package/dist/playCover/textSamples.js +412 -0
  33. package/dist/playCover/validate.d.ts +79 -0
  34. package/dist/playCover/validate.js +883 -0
  35. package/dist/playCover/verify.d.ts +56 -0
  36. package/dist/playCover/verify.js +578 -0
  37. package/dist/playCover/verifyRecord.d.ts +71 -0
  38. package/dist/playCover/verifyRecord.js +243 -0
  39. package/dist/playCoverGate.d.ts +4 -0
  40. package/dist/playCoverGate.js +57 -0
  41. package/dist/playCoverPlacement.d.ts +11 -0
  42. package/dist/playCoverPlacement.js +110 -0
  43. package/dist/serve.d.ts +1 -0
  44. package/dist/serve.js +42 -17
  45. package/dist/shell/assets/index-BPhS3Ysy.css +1 -0
  46. package/dist/shell/assets/{index-DzLbNBc7.js → index-CcJiCq02.js} +94 -92
  47. package/dist/shell/index.html +2 -2
  48. package/package.json +2 -2
  49. package/dist/shell/assets/index-BCrgYh76.css +0 -1
@@ -0,0 +1,159 @@
1
+ // The Play cover capture bridge: the script the serve injects at the top of a
2
+ // deck page's <head> when CASTLE_PLAY_COVER=on (see serve.ts). Bundled into one
3
+ // classic script at build time (vite.cover-bridge.config.ts).
4
+ //
5
+ // Inert everywhere but the editor's Play panel: it does nothing at all --
6
+ // installs no hook, listens for nothing -- unless this page is the play role
7
+ // (`?edit=0`) AND framed. There it installs the capture instrumentation before
8
+ // any deck code runs and answers exactly two messages from its parent (see
9
+ // protocol.ts), checked the same way as the serve's own readiness handler:
10
+ // the sender must be `window.parent`, and must be the shell's origin once the
11
+ // page knows it (`window.__castleShellOrigin`).
12
+ //
13
+ // Provenance: the capture mechanism is the reviewed visual-snapshot prototype
14
+ // (castle-sandboxes `scripts/visual-snapshot-prototype/serializer.js`, with its
15
+ // capture/retake/discard lifecycle from `play-mode-preview-browser.js`); the
16
+ // rasterizer is the SVG foreignObject path verified against that prototype's
17
+ // packets. Nothing here exposes the capture to the deck's own code.
18
+ // First: builtins.ts takes its copies of the built-ins before anything else runs.
19
+ import { assertBuiltinsIntact, snapshotBuiltins } from './builtins.js';
20
+ import { assertFrameUnchanged, captureNextFrame, prepareCapture, releaseActiveCapture, releaseCapture, } from './capture.js';
21
+ import { CoverCaptureError, errorCode } from './errors.js';
22
+ import { installInstrumentation } from './instrument.js';
23
+ import { runningInWebKit } from './engine.js';
24
+ import { BRIDGE_DEADLINE_MS, COVER_TARGET_SELECTOR, FRAME_TIMEOUT_MS, MAX_REQUEST_ID_LENGTH, PLAY_COVER_CANCEL, PLAY_COVER_CAPTURE, PLAY_COVER_RESULT, coverFailureSentence, } from './protocol.js';
25
+ import { rasterizePacket } from './rasterize.js';
26
+ let inflight = null;
27
+ function isPlayFrame() {
28
+ try {
29
+ if (window.parent === window)
30
+ return false;
31
+ return new URLSearchParams(location.search).get('edit') === '0';
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ }
37
+ function captureTarget() {
38
+ return document.querySelector(COVER_TARGET_SELECTOR) ?? document.body;
39
+ }
40
+ function reply(to, body) {
41
+ try {
42
+ window.parent.postMessage({ type: PLAY_COVER_RESULT, requestId: to.requestId, ...body }, to.replyTo);
43
+ }
44
+ catch {
45
+ /* the shell navigated away; nobody is waiting */
46
+ }
47
+ }
48
+ // `detail` is the capture's own diagnostic (which check failed, where); the
49
+ // shell never shows it, but a report or a test harness can.
50
+ function failureBody(error) {
51
+ const code = errorCode(error);
52
+ const detail = error instanceof CoverCaptureError ? error.message.slice(0, 400) : undefined;
53
+ return { ok: false, code, message: coverFailureSentence(code, runningInWebKit()), detail };
54
+ }
55
+ async function runCapture(job) {
56
+ assertBuiltinsIntact();
57
+ const session = await prepareCapture(captureTarget(), job.controller.signal, (held) => {
58
+ job.session = held;
59
+ });
60
+ try {
61
+ const packet = await captureNextFrame(session, FRAME_TIMEOUT_MS);
62
+ assertFrameUnchanged(session);
63
+ assertBuiltinsIntact();
64
+ // The packet is inert data now; the deck runs on while it is rasterized.
65
+ releaseCapture(session);
66
+ const image = await rasterizePacket(packet, job.controller.signal);
67
+ if (job.controller.signal.aborted)
68
+ throw new CoverCaptureError('CAPTURE_CANCELED', 'the capture was canceled');
69
+ assertBuiltinsIntact();
70
+ return image;
71
+ }
72
+ finally {
73
+ releaseCapture(session);
74
+ }
75
+ }
76
+ function withDeadline(job, work) {
77
+ let timer = 0;
78
+ const deadline = new Promise((_resolve, reject) => {
79
+ timer = window.setTimeout(() => {
80
+ // Only this job's own session. After a cancel the bridge is free and a
81
+ // Retake may own the active capture by now; releasing "whatever is
82
+ // active" would cancel it. A session still being prepared sees the abort
83
+ // and releases itself.
84
+ job.controller.abort();
85
+ if (job.session)
86
+ releaseCapture(job.session);
87
+ reject(new CoverCaptureError('CAPTURE_TIMEOUT', 'the capture exceeded its deadline'));
88
+ }, BRIDGE_DEADLINE_MS);
89
+ });
90
+ return Promise.race([work, deadline]).finally(() => window.clearTimeout(timer));
91
+ }
92
+ async function startCapture(requestId, replyTo) {
93
+ if (inflight) {
94
+ reply({ requestId, replyTo }, failureBody(new CoverCaptureError('CAPTURE_BUSY', 'a capture is running')));
95
+ return;
96
+ }
97
+ const job = { requestId, replyTo, controller: new AbortController(), session: null };
98
+ inflight = job;
99
+ try {
100
+ const image = await withDeadline(job, runCapture(job));
101
+ reply(job, {
102
+ ok: true,
103
+ dataUrl: image.dataUrl,
104
+ width: image.width,
105
+ height: image.height,
106
+ diagnostics: image.diagnostics,
107
+ });
108
+ }
109
+ catch (error) {
110
+ reply(job, failureBody(error));
111
+ }
112
+ finally {
113
+ if (inflight === job)
114
+ inflight = null;
115
+ }
116
+ }
117
+ // Cancel frees the bridge at once, so a Retake right after it is not refused as
118
+ // busy. Releasing here is synchronous -- the freeze and the RAF hold are gone
119
+ // before the next message is read -- and the canceled job's own later steps all
120
+ // check its aborted signal, so it cannot take the freeze again. Its eventual
121
+ // CAPTURE_CANCELED reply names its own request id, which the shell has dropped.
122
+ function cancelCapture(requestId) {
123
+ const job = inflight;
124
+ if (!job || job.requestId !== requestId)
125
+ return;
126
+ job.controller.abort();
127
+ inflight = null;
128
+ if (job.session)
129
+ releaseCapture(job.session);
130
+ }
131
+ function onMessage(event) {
132
+ if (event.source !== window.parent)
133
+ return;
134
+ const shellOrigin = window.__castleShellOrigin;
135
+ if (shellOrigin && event.origin !== shellOrigin)
136
+ return;
137
+ const data = event.data;
138
+ if (!data || typeof data !== 'object')
139
+ return;
140
+ const requestId = data.requestId;
141
+ if (typeof requestId !== 'string' || !requestId || requestId.length > MAX_REQUEST_ID_LENGTH)
142
+ return;
143
+ if (data.type === PLAY_COVER_CAPTURE)
144
+ void startCapture(requestId, event.origin);
145
+ else if (data.type === PLAY_COVER_CANCEL)
146
+ cancelCapture(requestId);
147
+ }
148
+ if (isPlayFrame()) {
149
+ installInstrumentation();
150
+ snapshotBuiltins();
151
+ window.addEventListener('message', onMessage);
152
+ // A page on its way out must not leave anything held: release on hide, and
153
+ // abandon the request -- the reply would have nobody to go to.
154
+ window.addEventListener('pagehide', () => {
155
+ inflight?.controller.abort();
156
+ inflight = null;
157
+ releaseActiveCapture();
158
+ });
159
+ }
@@ -0,0 +1,29 @@
1
+ /** The fetch the page had at load: a deck's later wrapper never sees ours. */
2
+ export declare const nativeFetch: typeof fetch;
3
+ /** String.prototype.trim as it was at load. */
4
+ export declare function trim(value: string): string;
5
+ /** A violation's fields, read through the getters captured at load. */
6
+ export declare function violationFields(event: Event): {
7
+ disposition: unknown;
8
+ effectiveDirective: unknown;
9
+ blockedURI: unknown;
10
+ } | null;
11
+ export interface ParsedUrl {
12
+ /** The URL as a CSP report names it: no fragment, no credentials. */
13
+ reported: string;
14
+ /** "https:", "data:", ... */
15
+ protocol: string;
16
+ origin: string;
17
+ }
18
+ /** Parses with the native URL, normalized the way violation reports are. */
19
+ export declare function parseReportedUrl(raw: string, base: string): ParsedUrl | null;
20
+ /** A string-keyed record with no prototype: no method a deck can replace. */
21
+ export declare function newRecord(): Record<string, true>;
22
+ /**
23
+ * Takes the watched built-ins as they are now. Called once the bridge has
24
+ * installed its own hooks (the canvas 2D wrappers are among the watched
25
+ * slots) and before any deck script runs.
26
+ */
27
+ export declare function snapshotBuiltins(): void;
28
+ /** Refuses the capture if a watched built-in was replaced since load. */
29
+ export declare function assertBuiltinsIntact(): void;
@@ -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 {};