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.
- package/dist/cover-bridge/play-cover-bridge.js +2 -0
- package/dist/externalSourcemaps.d.ts +29 -0
- package/dist/externalSourcemaps.js +163 -0
- package/dist/fontFaceImports.d.ts +7 -0
- package/dist/fontFaceImports.js +129 -0
- package/dist/ide.js +7 -2
- package/dist/playCover/bridge.d.ts +6 -0
- package/dist/playCover/bridge.js +159 -0
- package/dist/playCover/builtins.d.ts +29 -0
- package/dist/playCover/builtins.js +189 -0
- package/dist/playCover/capture.d.ts +53 -0
- package/dist/playCover/capture.js +419 -0
- package/dist/playCover/clone.d.ts +40 -0
- package/dist/playCover/clone.js +317 -0
- package/dist/playCover/engine.d.ts +37 -0
- package/dist/playCover/engine.js +76 -0
- package/dist/playCover/errors.d.ts +6 -0
- package/dist/playCover/errors.js +18 -0
- package/dist/playCover/images.d.ts +21 -0
- package/dist/playCover/images.js +180 -0
- package/dist/playCover/instrument.d.ts +49 -0
- package/dist/playCover/instrument.js +334 -0
- package/dist/playCover/protocol.d.ts +14 -0
- package/dist/playCover/protocol.js +139 -0
- package/dist/playCover/rasterize.d.ts +21 -0
- package/dist/playCover/rasterize.js +408 -0
- package/dist/playCover/resources.d.ts +31 -0
- package/dist/playCover/resources.js +823 -0
- package/dist/playCover/scratchCanvas.d.ts +4 -0
- package/dist/playCover/scratchCanvas.js +16 -0
- package/dist/playCover/textSamples.d.ts +36 -0
- package/dist/playCover/textSamples.js +412 -0
- package/dist/playCover/validate.d.ts +79 -0
- package/dist/playCover/validate.js +883 -0
- package/dist/playCover/verify.d.ts +56 -0
- package/dist/playCover/verify.js +578 -0
- package/dist/playCover/verifyRecord.d.ts +71 -0
- package/dist/playCover/verifyRecord.js +243 -0
- package/dist/playCoverGate.d.ts +4 -0
- package/dist/playCoverGate.js +57 -0
- package/dist/playCoverPlacement.d.ts +11 -0
- package/dist/playCoverPlacement.js +110 -0
- package/dist/serve.d.ts +1 -0
- package/dist/serve.js +42 -17
- package/dist/shell/assets/index-BPhS3Ysy.css +1 -0
- package/dist/shell/assets/{index-DzLbNBc7.js → index-CcJiCq02.js} +94 -92
- package/dist/shell/index.html +2 -2
- package/package.json +2 -2
- package/dist/shell/assets/index-BCrgYh76.css +0 -1
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
// Turns a cover packet into the PNG the creator previews and Castle stores.
|
|
2
|
+
//
|
|
3
|
+
// The packet's HTML is laid out by the browser itself, inside an SVG
|
|
4
|
+
// <foreignObject> loaded as an image, and drawn onto a canvas at twice the
|
|
5
|
+
// card's CSS size. Everything the packet holds is a data: URL, so the image is
|
|
6
|
+
// self-contained and the canvas stays origin-clean in Chromium. A browser that
|
|
7
|
+
// taints it anyway (older WebKit does for foreignObject) fails with
|
|
8
|
+
// RASTERIZE_BLOCKED; there is deliberately no fallback to another, less
|
|
9
|
+
// faithful rasterizer.
|
|
10
|
+
//
|
|
11
|
+
// Before a PNG is returned it is checked against the page (verify.ts), and a
|
|
12
|
+
// drawing that does not match is RASTERIZE_MISMATCH: WebKit has been seen to
|
|
13
|
+
// ignore the scale and leave out every data: image and web font while
|
|
14
|
+
// reporting success. How the SVG is scaled is one of two geometries (a
|
|
15
|
+
// viewBox, then a CSS transform), tried in order; each is only used if its own
|
|
16
|
+
// drawing passes the check, so neither is a less faithful fallback -- they are
|
|
17
|
+
// two ways to ask for the same picture, and only a verified one is kept.
|
|
18
|
+
import { CoverCaptureError, fail } from './errors.js';
|
|
19
|
+
import { natives } from './instrument.js';
|
|
20
|
+
import { refuseWebKitEffects, runningInWebKit } from './engine.js';
|
|
21
|
+
import { bytesToDataUrl } from './resources.js';
|
|
22
|
+
import { COVER_MAX_EDGE, COVER_SCALE, MAX_COVER_PNG_BYTES } from './protocol.js';
|
|
23
|
+
import { HTML_NAMESPACE, SVG_NAMESPACE } from './validate.js';
|
|
24
|
+
import { bitmapCode, checkBitmap, checkStrip, checkUnclipped, loadBitmapRasters, readAndRelease, readRaster, releaseCanvas, stripElement, stripHeight, } from './verify.js';
|
|
25
|
+
// CSS zoom is not among the shipped choices: it passes the check, but in
|
|
26
|
+
// Chromium it lays text out measurably differently from the page (mean channel
|
|
27
|
+
// error 9.7 on a web-font card, against 0.05 for the other two). It stays
|
|
28
|
+
// available to a forced diagnostic build.
|
|
29
|
+
// `transform-padded` lays the card out with room around it inside the SVG
|
|
30
|
+
// image and crops it back, for a browser that misdraws effects reaching the
|
|
31
|
+
// image's edge.
|
|
32
|
+
function geometries() {
|
|
33
|
+
const forced = typeof __COVER_GEOMETRY__ === 'string' ? __COVER_GEOMETRY__ : null;
|
|
34
|
+
const known = ['viewbox', 'transform', 'transform-padded', 'zoom'];
|
|
35
|
+
if (forced && known.includes(forced))
|
|
36
|
+
return [forced];
|
|
37
|
+
return ['viewbox', 'transform', 'transform-padded'];
|
|
38
|
+
}
|
|
39
|
+
// Room around the card in a padded drawing, in output pixels: whole pixels, so
|
|
40
|
+
// the crop back to the card lands exactly on the unpadded drawing's grid.
|
|
41
|
+
function padFor(scale) {
|
|
42
|
+
return Math.round(48 * scale);
|
|
43
|
+
}
|
|
44
|
+
const ATTEMPTS = 4;
|
|
45
|
+
/** The output scale for a card: 2x, with the long edge held to COVER_MAX_EDGE. */
|
|
46
|
+
export function coverScale(width, height) {
|
|
47
|
+
return Math.min(COVER_SCALE, COVER_MAX_EDGE / Math.max(width, height));
|
|
48
|
+
}
|
|
49
|
+
// The packet as an XHTML subtree, serialized as XML so every attribute, text
|
|
50
|
+
// node and the font CSS is escaped for the SVG document it goes into. In the
|
|
51
|
+
// magenta and black modes each checked bitmap is a solid box of the same
|
|
52
|
+
// geometry instead (verify.ts); `strip` adds the check strip under the card.
|
|
53
|
+
function packetXml(packet, mode, strip) {
|
|
54
|
+
const parsed = document.implementation.createHTMLDocument('');
|
|
55
|
+
parsed.body.innerHTML = packet.html;
|
|
56
|
+
const { marker } = packet;
|
|
57
|
+
if (mode === 'magenta' || mode === 'black')
|
|
58
|
+
replaceBitmaps(parsed, mode, marker, null);
|
|
59
|
+
const only = /^(magenta|black)-only-(\d+)$/.exec(mode);
|
|
60
|
+
if (only)
|
|
61
|
+
replaceBitmaps(parsed, only[1], marker, Number(only[2]));
|
|
62
|
+
if (mode === 'unclip-root')
|
|
63
|
+
for (const root of Array.from(parsed.body.children))
|
|
64
|
+
unclip(root, true, marker);
|
|
65
|
+
const boxIndex = mode.startsWith('unclip-box-') ? Number(mode.slice('unclip-box-'.length)) : -1;
|
|
66
|
+
if (boxIndex >= 0) {
|
|
67
|
+
// This box, the recorded boxes around it, and the card's own clip.
|
|
68
|
+
for (const index of [boxIndex, ...packet.effectClips.clips[boxIndex].ancestors]) {
|
|
69
|
+
const box = parsed.body.querySelector(`[${marker}-effect-clip="${index}"]`);
|
|
70
|
+
if (box instanceof HTMLElement)
|
|
71
|
+
unclip(box, false, marker);
|
|
72
|
+
}
|
|
73
|
+
for (const root of Array.from(parsed.body.children))
|
|
74
|
+
unclip(root, true, marker);
|
|
75
|
+
}
|
|
76
|
+
const card = parsed.createElementNS(HTML_NAMESPACE, 'div');
|
|
77
|
+
const cardOverflow = mode === 'unclip-root' || boxIndex >= 0 ? 'visible' : 'hidden';
|
|
78
|
+
card.setAttribute('style', `margin:0;width:${packet.width}px;height:${packet.height}px;overflow:${cardOverflow};background:${packet.backdropColor}`);
|
|
79
|
+
if (packet.fontCss) {
|
|
80
|
+
const style = parsed.createElementNS(HTML_NAMESPACE, 'style');
|
|
81
|
+
style.textContent = packet.fontCss;
|
|
82
|
+
card.append(style);
|
|
83
|
+
}
|
|
84
|
+
card.append(...Array.from(parsed.body.childNodes));
|
|
85
|
+
if (!strip)
|
|
86
|
+
return new XMLSerializer().serializeToString(card);
|
|
87
|
+
const column = parsed.createElementNS(HTML_NAMESPACE, 'div');
|
|
88
|
+
column.setAttribute('style', `margin:0;width:${packet.width}px`);
|
|
89
|
+
column.append(card, stripElement(parsed, HTML_NAMESPACE, packet.width, packet.textSamples, packet.effects));
|
|
90
|
+
return new XMLSerializer().serializeToString(column);
|
|
91
|
+
}
|
|
92
|
+
// Lets a box's content paint past it without changing its layout: overflow
|
|
93
|
+
// other than visible makes a block its own formatting context, which
|
|
94
|
+
// flow-root keeps. `root` also unclips the card inside a transformed-root
|
|
95
|
+
// wrapper (clone.ts), which is the wrapper's only child -- never any other.
|
|
96
|
+
function unclip(element, root, marker) {
|
|
97
|
+
const style = element.style;
|
|
98
|
+
if (!style)
|
|
99
|
+
return;
|
|
100
|
+
const clipping = (value) => value !== '' && value !== 'visible';
|
|
101
|
+
if (clipping(style.overflowX) || clipping(style.overflowY)) {
|
|
102
|
+
// Still a clipping box, so what depends on one (text-overflow: ellipsis)
|
|
103
|
+
// lays out the same, but with its clip pushed far outside the card. It
|
|
104
|
+
// stays its own formatting context, as overflow other than visible made it.
|
|
105
|
+
if (style.display === 'block')
|
|
106
|
+
style.setProperty('display', 'flow-root', 'important');
|
|
107
|
+
style.setProperty('overflow', 'clip', 'important');
|
|
108
|
+
style.setProperty('overflow-clip-margin', '8192px', 'important');
|
|
109
|
+
}
|
|
110
|
+
if (root &&
|
|
111
|
+
element.hasAttribute(`${marker}-root-wrapper`) &&
|
|
112
|
+
element.firstElementChild instanceof HTMLElement) {
|
|
113
|
+
unclip(element.firstElementChild, false, marker);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function replaceBitmaps(parsed, mode, marker, only) {
|
|
117
|
+
for (const image of Array.from(parsed.querySelectorAll(`img[${marker}-bitmap]`))) {
|
|
118
|
+
if (only !== null && Number(image.getAttribute(`${marker}-bitmap`)) !== only)
|
|
119
|
+
continue;
|
|
120
|
+
const box = parsed.createElement('span');
|
|
121
|
+
const style = image.style;
|
|
122
|
+
box.setAttribute('style', style.cssText);
|
|
123
|
+
if (style.display === 'inline')
|
|
124
|
+
box.style.setProperty('display', 'inline-block', 'important');
|
|
125
|
+
const id = Number(image.getAttribute(`${marker}-bitmap`));
|
|
126
|
+
box.style.setProperty('background', mode === 'magenta' ? bitmapCode(id) : '#000000', 'important');
|
|
127
|
+
box.style.setProperty('background-clip', 'content-box', 'important');
|
|
128
|
+
image.replaceWith(box);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
// `padOut` output pixels of room on every side (the body is inset by the same
|
|
132
|
+
// amount in CSS pixels); drawDocument crops it back off.
|
|
133
|
+
function svgDocument(body, cssWidth, cssHeight, scale, geometry, padOut = 0) {
|
|
134
|
+
const pad = padOut / scale;
|
|
135
|
+
const width = cssWidth + 2 * pad;
|
|
136
|
+
const height = cssHeight + 2 * pad;
|
|
137
|
+
const outWidth = Math.round(cssWidth * scale) + 2 * padOut;
|
|
138
|
+
const outHeight = Math.round(cssHeight * scale) + 2 * padOut;
|
|
139
|
+
const inset = pad
|
|
140
|
+
? `<div xmlns="${HTML_NAMESPACE}" style="margin:0;padding:${pad}px">${body}</div>`
|
|
141
|
+
: body;
|
|
142
|
+
if (geometry === 'viewbox') {
|
|
143
|
+
return (`<svg xmlns="${SVG_NAMESPACE}" width="${outWidth}" height="${outHeight}" viewBox="0 0 ${width} ${height}">` +
|
|
144
|
+
`<foreignObject x="0" y="0" width="${width}" height="${height}">${inset}</foreignObject></svg>`);
|
|
145
|
+
}
|
|
146
|
+
const scaling = geometry === 'zoom' ? `zoom:${scale}` : `transform:scale(${scale});transform-origin:0 0`;
|
|
147
|
+
return (`<svg xmlns="${SVG_NAMESPACE}" width="${outWidth}" height="${outHeight}">` +
|
|
148
|
+
`<foreignObject x="0" y="0" width="${outWidth}" height="${outHeight}">` +
|
|
149
|
+
`<div xmlns="${HTML_NAMESPACE}" style="margin:0;width:${width}px;height:${height}px;${scaling}">${inset}</div>` +
|
|
150
|
+
'</foreignObject></svg>');
|
|
151
|
+
}
|
|
152
|
+
// Draws a document with its padding cropped off: whole-pixel offsets at 1:1,
|
|
153
|
+
// so the result is exactly the card region of the drawing.
|
|
154
|
+
function drawDocument(doc, width, height) {
|
|
155
|
+
const canvas = document.createElement('canvas');
|
|
156
|
+
canvas.width = width;
|
|
157
|
+
canvas.height = height;
|
|
158
|
+
const context = Reflect.apply(natives.getContext, canvas, [
|
|
159
|
+
'2d',
|
|
160
|
+
]);
|
|
161
|
+
if (!context)
|
|
162
|
+
fail('RASTERIZE_FAILED', 'no 2D context for the output canvas');
|
|
163
|
+
const p = doc.padOut;
|
|
164
|
+
context.drawImage(doc.image, -p, -p, width + 2 * p, height + 2 * p);
|
|
165
|
+
return canvas;
|
|
166
|
+
}
|
|
167
|
+
async function decodeSvg(svg) {
|
|
168
|
+
const image = new Image();
|
|
169
|
+
image.decoding = 'sync';
|
|
170
|
+
image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
|
|
171
|
+
try {
|
|
172
|
+
await image.decode();
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
fail('RASTERIZE_FAILED', `the capture did not decode as an image: ${error instanceof Error ? error.message : ''}`);
|
|
176
|
+
}
|
|
177
|
+
return image;
|
|
178
|
+
}
|
|
179
|
+
function wait(ms) {
|
|
180
|
+
return new Promise((resolve) => window.setTimeout(resolve, ms));
|
|
181
|
+
}
|
|
182
|
+
async function decodeDocuments(plan, geometry) {
|
|
183
|
+
const { packet, scale } = plan;
|
|
184
|
+
const shape = geometry === 'transform-padded' ? 'transform' : geometry;
|
|
185
|
+
const realPad = geometry === 'transform-padded' ? padFor(scale) : 0;
|
|
186
|
+
const cssFull = packet.height + stripHeight(packet.textSamples, packet.effects, packet.width);
|
|
187
|
+
const decode = async (mode, strip, padOut) => ({
|
|
188
|
+
image: await decodeSvg(svgDocument(packetXml(packet, mode, strip), packet.width, strip ? cssFull : packet.height, scale, shape, padOut)),
|
|
189
|
+
padOut,
|
|
190
|
+
});
|
|
191
|
+
const effects = packet.effects.length > 0;
|
|
192
|
+
return {
|
|
193
|
+
real: await decode('real', true, realPad),
|
|
194
|
+
magenta: plan.rasters.size ? await decode('magenta', false, realPad) : null,
|
|
195
|
+
black: plan.rasters.size ? await decode('black', false, realPad) : null,
|
|
196
|
+
unclipRoot: effects ? await decode('unclip-root', false, padFor(scale)) : null,
|
|
197
|
+
// One drawing per box: with only that box unclipped, anything else that
|
|
198
|
+
// clips (an avatar, an ellipsis, a nested box) is clipped the same way in
|
|
199
|
+
// both drawings, so no difference inside the box is legitimate.
|
|
200
|
+
unclipBoxes: effects
|
|
201
|
+
? await Promise.all(packet.effectClips.clips.map((_box, index) => decode(`unclip-box-${index}`, false, padFor(scale))))
|
|
202
|
+
: [],
|
|
203
|
+
decode: (mode) => decode(mode, false, realPad),
|
|
204
|
+
isolated: new Map(),
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
// Checks each bitmap against the shared magenta/black drawings, where every
|
|
208
|
+
// checked bitmap is replaced at once. A bitmap over or under another (a
|
|
209
|
+
// translucent canvas on a canvas) is confused there by the other one's box, so
|
|
210
|
+
// one that fails is checked again with only itself replaced.
|
|
211
|
+
async function checkAllBitmaps(plan, docs, real) {
|
|
212
|
+
if (!docs.magenta || !docs.black)
|
|
213
|
+
return null;
|
|
214
|
+
const shared = {
|
|
215
|
+
real,
|
|
216
|
+
magenta: readAndRelease(drawDocument(docs.magenta, plan.width, plan.height)),
|
|
217
|
+
black: readAndRelease(drawDocument(docs.black, plan.width, plan.height)),
|
|
218
|
+
};
|
|
219
|
+
for (const box of plan.packet.bitmaps) {
|
|
220
|
+
const bitmap = plan.rasters.get(box.id);
|
|
221
|
+
if (!bitmap)
|
|
222
|
+
continue;
|
|
223
|
+
let reason = checkBitmap(shared, box, bitmap, plan.scale, plan.webkit);
|
|
224
|
+
if (reason && plan.packet.bitmaps.length > 1) {
|
|
225
|
+
let own = docs.isolated.get(box.id);
|
|
226
|
+
if (!own) {
|
|
227
|
+
own = {
|
|
228
|
+
magenta: await docs.decode(`magenta-only-${box.id}`),
|
|
229
|
+
black: await docs.decode(`black-only-${box.id}`),
|
|
230
|
+
};
|
|
231
|
+
docs.isolated.set(box.id, own);
|
|
232
|
+
}
|
|
233
|
+
const isolated = {
|
|
234
|
+
real,
|
|
235
|
+
magenta: readAndRelease(drawDocument(own.magenta, plan.width, plan.height)),
|
|
236
|
+
black: readAndRelease(drawDocument(own.black, plan.width, plan.height)),
|
|
237
|
+
};
|
|
238
|
+
reason = checkBitmap(isolated, box, bitmap, plan.scale, plan.webkit);
|
|
239
|
+
}
|
|
240
|
+
if (reason)
|
|
241
|
+
return reason;
|
|
242
|
+
}
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
// The clipped effects, checked against the same card drawn without the clips.
|
|
246
|
+
function checkEffectClips(plan, real, docs) {
|
|
247
|
+
const { packet, scale } = plan;
|
|
248
|
+
if (packet.effectClips.unverifiable)
|
|
249
|
+
return `effect clip: ${packet.effectClips.unverifiable}`;
|
|
250
|
+
if (docs.unclipRoot) {
|
|
251
|
+
const card = {
|
|
252
|
+
x: 0,
|
|
253
|
+
y: 0,
|
|
254
|
+
width: packet.width,
|
|
255
|
+
height: packet.height,
|
|
256
|
+
radius: packet.effectClips.rootRadius,
|
|
257
|
+
};
|
|
258
|
+
const unclipped = readAndRelease(drawDocument(docs.unclipRoot, plan.width, plan.height));
|
|
259
|
+
const reason = checkUnclipped(real, unclipped, [card], scale, 'the card');
|
|
260
|
+
if (reason)
|
|
261
|
+
return reason;
|
|
262
|
+
}
|
|
263
|
+
for (const [index, doc] of docs.unclipBoxes.entries()) {
|
|
264
|
+
const unclipped = readAndRelease(drawDocument(doc, plan.width, plan.height));
|
|
265
|
+
const reason = checkUnclipped(real, unclipped, [packet.effectClips.clips[index]], scale, 'a clipped box');
|
|
266
|
+
if (reason)
|
|
267
|
+
return reason;
|
|
268
|
+
}
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
// One draw of every document, checked. Returns the drawn card on success, or
|
|
272
|
+
// why it did not match.
|
|
273
|
+
async function drawAndCheck(plan, docs) {
|
|
274
|
+
const full = drawDocument(docs.real, plan.width, plan.fullHeight);
|
|
275
|
+
const real = readRaster(full);
|
|
276
|
+
const { packet } = plan;
|
|
277
|
+
const failed = (reason) => {
|
|
278
|
+
releaseCanvas(full);
|
|
279
|
+
return { reason };
|
|
280
|
+
};
|
|
281
|
+
const stripReason = checkStrip(real, packet.width, packet.height, plan.scale, packet.textSamples, packet.effects, true);
|
|
282
|
+
if (stripReason)
|
|
283
|
+
return failed(stripReason);
|
|
284
|
+
const clipReason = checkEffectClips(plan, real, docs);
|
|
285
|
+
if (clipReason)
|
|
286
|
+
return failed(clipReason);
|
|
287
|
+
const bitmapReason = await checkAllBitmaps(plan, docs, real);
|
|
288
|
+
if (bitmapReason)
|
|
289
|
+
return failed(bitmapReason);
|
|
290
|
+
const card = document.createElement('canvas');
|
|
291
|
+
card.width = plan.width;
|
|
292
|
+
card.height = plan.height;
|
|
293
|
+
const context = Reflect.apply(natives.getContext, card, [
|
|
294
|
+
'2d',
|
|
295
|
+
]);
|
|
296
|
+
if (!context)
|
|
297
|
+
fail('RASTERIZE_FAILED', 'no 2D context for the output canvas');
|
|
298
|
+
context.drawImage(full, 0, 0, plan.width, plan.height, 0, 0, plan.width, plan.height);
|
|
299
|
+
releaseCanvas(full);
|
|
300
|
+
return { canvas: card };
|
|
301
|
+
}
|
|
302
|
+
// WebKit has been seen to paint a foreignObject's images and fonts only on a
|
|
303
|
+
// later draw of the same SVG image, so a failed check is redrawn a few times,
|
|
304
|
+
// and from a fresh decode halfway, before this geometry is given up on.
|
|
305
|
+
function stopIfAborted(signal) {
|
|
306
|
+
if (signal?.aborted)
|
|
307
|
+
fail('CAPTURE_CANCELED', 'the capture was canceled while rasterizing');
|
|
308
|
+
}
|
|
309
|
+
// A redraw is for late paint; a failure that comes back identical -- same
|
|
310
|
+
// check, same counts -- is the drawing itself, and redrawing it again only
|
|
311
|
+
// costs time.
|
|
312
|
+
async function drawVerified(plan, geometry, signal) {
|
|
313
|
+
let docs = await decodeDocuments(plan, geometry);
|
|
314
|
+
let reason = '';
|
|
315
|
+
for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {
|
|
316
|
+
stopIfAborted(signal);
|
|
317
|
+
const result = await drawAndCheck(plan, docs);
|
|
318
|
+
if ('canvas' in result)
|
|
319
|
+
return { canvas: result.canvas, attempts: attempt };
|
|
320
|
+
// A web font inside the SVG image can finish loading only after a draw
|
|
321
|
+
// or two (an unloaded unicode-range subset, a bold face): a font failure
|
|
322
|
+
// gets every redraw, however alike its results.
|
|
323
|
+
if (result.reason === reason && !result.reason.startsWith('font:'))
|
|
324
|
+
break;
|
|
325
|
+
reason = result.reason;
|
|
326
|
+
await wait(50 * 2 ** attempt);
|
|
327
|
+
if (attempt === ATTEMPTS / 2)
|
|
328
|
+
docs = await decodeDocuments(plan, geometry);
|
|
329
|
+
}
|
|
330
|
+
return `${geometry}: ${reason}`;
|
|
331
|
+
}
|
|
332
|
+
function canvasToPngBlob(canvas) {
|
|
333
|
+
return new Promise((resolve, reject) => {
|
|
334
|
+
try {
|
|
335
|
+
const done = (blob) => {
|
|
336
|
+
if (blob)
|
|
337
|
+
resolve(blob);
|
|
338
|
+
else
|
|
339
|
+
reject(new CoverCaptureError('RASTERIZE_FAILED', 'the canvas produced no PNG'));
|
|
340
|
+
};
|
|
341
|
+
Reflect.apply(natives.toBlob, canvas, [done, 'image/png']);
|
|
342
|
+
}
|
|
343
|
+
catch (error) {
|
|
344
|
+
reject(error instanceof DOMException && error.name === 'SecurityError'
|
|
345
|
+
? new CoverCaptureError('RASTERIZE_BLOCKED', 'the browser tainted the rasterized capture')
|
|
346
|
+
: new CoverCaptureError('RASTERIZE_FAILED', error instanceof Error ? error.message : String(error)));
|
|
347
|
+
}
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
/** Rasterizes a packet to a PNG data URL at cover resolution, verified against the page. */
|
|
351
|
+
export async function rasterizePacket(packet, signal) {
|
|
352
|
+
const webkit = runningInWebKit();
|
|
353
|
+
if (webkit) {
|
|
354
|
+
refuseWebKitEffects(packet.webkitEffects);
|
|
355
|
+
if (packet.unverifiedBitmaps > 0) {
|
|
356
|
+
fail('CAPTURE_UNVERIFIABLE', `webkit: ${packet.unverifiedBitmaps} image(s) or canvas(es) cannot be checked`);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
const scale = coverScale(packet.width, packet.height);
|
|
360
|
+
const width = Math.max(1, Math.round(packet.width * scale));
|
|
361
|
+
const height = Math.max(1, Math.round(packet.height * scale));
|
|
362
|
+
const plan = {
|
|
363
|
+
packet,
|
|
364
|
+
scale,
|
|
365
|
+
width,
|
|
366
|
+
height,
|
|
367
|
+
fullHeight: Math.round((packet.height + stripHeight(packet.textSamples, packet.effects, packet.width)) * scale),
|
|
368
|
+
rasters: await loadBitmapRasters(packet.bitmaps),
|
|
369
|
+
webkit,
|
|
370
|
+
};
|
|
371
|
+
const reasons = [];
|
|
372
|
+
for (const geometry of geometries()) {
|
|
373
|
+
stopIfAborted(signal);
|
|
374
|
+
const result = await drawVerified(plan, geometry, signal);
|
|
375
|
+
if (typeof result === 'string') {
|
|
376
|
+
reasons.push(result);
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
const blob = await canvasToPngBlob(result.canvas);
|
|
380
|
+
releaseCanvas(result.canvas);
|
|
381
|
+
if (blob.size > MAX_COVER_PNG_BYTES)
|
|
382
|
+
fail('COVER_TOO_LARGE', `${blob.size} bytes exceeds ${MAX_COVER_PNG_BYTES}`);
|
|
383
|
+
return {
|
|
384
|
+
dataUrl: bytesToDataUrl(new Uint8Array(await blob.arrayBuffer()), 'image/png'),
|
|
385
|
+
width,
|
|
386
|
+
height,
|
|
387
|
+
diagnostics: {
|
|
388
|
+
geometry,
|
|
389
|
+
attempts: result.attempts,
|
|
390
|
+
bitmapsChecked: plan.rasters.size,
|
|
391
|
+
fontFacesChecked: packet.textSamples.reduce((sum, sample) => sum + sample.faces, 0),
|
|
392
|
+
unverifiedBitmaps: packet.unverifiedBitmaps,
|
|
393
|
+
strippedMarks: packet.strippedMarks,
|
|
394
|
+
},
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
// A geometry that drew the card right but got an effect wrong names the real
|
|
398
|
+
// blocker, even if another geometry failed earlier on something else: the
|
|
399
|
+
// browser cannot draw that effect in a copy (Chromium draws no
|
|
400
|
+
// backdrop-filter inside an SVG image; WebKit misdraws a clipped shadow).
|
|
401
|
+
if (reasons.some((reason) => /^[a-z-]+: effect /.test(reason))) {
|
|
402
|
+
fail('EFFECT_NOT_REPRODUCIBLE', reasons.join('; '));
|
|
403
|
+
}
|
|
404
|
+
if (reasons.some((reason) => /^[a-z-]+: unverifiable: /.test(reason))) {
|
|
405
|
+
fail('CAPTURE_UNVERIFIABLE', reasons.join('; '));
|
|
406
|
+
}
|
|
407
|
+
fail('RASTERIZE_MISMATCH', reasons.join('; '));
|
|
408
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
type ResourceKind = 'image' | 'font' | 'stylesheet';
|
|
2
|
+
interface FetchedStylesheet {
|
|
3
|
+
text: string;
|
|
4
|
+
baseUrl: string;
|
|
5
|
+
}
|
|
6
|
+
export interface ResourceBudget {
|
|
7
|
+
total: number;
|
|
8
|
+
cache: Map<string, Promise<string> | string>;
|
|
9
|
+
cssCache: Map<string, Promise<FetchedStylesheet>>;
|
|
10
|
+
signal: AbortSignal;
|
|
11
|
+
}
|
|
12
|
+
export interface EmbeddedResources {
|
|
13
|
+
budget: ResourceBudget;
|
|
14
|
+
fontCss: string;
|
|
15
|
+
/** The web font families embedded in fontCss (lower-cased), for the font check. */
|
|
16
|
+
fontFamilies: string[];
|
|
17
|
+
}
|
|
18
|
+
export declare function newBudget(signal: AbortSignal): ResourceBudget;
|
|
19
|
+
export declare function bytesToDataUrl(bytes: Uint8Array, mimeType: string): string;
|
|
20
|
+
/** Where a resource may come from; an inline one is already embedded. */
|
|
21
|
+
export declare function allowedResourceUrl(rawUrl: string, kind: ResourceKind, baseUrl?: string): {
|
|
22
|
+
inline: boolean;
|
|
23
|
+
url: string;
|
|
24
|
+
};
|
|
25
|
+
/** The preloaded data: URL for a CSS value, synchronously, at the capture boundary. */
|
|
26
|
+
export declare function rewriteCssValueSynchronously(value: string, budget: ResourceBudget, label: string, property: string): string;
|
|
27
|
+
/** A CSS string literal for any text: quotes, backslashes and line breaks escaped. */
|
|
28
|
+
export declare function cssString(value: string): string;
|
|
29
|
+
/** Validates the card, then embeds every image and font it renders. */
|
|
30
|
+
export declare function preloadResources(root: Element, signal: AbortSignal): Promise<EmbeddedResources>;
|
|
31
|
+
export {};
|