@marver-design/marver 0.26.1 → 0.27.2

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 (109) hide show
  1. package/CHANGELOG.md +198 -0
  2. package/README.md +12 -4
  3. package/dist/{anchor-check-l-ny3UzH.mjs → anchor-check-gkxkPAIv.mjs} +1 -1
  4. package/dist/{board-tree-DRioF94d.mjs → board-tree-BXR8dw4b.mjs} +3 -1
  5. package/dist/{boards-CGg6piKF.mjs → boards-BHKP5yhI.mjs} +1 -1
  6. package/dist/{boards-DYG22tOe.mjs → boards-BqUqKNW8.mjs} +4 -4
  7. package/dist/{build-BDRiO_mP.mjs → build-VgNg4rr8.mjs} +8 -23
  8. package/dist/cli.mjs +45 -19
  9. package/dist/{collab-Dxg2trOK.mjs → collab-BEAcXrBb.mjs} +1 -1
  10. package/dist/{comments-BqXua-XL.mjs → comments-YEU1Zhv9.mjs} +4 -4
  11. package/dist/{context-HQ4Giw58.mjs → context-Ccjrhr1J.mjs} +3 -3
  12. package/dist/{daemon-DL6Fwq6D.mjs → daemon-Dc9AH0M3.mjs} +9 -7
  13. package/dist/detect-C0wpaePX.mjs +125 -0
  14. package/dist/dev-lock-C_FC70Mu.mjs +65 -0
  15. package/dist/dev-ri6nAlRp.mjs +1273 -0
  16. package/dist/exclusive-B1RtpeeP.mjs +150 -0
  17. package/dist/{init-D8DtrK_F.mjs → init-W0nxR1OY.mjs} +8 -6
  18. package/dist/{link-BNzLvdhI.mjs → link-CdTgn94Y.mjs} +23 -11
  19. package/dist/ls-BZ5TAtd5.mjs +38 -0
  20. package/dist/{manifest-Nl3KSVOk.mjs → manifest-aFyDmL8C.mjs} +2 -2
  21. package/dist/{marks-DyWMv_Z1.mjs → marks-BF9pNEgH.mjs} +3 -3
  22. package/dist/{marks-CKgzucHZ.mjs → marks-CnCCfAbD.mjs} +3 -3
  23. package/dist/{marver-id-gate-BjF6v4bT.mjs → marver-id-gate-D-R0hSt_.mjs} +1 -1
  24. package/dist/perf-DkAUFT6W.mjs +1319 -0
  25. package/dist/perf-jam-BaH3Lg0m.mjs +635 -0
  26. package/dist/plugin-B8UghYuF.mjs +5242 -0
  27. package/dist/{poster-BdtSKMDm.mjs → poster-BNgafWMK.mjs} +1 -1
  28. package/dist/{profile-WU9qcbIo.mjs → profile-jIS6BcAs.mjs} +1 -1
  29. package/dist/{publish-bakes-9RzRToXV.mjs → publish-bakes-38Nja78p.mjs} +3 -3
  30. package/dist/{queue-29ok5_eZ.mjs → queue-CAM_vNmX.mjs} +1 -1
  31. package/dist/recover-B8AiI29B.mjs +66 -0
  32. package/dist/{serve-C8rVheYk.mjs → serve-Dp3nHstu.mjs} +3 -3
  33. package/dist/{share--oFJ1bCI.mjs → share-Ce4tP7ji.mjs} +1 -1
  34. package/dist/{shot-XQV7HC9A.mjs → shot-CMQgMVZm.mjs} +1 -1
  35. package/dist/{shot-DQeR_Pfn.mjs → shot-Ch24tiMO.mjs} +36 -5
  36. package/dist/slots-CFNnegCc.mjs +478 -0
  37. package/dist/{sync-DKk-yT1V.mjs → sync-CQdGARJ9.mjs} +4 -3
  38. package/dist/{work-VvX_JIgl.mjs → work-Bxz-ObF3.mjs} +4 -2
  39. package/dist/{work-F5u-twpJ.mjs → work-CNhFF9pU.mjs} +5 -3
  40. package/docs/boards-and-folders.md +3 -1
  41. package/docs/jam-session.md +57 -2
  42. package/docs/performance.md +424 -0
  43. package/package.json +2 -2
  44. package/src/client/content/index.tsx +3 -0
  45. package/src/client/content/video.tsx +16 -4
  46. package/src/client/frame-host/bridge.js +22 -6
  47. package/src/client/frame-host/main.tsx +17 -5
  48. package/src/client/shell/App.tsx +188 -26
  49. package/src/client/shell/BoardList.tsx +5 -5
  50. package/src/client/shell/Comments.tsx +8 -5
  51. package/src/client/shell/ContextMenu.tsx +5 -3
  52. package/src/client/shell/JamSurface.tsx +4 -2
  53. package/src/client/shell/LockedApp.tsx +8 -5
  54. package/src/client/shell/Play.tsx +20 -10
  55. package/src/client/shell/Tip.tsx +3 -1
  56. package/src/client/shell/Toolbar.tsx +12 -1
  57. package/src/client/shell/api.ts +233 -0
  58. package/src/client/shell/app-bridge.ts +254 -0
  59. package/src/client/shell/app-perf.ts +92 -0
  60. package/src/client/shell/canvas/Canvas.tsx +141 -21
  61. package/src/client/shell/canvas/FrameNode.tsx +22 -9
  62. package/src/client/shell/canvas/admission.ts +31 -9
  63. package/src/client/shell/canvas/camera-broadcast.ts +15 -5
  64. package/src/client/shell/canvas/ctl.ts +8 -0
  65. package/src/client/shell/canvas/frame-registry.ts +28 -2
  66. package/src/client/shell/canvas/sleep.ts +60 -17
  67. package/src/client/shell/canvas/updates.ts +2 -1
  68. package/src/client/shell/comments-store.ts +12 -4
  69. package/src/client/shell/goto.ts +22 -10
  70. package/src/client/shell/inset.ts +44 -0
  71. package/src/client/shell/jam-capture.ts +41 -22
  72. package/src/client/shell/jam-keys.ts +12 -3
  73. package/src/client/shell/jam-panel.tsx +9 -3
  74. package/src/client/shell/jam-queue.ts +3 -3
  75. package/src/client/shell/jam-session.tsx +14 -8
  76. package/src/client/shell/jam-voice.ts +55 -15
  77. package/src/client/shell/legacy-links.ts +2 -2
  78. package/src/client/shell/main.tsx +18 -1
  79. package/src/client/shell/marks-ui.tsx +5 -3
  80. package/src/client/shell/marver-app.ts +21 -0
  81. package/src/client/shell/notes.ts +8 -1
  82. package/src/client/shell/perf-run-probe.ts +34 -0
  83. package/src/client/shell/perf-run.ts +70 -0
  84. package/src/client/shell/perf.ts +80 -58
  85. package/src/client/shell/recorder-core.ts +183 -0
  86. package/src/client/shell/recorder.ts +607 -0
  87. package/src/client/shell/store.ts +294 -110
  88. package/src/client/shell/styles.css +72 -15
  89. package/src/client/shell/unsaved.ts +81 -0
  90. package/src/client/shell/whiteout-probes.ts +141 -0
  91. package/src/shared/app-api.ts +205 -0
  92. package/src/shared/app-perf.ts +308 -0
  93. package/src/shared/logo-sniff.ts +86 -0
  94. package/src/shared/machine.ts +132 -0
  95. package/src/shared/perf-run.ts +177 -0
  96. package/templates/AGENTS-embedded.md +25 -4
  97. package/templates/AGENTS-studio.md +25 -4
  98. package/templates/demo/dark.tsx +1 -1
  99. package/templates/demo/welcome.tsx +1 -1
  100. package/templates/instructions/boards.md +3 -1
  101. package/templates/instructions/welcome.md +6 -3
  102. package/dist/bake-C-awKgLA.mjs +0 -786
  103. package/dist/config-Cf7EjAMf.mjs +0 -292
  104. package/dist/dev-Bw_qYWWq.mjs +0 -755
  105. package/dist/dev-lock-DWSpa6nj.mjs +0 -179
  106. package/dist/perf-C75MZ73h.mjs +0 -167
  107. package/dist/perf-DPbLGhhO.mjs +0 -49
  108. package/dist/perf-jam-BU3TVrZu.mjs +0 -239
  109. package/dist/plugin-DkGmZs_r.mjs +0 -2423
@@ -1,786 +0,0 @@
1
- import { AREA, SURFACE, pool, shotConcurrency, withBrowser } from "./shot-DQeR_Pfn.mjs";
2
- import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
3
- import { join, sep } from "node:path";
4
- import { createHash } from "node:crypto";
5
- //#region src/shared/sleep-rule.ts
6
- /** The element's own background and filter, read once BEFORE any override touches it. */
7
- function readOwn(cs) {
8
- return {
9
- img: cs.backgroundImage,
10
- color: cs.backgroundColor,
11
- size: cs.backgroundSize,
12
- pos: cs.backgroundPosition,
13
- rep: cs.backgroundRepeat,
14
- org: cs.backgroundOrigin,
15
- clip: cs.backgroundClip,
16
- filter: cs.filter
17
- };
18
- }
19
- function sleepRule(selector, o, texture) {
20
- const img = o.img === "none" ? "" : o.img + ",";
21
- const colorClip = o.clip.split(",").pop().trim() || "border-box";
22
- return selector + "{backdrop-filter:none!important;-webkit-backdrop-filter:none!important;" + (o.filter === "none" ? "filter:opacity(1)!important;" : "") + "background-color:transparent!important;background-image:" + img + "linear-gradient(" + o.color + "," + o.color + "),url(\"" + texture + "\")!important;background-size:" + (img ? o.size + "," : "") + "auto,100% 100%!important;background-position:" + (img ? o.pos + "," : "") + "0 0,0 0!important;background-repeat:" + (img ? o.rep + "," : "") + "no-repeat,no-repeat!important;background-origin:" + (img ? o.org + "," : "") + "border-box,border-box!important;background-clip:" + (img ? o.clip + "," : "") + colorClip + ",border-box!important}";
23
- }
24
- //#endregion
25
- //#region src/server/bake.ts
26
- /**
27
- * Effect compilation - what lets a hi-fi frame SLEEP on the canvas (spec 16).
28
- *
29
- * A frame at rest is its own live document. What makes a glass design unrenderable at scale is not
30
- * layout or text but its effects: every `backdrop-filter` is a compositor render surface that reads
31
- * back what is behind it on every composited frame, and under a scaled canvas the tiles behind it
32
- * re-raster on every zoom step. At rest nothing behind a glass surface changes, so its filtered
33
- * backdrop is a constant - a texture. This module computes those textures with Chrome itself, so
34
- * the pixels are the compositor's own, and CERTIFIES each one before it ships:
35
- *
36
- * 1. render the frame headless at the node's width/height/theme (DPR 2) and settle it like the
37
- * shot pipeline does, plus SVG images, running animations and a DOM-quiet window
38
- * 2. DETECT every element with a computed backdrop-filter; level overlapping elements (an element
39
- * over an earlier one bakes one level later, so its backdrop contains the earlier one's result)
40
- * 3. a WARMED, STABLE reference: one hide-and-show cycle first (tiles under the targets then sit in
41
- * the state every later capture is in), captured until two consecutive captures are identical
42
- * 4. per level: hide this level and above with opacity (a descendant can undo `visibility`), ONE
43
- * screenshot, and one filter page that cuts every crop at integer device pixels, tiles it 3x3
44
- * with mirrored copies (Chrome's backdrop blur reads only the element's own region and mirrors
45
- * at its edges) and applies the element's own filter list by CSS; one screenshot of that page,
46
- * sliced back into the textures at TEXTURE_DSF
47
- * 5. certification: apply everything, render, and diff the INSIDE of each element's rounded
48
- * shape (eroded 3 device px - a composited edge and an inline edge differ by an AA halo) against
49
- * the reference; then re-apply only what passed and certify THAT composition (a rejected
50
- * neighbour changes a backdrop); then check that no element's box moved
51
- *
52
- * The override the shell will use is the one certified here (src/shared/sleep-rule.ts):
53
- * `backdrop-filter: none` under a static `filter` (the containing block stays, the compositor layer
54
- * goes) with the texture under the element's own background layers. Layout is never touched.
55
- */
56
- const DSF = 2;
57
- /** Texture device px per CSS px. Blur is scale-tolerant: 1x matches 2x on identity at 2x zoom
58
- * (29 px > 8 of 5.18 M, none > 32) at a quarter of the memory; 0.5x fails on 30 px pills. */
59
- const TEXTURE_DSF = 1;
60
- const DEADLINE_MS = 45e3;
61
- /** The refusal for a frame with a looping animation: it rests paused, never compiled. */
62
- const LOOPING = "a looping animation - the frame rests paused, uncompiled";
63
- /** The largest frame an ask may name, in CSS px: the shot pipeline's bitmap budget at DPR 2. */
64
- const ASK_MAX = {
65
- side: Math.floor(SURFACE / DSF),
66
- area: Math.floor(AREA / 4)
67
- };
68
- const MAX_TARGETS = 200;
69
- /** One element's texture, in CSS px (its 3x3 mirrored tiling is filtered in a page of its own). */
70
- const MAX_TARGET_AREA = 4e6;
71
- const KEYS_PER_GEN = 400;
72
- /** Runs INSIDE the frame document: the effect census and the paint-order levelling. Assigns
73
- * data-mv-bake ids so later passes address elements without re-walking. */
74
- const DETECT = `(() => {
75
- const sel = (el) => {
76
- const seg = []
77
- for (let cur = el; cur && cur !== document.documentElement; cur = cur.parentElement) {
78
- if (cur.id) { seg.unshift('#' + CSS.escape(cur.id)); break }
79
- const tag = cur.tagName.toLowerCase()
80
- let n = 1
81
- for (let s = cur.previousElementSibling; s; s = s.previousElementSibling) if (s.tagName === cur.tagName) n++
82
- seg.unshift(tag + ':nth-of-type(' + n + ')')
83
- }
84
- return seg.join('>')
85
- }
86
- const glass = []
87
- for (const el of document.querySelectorAll('*')) {
88
- const cs = getComputedStyle(el)
89
- const bf = cs.backdropFilter || cs.webkitBackdropFilter
90
- if (!bf || bf === 'none') continue
91
- const r = el.getBoundingClientRect()
92
- if (r.width < 1 || r.height < 1) continue
93
- el.setAttribute('data-mv-glass', '')
94
- glass.push({ el, bf, r })
95
- }
96
- window.__mvBakeDetected = glass.length
97
- // glass inside glass: the inner element reads its ancestor's UNFILTERED backdrop (measured in
98
- // Chrome 152), which no texture on either of them reproduces - both stay live
99
- const out = []
100
- let i = 0
101
- for (const { el, bf, r } of glass) {
102
- if ((el.parentElement && el.parentElement.closest('[data-mv-glass]')) || el.querySelector('[data-mv-glass]')) continue
103
- el.setAttribute('data-mv-bake', String(i))
104
- out.push({ i: i++, sel: sel(el), rect: { x: r.x, y: r.y, w: r.width, h: r.height }, filter: bf })
105
- }
106
- for (const { el } of glass) el.removeAttribute('data-mv-glass')
107
- const level = new Array(out.length).fill(0)
108
- const hit = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
109
- for (let k = 0; k < out.length; k++) for (let j = 0; j < k; j++) if (hit(out[k].rect, out[j].rect)) level[k] = Math.max(level[k], level[j] + 1)
110
- return out.map((t, k) => ({ ...t, level: level[k] }))
111
- })()`;
112
- /** Runs inside the frame document: hide the targets at or above \`level\` (opacity, the authored
113
- * inline declaration remembered and restored exactly), show the rest, apply \`bakes\` as the
114
- * override the shell will use. */
115
- const APPLY = `((level, bakes) => {
116
- const readOwn = ${readOwn.toString()}
117
- const sleepRule = ${sleepRule.toString()}
118
- let st = document.getElementById('mv-bake-style')
119
- if (!st) { st = document.createElement('style'); st.id = 'mv-bake-style'; document.head.appendChild(st) }
120
- const rules = []
121
- // no authored transition may animate the override in: the shell installs it the same way
122
- for (const el of document.querySelectorAll('[data-mv-bake]')) el.style.setProperty('transition-property', 'none', 'important')
123
- for (const el of document.querySelectorAll('[data-mv-bake]')) {
124
- const i = el.getAttribute('data-mv-bake')
125
- const b = bakes.find((x) => String(x.i) === i)
126
- if (!b) continue
127
- // the element's OWN background, read once before any override touches it
128
- const own = el.dataset.mvOwn ? JSON.parse(el.dataset.mvOwn) : readOwn(getComputedStyle(el))
129
- if (!el.dataset.mvOwn) el.dataset.mvOwn = JSON.stringify(own)
130
- rules.push(sleepRule('[data-mv-bake="' + i + '"]', own, b.texture))
131
- }
132
- st.textContent = rules.join('\\n')
133
- for (const el of document.querySelectorAll('[data-mv-bake]')) {
134
- const i = Number(el.getAttribute('data-mv-bake'))
135
- const t = window.__mvBakeTargets.find((x) => x.i === i)
136
- if (t && t.level >= level) {
137
- if (!('mvOpacity' in el.dataset)) el.dataset.mvOpacity = JSON.stringify([el.style.getPropertyValue('opacity'), el.style.getPropertyPriority('opacity')])
138
- el.style.setProperty('opacity', '0', 'important')
139
- } else if ('mvOpacity' in el.dataset) {
140
- const [v, p] = JSON.parse(el.dataset.mvOpacity)
141
- if (v) el.style.setProperty('opacity', v, p); else el.style.removeProperty('opacity')
142
- delete el.dataset.mvOpacity
143
- }
144
- }
145
- return true
146
- })`;
147
- /** Every element's box, for the geometry guard (a lost containing block would move a fixed child). */
148
- const GEOMETRY = `Array.from(document.querySelectorAll('body *')).map((el) => { const r = el.getBoundingClientRect(); return [r.x, r.y, r.width, r.height] })`;
149
- const PAINTED = `new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(true))))`;
150
- /** The filter page: ONE screenshot of the level comes in; every element's crop is cut from it in-page
151
- * at integer device pixels, tiled 3x3 with mirrored copies, filtered by CSS with the element's own
152
- * filter list and clipped to its box - stacked so one screenshot yields every texture. */
153
- function filterPage(full, items, dsf, tex) {
154
- return `<!doctype html><html><head><meta charset=utf-8><style>html,body{margin:0;background:transparent}.clip{overflow:hidden;position:absolute;left:0}canvas{position:absolute;display:block}</style></head><body>
155
- <script>
156
- const items = ${JSON.stringify(items)}, dsf = ${dsf}, tex = ${tex}
157
- const img = new Image()
158
- img.onload = () => {
159
- let top = 0
160
- for (const it of items) {
161
- const sx = Math.round(it.x * dsf), sy = Math.round(it.y * dsf), sw = Math.round(it.w * dsf), sh = Math.round(it.h * dsf)
162
- const cw = it.w, ch = it.h
163
- const tw = Math.max(1, Math.round(cw * tex)), th = Math.max(1, Math.round(ch * tex))
164
- const clip = document.createElement('div'); clip.className = 'clip'; clip.id = 'c' + it.i
165
- clip.style.top = top + 'px'; clip.style.width = cw + 'px'; clip.style.height = ch + 'px'
166
- clip.dataset.box = [Math.round(top * tex), tw, th].join(',')
167
- const c = document.createElement('canvas'); c.width = 3 * tw; c.height = 3 * th
168
- c.style.left = -cw + 'px'; c.style.top = -ch + 'px'; c.style.width = (3 * cw) + 'px'; c.style.height = (3 * ch) + 'px'; c.style.filter = it.filter
169
- const g = c.getContext('2d')
170
- for (let ty = 0; ty < 3; ty++) for (let tx = 0; tx < 3; tx++) {
171
- g.save(); g.translate(tx * tw, ty * th)
172
- const fx = tx === 1 ? 1 : -1, fy = ty === 1 ? 1 : -1
173
- g.translate(fx < 0 ? tw : 0, fy < 0 ? th : 0); g.scale(fx, fy)
174
- g.drawImage(img, sx, sy, sw, sh, 0, 0, tw, th); g.restore()
175
- }
176
- clip.appendChild(c); document.body.appendChild(clip)
177
- top += Math.ceil(ch) + 8
178
- }
179
- document.body.style.height = top + 'px'
180
- window.__mvReady = true
181
- }
182
- img.src = ${JSON.stringify(full)}
183
- <\/script></body></html>`;
184
- }
185
- const SLICE = `((shot) => new Promise((res) => { const im = new Image(); im.onload = () => {
186
- const out = {}
187
- for (const clip of document.querySelectorAll('.clip')) {
188
- const [y, w, h] = clip.dataset.box.split(',').map(Number)
189
- const c = document.createElement('canvas'); c.width = w; c.height = h
190
- c.getContext('2d').drawImage(im, 0, y, w, h, 0, 0, w, h)
191
- out[clip.id.slice(1)] = c.toDataURL('image/png')
192
- }
193
- res(out)
194
- }; im.src = 'data:image/png;base64,' + shot }))`;
195
- /** Runs in the frame page: are two captures the same picture within GPU dither (no channel differs by more than 2)? */
196
- const NEAR = `((a, b) => (async () => {
197
- const load = (d) => new Promise((r) => { const im = new Image(); im.onload = () => r(im); im.src = 'data:image/png;base64,' + d })
198
- const [ia, ib] = await Promise.all([load(a), load(b)])
199
- const px = (im) => { const c = document.createElement('canvas'); c.width = im.width; c.height = im.height; const g = c.getContext('2d', { willReadFrequently: true }); g.drawImage(im, 0, 0); return g.getImageData(0, 0, c.width, c.height).data }
200
- const A = px(ia), B = px(ib)
201
- if (A.length !== B.length) return false
202
- for (let i = 0; i < A.length; i++) if (Math.abs(A[i] - B[i]) > 2) return false
203
- return true
204
- })())`;
205
- /** Runs in the frame page: diff \`baked\` against \`reference\` inside each target's rounded shape,
206
- * and over the rest of the frame - an override may not change one pixel outside the boxes it owns. */
207
- const CERTIFY = `((reference, baked, rects, width) => (async () => {
208
- const load = (d) => new Promise((r) => { const im = new Image(); im.onload = () => r(im); im.src = 'data:image/png;base64,' + d })
209
- const [ia, ib] = await Promise.all([load(reference), load(baked)])
210
- const px = (im) => { const c = document.createElement('canvas'); c.width = im.width; c.height = im.height; const g = c.getContext('2d', { willReadFrequently: true }); g.drawImage(im, 0, 0); return { d: g.getImageData(0, 0, c.width, c.height).data, w: c.width, h: c.height } }
211
- const A = px(ia), B = px(ib), k = A.w / width, E = 3
212
- const owned = new Uint8Array(A.w * A.h)
213
- const verdicts = rects.map((t) => {
214
- const x0 = Math.max(0, Math.floor(t.rect.x * k) + E), y0 = Math.max(0, Math.floor(t.rect.y * k) + E)
215
- const x1 = Math.min(A.w, Math.ceil((t.rect.x + t.rect.w) * k) - E), y1 = Math.min(A.h, Math.ceil((t.rect.y + t.rect.h) * k) - E)
216
- const el = document.querySelector(t.sel); const cs = el ? getComputedStyle(el) : null
217
- const rad = (v) => Math.max(0, Math.min(parseFloat(v) || 0, Math.min(t.rect.w, t.rect.h) / 2) * k - E)
218
- const R = cs ? [rad(cs.borderTopLeftRadius), rad(cs.borderTopRightRadius), rad(cs.borderBottomRightRadius), rad(cs.borderBottomLeftRadius)] : [0, 0, 0, 0]
219
- const inside = (x, y) => {
220
- const cx = [x0 + R[0], x1 - R[1], x1 - R[2], x0 + R[3]], cy = [y0 + R[0], y0 + R[1], y1 - R[2], y1 - R[3]]
221
- const c = x < x0 + R[0] && y < y0 + R[0] ? 0 : x >= x1 - R[1] && y < y0 + R[1] ? 1 : x >= x1 - R[2] && y >= y1 - R[2] ? 2 : x < x0 + R[3] && y >= y1 - R[3] ? 3 : -1
222
- if (c < 0) return true
223
- const dx = x + 0.5 - cx[c], dy = y + 0.5 - cy[c]
224
- return dx * dx + dy * dy <= R[c] * R[c]
225
- }
226
- // the perimeter - the box minus the eroded shape - is where a composited edge and an inline
227
- // edge differ by an anti-aliasing halo; a tint painted into a transparent border shows there
228
- // as a solid band, so it has its own, looser gate
229
- const X0 = Math.max(0, Math.floor(t.rect.x * k)), Y0 = Math.max(0, Math.floor(t.rect.y * k))
230
- const X1 = Math.min(A.w, Math.ceil((t.rect.x + t.rect.w) * k)), Y1 = Math.min(A.h, Math.ceil((t.rect.y + t.rect.h) * k))
231
- let maxErr = 0, bad = 0, n = 0, ringBad = 0, ringN = 0
232
- for (let y = Y0; y < Y1; y++) for (let x = X0; x < X1; x++) {
233
- owned[y * A.w + x] = 1
234
- const i = (y * A.w + x) * 4
235
- const d = Math.max(Math.abs(A.d[i] - B.d[i]), Math.abs(A.d[i+1] - B.d[i+1]), Math.abs(A.d[i+2] - B.d[i+2]))
236
- if (x >= x0 && x < x1 && y >= y0 && y < y1 && inside(x, y)) { if (d > maxErr) maxErr = d; if (d > 8) bad++; n++ }
237
- else { if (d > 48) ringBad++; ringN++ }
238
- }
239
- return { maxErr, bad, n, ringBad, ringN }
240
- })
241
- // outside every box: a changed pixel here is an anti-aliased edge next to a former layer (sparse,
242
- // a few per block) or a real change of paint (a blob) - counted per 16x16 device-pixel block
243
- const cols = Math.ceil(A.w / 16), blocks = new Uint16Array(cols * Math.ceil(A.h / 16))
244
- let maxErr = 0, bad = 0, gt32 = 0, n = 0, blockMax = 0
245
- for (let p = 0; p < owned.length; p++) {
246
- if (owned[p]) continue
247
- const i = p * 4
248
- const d = Math.max(Math.abs(A.d[i] - B.d[i]), Math.abs(A.d[i+1] - B.d[i+1]), Math.abs(A.d[i+2] - B.d[i+2]))
249
- if (d > maxErr) maxErr = d; if (d > 8) bad++; n++
250
- if (d > 32) { gt32++; const b = ((p / A.w) >> 4) * cols + ((p % A.w) >> 4); if (++blocks[b] > blockMax) blockMax = blocks[b] }
251
- }
252
- return { verdicts, outside: { maxErr, bad, gt32, n, blockMax } }
253
- })())`;
254
- const passes = (v) => !!v && v.n >= 64 && v.maxErr <= 32 && v.bad <= v.n * .005 && v.ringBad <= v.ringN * .05;
255
- /** The frame outside the boxes: at most 0.05 % of its pixels beyond 32 levels and no 16x16 block
256
- * more than a quarter changed (measured: 154 of 2.5 M, 22 per block at worst, on the largest real
257
- * frame; a 60x40 CSS px blob fills its blocks). */
258
- const untouched = (o) => !!o && o.gt32 <= o.n * 5e-4 && o.blockMax <= 64;
259
- /** Compile one frame inside a browser the caller owns. */
260
- async function bakeIn(b, opts) {
261
- const { url, width, height } = opts;
262
- const t0 = Date.now();
263
- const me = {};
264
- let targetId;
265
- const deadline = setTimeout(() => b.abort(me, "the bake timed out"), DEADLINE_MS);
266
- const closeTarget = async (id) => {
267
- let t;
268
- await Promise.race([b.send("Target.closeTarget", { targetId: id }).catch(() => {}), new Promise((r) => {
269
- t = setTimeout(r, 2e3);
270
- })]);
271
- clearTimeout(t);
272
- };
273
- try {
274
- targetId = (await b.send("Target.createTarget", { url: "about:blank" }, void 0, me)).targetId;
275
- const sessionId = (await b.send("Target.attachToTarget", {
276
- targetId,
277
- flatten: true
278
- }, void 0, me)).sessionId;
279
- const send = (m, p = {}, sid = sessionId) => b.send(m, p, sid, me);
280
- const ev = async (expression, awaitPromise = false) => (await send("Runtime.evaluate", {
281
- expression,
282
- returnByValue: true,
283
- awaitPromise
284
- })).result?.value;
285
- const wait = (ms) => new Promise((r) => setTimeout(r, ms));
286
- const capture = async () => (await send("Page.captureScreenshot", {
287
- format: "png",
288
- captureBeyondViewport: true,
289
- clip: {
290
- x: 0,
291
- y: 0,
292
- width,
293
- height,
294
- scale: 1
295
- }
296
- })).data;
297
- await send("Emulation.setDeviceMetricsOverride", {
298
- width,
299
- height,
300
- deviceScaleFactor: DSF,
301
- mobile: false
302
- });
303
- await send("Page.enable");
304
- await send("Runtime.enable");
305
- const nav = await send("Page.navigate", { url });
306
- if (nav?.errorText && nav.errorText !== "net::ERR_ABORTED") return {
307
- ok: false,
308
- error: `could not load the frame (${nav.errorText})`
309
- };
310
- const readyBy = Date.now() + 3e4;
311
- let rendered = false;
312
- while (!rendered && Date.now() < readyBy) {
313
- rendered = !!await ev(`(() => { const el = document.getElementById('root') ?? document.body; return !!el && el.childElementCount > 0 && document.readyState !== 'loading' })()`);
314
- if (!rendered) await wait(100);
315
- }
316
- if (!rendered) return {
317
- ok: false,
318
- error: "the frame never rendered"
319
- };
320
- await ev(`document.fonts.ready.then(() => true)`, true);
321
- const unsettled = await ev(`new Promise((r) => { const t = Date.now(); const tick = () => {
322
- const H = innerHeight, W = innerWidth
323
- let pending = 0
324
- if (typeof window.__mvLodBusy === 'function' && window.__mvLodBusy() > 0) pending++
325
- if (typeof window.__mvPosterBusy === 'function' && window.__mvPosterBusy() > 0) pending++
326
- for (const im of document.images) { if (im.complete) continue; const b = im.getBoundingClientRect(); if (b.bottom < 0 || b.top > H || b.right < 0 || b.left > W) continue; pending++ }
327
- for (const c of document.querySelectorAll('.mv-chart')) if (!c.querySelector('svg, canvas')) pending++
328
- for (const d of document.querySelectorAll('.mv-diagram')) if (!d.querySelector('.mv-diagram-svg svg, .mv-diagram-err')) pending++
329
- if (!pending || Date.now() - t > 6000) r(pending); else setTimeout(tick, 60) }; tick() })`, true);
330
- if (unsettled) return {
331
- ok: false,
332
- error: `the frame did not settle (${unsettled} image(s) or chart(s) still loading)`
333
- };
334
- await ev(`Promise.all(Array.from(document.querySelectorAll('image')).map((el) => { const href = el.getAttribute('href') || el.getAttribute('xlink:href'); if (!href) return 1; const im = new Image(); im.src = new URL(href, location.href).href; return im.decode().catch(() => 1) })).then(() => true)`, true);
335
- if (await ev(`document.getAnimations().some((a) => { const t = a.effect && a.effect.getComputedTiming(); return !!t && t.iterations === Infinity && a.playState === 'running' })`)) return {
336
- ok: false,
337
- error: LOOPING
338
- };
339
- await ev(`Promise.race([Promise.all(document.getAnimations().map((a) => a.finished.catch(() => 1))), new Promise((r) => setTimeout(r, 5000))]).then(() => true)`, true);
340
- await ev(`new Promise((resolve) => { let timer = 0; const done = () => { mo.disconnect(); resolve(true) }; const mo = new MutationObserver(() => { clearTimeout(timer); timer = setTimeout(done, 250) }); mo.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true }); timer = setTimeout(done, 250); setTimeout(done, 3000) })`, true);
341
- await ev(PAINTED, true);
342
- const err = await ev(`window.__mvFrameError || ''`);
343
- if (err) return {
344
- ok: false,
345
- error: `the frame rendered an error - ${err}`
346
- };
347
- const targets = await ev(`(window.__mvBakeTargets = ${DETECT})`);
348
- const effects = Number(await ev("window.__mvBakeDetected")) || 0;
349
- if (!targets?.length) return {
350
- ok: true,
351
- targets: [],
352
- levels: 0,
353
- rejected: 0,
354
- ms: Date.now() - t0,
355
- effects
356
- };
357
- if (targets.length > MAX_TARGETS) return {
358
- ok: false,
359
- error: `too many effects to compile (${targets.length})`
360
- };
361
- if (targets.some((t) => t.rect.w * t.rect.h > MAX_TARGET_AREA)) return {
362
- ok: false,
363
- error: "an effect larger than the texture budget"
364
- };
365
- const levels = Math.max(...targets.map((t) => t.level)) + 1;
366
- const geometryBefore = await ev(GEOMETRY);
367
- await ev(`${APPLY}(0, [])`);
368
- await ev(PAINTED, true);
369
- await ev(`${APPLY}(${levels}, [])`);
370
- await ev(PAINTED, true);
371
- await wait(300);
372
- let reference = await capture(), stable = false;
373
- let previous = "";
374
- for (let i = 0; i < 8; i++) {
375
- await wait(400);
376
- const again = await capture();
377
- if (again === reference || await ev(`${NEAR}(${JSON.stringify(reference)}, ${JSON.stringify(again)})`, true)) {
378
- stable = true;
379
- break;
380
- }
381
- previous = reference;
382
- reference = again;
383
- }
384
- if (!stable) {
385
- if (process.env.MV_BAKE_DEBUG) {
386
- mkdirSync(process.env.MV_BAKE_DEBUG, { recursive: true });
387
- writeFileSync(join(process.env.MV_BAKE_DEBUG, `unstable-a-${Date.now()}.png`), Buffer.from(previous, "base64"));
388
- writeFileSync(join(process.env.MV_BAKE_DEBUG, `unstable-b-${Date.now()}.png`), Buffer.from(reference, "base64"));
389
- }
390
- return {
391
- ok: false,
392
- error: "the frame never stopped changing - nothing to certify against"
393
- };
394
- }
395
- const bakes = [];
396
- const done = /* @__PURE__ */ new Map();
397
- for (let level = 0; level < levels; level++) {
398
- await ev(`${APPLY}(${level}, ${JSON.stringify(bakes)})`);
399
- await ev(PAINTED, true);
400
- const mine = targets.filter((t) => t.level === level);
401
- const full = await capture();
402
- const items = mine.map((t) => ({
403
- i: t.i,
404
- x: t.rect.x,
405
- y: t.rect.y,
406
- w: t.rect.w,
407
- h: t.rect.h,
408
- filter: t.filter
409
- }));
410
- const { targetId: ft } = await b.send("Target.createTarget", { url: "about:blank" }, void 0, me);
411
- try {
412
- const { sessionId: fs } = await b.send("Target.attachToTarget", {
413
- targetId: ft,
414
- flatten: true
415
- }, void 0, me);
416
- const totalH = items.reduce((a, c) => a + Math.ceil(c.h) + 9, 0);
417
- await b.send("Emulation.setDeviceMetricsOverride", {
418
- width: Math.ceil(Math.max(...items.map((c) => c.w))),
419
- height: Math.min(16e3, totalH),
420
- deviceScaleFactor: TEXTURE_DSF,
421
- mobile: false
422
- }, fs, me);
423
- await b.send("Page.enable", {}, fs, me);
424
- const { frameTree } = await b.send("Page.getFrameTree", {}, fs, me);
425
- await b.send("Page.setDocumentContent", {
426
- frameId: frameTree.frame.id,
427
- html: filterPage(`data:image/png;base64,${full}`, items, DSF, TEXTURE_DSF)
428
- }, fs, me);
429
- await b.send("Runtime.evaluate", {
430
- expression: `new Promise((r) => { const t = () => window.__mvReady ? requestAnimationFrame(() => requestAnimationFrame(() => r(true))) : setTimeout(t, 20); t() })`,
431
- awaitPromise: true,
432
- returnByValue: true
433
- }, fs, me);
434
- const fshot = (await b.send("Page.captureScreenshot", {
435
- format: "png",
436
- captureBeyondViewport: true
437
- }, fs, me)).data;
438
- const textures = (await b.send("Runtime.evaluate", {
439
- expression: `${SLICE}(${JSON.stringify(fshot)})`,
440
- awaitPromise: true,
441
- returnByValue: true
442
- }, fs, me)).result.value;
443
- for (const t of mine) {
444
- const texture = textures[String(t.i)];
445
- if (!texture) continue;
446
- bakes.push({
447
- i: t.i,
448
- texture
449
- });
450
- done.set(t.i, {
451
- sel: t.sel,
452
- rect: t.rect,
453
- filter: t.filter,
454
- level,
455
- texture,
456
- verified: false,
457
- maxErr: 255,
458
- bad: -1
459
- });
460
- }
461
- } finally {
462
- await closeTarget(ft);
463
- }
464
- }
465
- const certify = async (set) => {
466
- await ev(`${APPLY}(${levels}, ${JSON.stringify(set)})`);
467
- await ev(PAINTED, true);
468
- const baked = await capture();
469
- if (process.env.MV_BAKE_DEBUG) {
470
- const d = join(process.env.MV_BAKE_DEBUG, new URL(url).pathname.replace(/[^\w.-]+/g, "_"));
471
- mkdirSync(d, { recursive: true });
472
- writeFileSync(join(d, "reference.png"), Buffer.from(reference, "base64"));
473
- writeFileSync(join(d, `baked-${set.length}.png`), Buffer.from(baked, "base64"));
474
- }
475
- const rects = set.map((s) => done.get(s.i)).map((t) => ({
476
- sel: t.sel,
477
- rect: t.rect
478
- }));
479
- return await ev(`${CERTIFY}(${JSON.stringify(reference)}, ${JSON.stringify(baked)}, ${JSON.stringify(rects)}, ${width})`, true);
480
- };
481
- let set = bakes, settled = false, outside;
482
- for (let round = 0; set.length && round <= levels + 1 && !settled; round++) {
483
- const { verdicts, outside: o } = await certify(set);
484
- outside = o;
485
- set.forEach((s, k) => {
486
- const t = done.get(s.i);
487
- t.verified = passes(verdicts[k]);
488
- t.maxErr = verdicts[k]?.maxErr ?? 255;
489
- t.bad = verdicts[k]?.bad ?? -1;
490
- });
491
- const next = set.filter((s) => done.get(s.i).verified);
492
- settled = next.length === set.length;
493
- set = next;
494
- }
495
- if (settled && set.length && !untouched(outside)) settled = false;
496
- if (!settled) for (const s of set) done.get(s.i).verified = false;
497
- const geometryAfter = await ev(GEOMETRY);
498
- if (geometryBefore.length !== geometryAfter.length || geometryBefore.some((r, k) => r.some((v, j) => Math.abs(v - geometryAfter[k][j]) > .01))) for (const t of done.values()) t.verified = false;
499
- const out = [...done.values()];
500
- return {
501
- ok: true,
502
- targets: out,
503
- levels,
504
- rejected: out.filter((t) => !t.verified).length,
505
- ms: Date.now() - t0,
506
- outside,
507
- effects
508
- };
509
- } catch (err) {
510
- return {
511
- ok: false,
512
- error: err.message
513
- };
514
- } finally {
515
- clearTimeout(deadline);
516
- b.abort(me, "the bake finished");
517
- if (targetId && !b.dead) await closeTarget(targetId);
518
- }
519
- }
520
- /** Where a compiled frame lives on disk: design/.local/bakes/<generation>/<key>/. The generation
521
- * is the dev server's source generation (bumped on any watched change), so a stale bake can never
522
- * be served after an edit; older generations are removed as new ones appear. */
523
- function bakeKey(ask) {
524
- return createHash("sha1").update(`${ask.frame}|${ask.theme}|${Math.round(ask.w)}|${Math.round(ask.h)}`).digest("hex").slice(0, 16);
525
- }
526
- function cacheDir(root, gen, key) {
527
- return join(root, "design", ".local", "bakes", String(gen), key);
528
- }
529
- /** The cache lives INSIDE the project: a `bakes` directory that resolves elsewhere (a symlink) is
530
- * never read, written or pruned. */
531
- function cacheInside(root) {
532
- const base = join(root, "design", ".local", "bakes");
533
- if (!existsSync(base)) return true;
534
- try {
535
- return realpathSync(base).startsWith(realpathSync(root) + sep);
536
- } catch {
537
- return false;
538
- }
539
- }
540
- function readCached(root, gen, ask, urlBase) {
541
- const key = bakeKey(ask);
542
- const dir = cacheDir(root, gen, key);
543
- try {
544
- const meta = JSON.parse(readFileSync(join(dir, "bake.json"), "utf8"));
545
- try {
546
- const now = /* @__PURE__ */ new Date();
547
- utimesSync(dir, now, now);
548
- } catch {}
549
- return {
550
- ...ask,
551
- ok: true,
552
- targets: meta.targets.map((t) => ({
553
- ...t,
554
- texture: t.verified ? `${urlBase}/${gen}/${key}/${t.texture}` : ""
555
- })),
556
- levels: meta.levels,
557
- rejected: meta.rejected,
558
- ms: 0
559
- };
560
- } catch {
561
- return null;
562
- }
563
- }
564
- function writeCached(root, gen, ask, r, urlBase, protect) {
565
- const key = bakeKey(ask);
566
- const dir = cacheDir(root, gen, key);
567
- const gdir = join(root, "design", ".local", "bakes", String(gen));
568
- mkdirSync(gdir, { recursive: true });
569
- if (!existsSync(join(gdir, "owner"))) writeFileSync(join(gdir, "owner"), String(process.pid));
570
- try {
571
- const names = readdirSync(gdir).filter((n) => !n.includes(".tmp-") && n !== key && n !== "owner" && !protect.has(n));
572
- if (names.length >= KEYS_PER_GEN) names.map((n) => ({
573
- n,
574
- t: statSync(join(gdir, n)).mtimeMs
575
- })).sort((a, b) => a.t - b.t).slice(0, names.length - KEYS_PER_GEN + 1).forEach(({ n }) => rmSync(join(gdir, n), {
576
- recursive: true,
577
- force: true
578
- }));
579
- } catch {}
580
- const tmp = `${dir}.tmp-${process.pid}`;
581
- rmSync(tmp, {
582
- recursive: true,
583
- force: true
584
- });
585
- mkdirSync(tmp, { recursive: true });
586
- const targets = r.targets.map((t, i) => {
587
- if (!t.verified) return {
588
- ...t,
589
- texture: ""
590
- };
591
- const name = `${i}.png`;
592
- writeFileSync(join(tmp, name), Buffer.from(t.texture.slice(t.texture.indexOf(",") + 1), "base64"));
593
- return {
594
- ...t,
595
- texture: name
596
- };
597
- });
598
- writeFileSync(join(tmp, "bake.json"), JSON.stringify({
599
- targets,
600
- levels: r.levels,
601
- rejected: r.rejected,
602
- ms: r.ms,
603
- outside: r.outside
604
- }));
605
- rmSync(dir, {
606
- recursive: true,
607
- force: true
608
- });
609
- try {
610
- renameSync(tmp, dir);
611
- } catch (e) {
612
- rmSync(tmp, {
613
- recursive: true,
614
- force: true
615
- });
616
- throw new Error(`could not write the compiled frame: ${e.message}`);
617
- }
618
- return {
619
- ...ask,
620
- ok: true,
621
- targets: targets.map((t) => ({
622
- ...t,
623
- texture: t.verified ? `${urlBase}/${gen}/${key}/${t.texture}` : ""
624
- })),
625
- levels: r.levels,
626
- rejected: r.rejected,
627
- ms: r.ms
628
- };
629
- }
630
- const alive = (pid) => {
631
- try {
632
- process.kill(pid, 0);
633
- return true;
634
- } catch (e) {
635
- return e.code === "EPERM";
636
- }
637
- };
638
- /** Drop every generation but the current one and those another live server owns (called at start
639
- * and when the generation bumps). */
640
- function pruneBakes(root, keep) {
641
- const base = join(root, "design", ".local", "bakes");
642
- if (!existsSync(base) || !cacheInside(root)) return;
643
- try {
644
- for (const name of readdirSync(base)) {
645
- if (name === String(keep)) continue;
646
- let owner = 0;
647
- try {
648
- owner = Number(readFileSync(join(base, name, "owner"), "utf8"));
649
- } catch {}
650
- if (owner && owner !== process.pid && alive(owner)) continue;
651
- rmSync(join(base, name), {
652
- recursive: true,
653
- force: true
654
- });
655
- }
656
- } catch {}
657
- }
658
- /** Compiles in flight, by generation and key: identical asks - inside one request or across
659
- * concurrent ones - share one compile. */
660
- const inflight = /* @__PURE__ */ new Map();
661
- /** Compiles that FAILED for the frame's own reasons (it loops, never stops changing, never settles,
662
- * timed out, has too many effects), by generation and key, so it is answered at once from memory
663
- * instead of being compiled again on every rest. The generation is in the key: an edit retries it.
664
- * Only these are kept - anything else (the source moved mid-compile, the browser or its pipe died,
665
- * a cache write failed) says nothing about the frame and is tried again. */
666
- const failed = /* @__PURE__ */ new Map();
667
- const FAILED_MAX = 2e3;
668
- const ofTheFrame = (error) => error === "a looping animation - the frame rests paused, uncompiled" || /^the frame (never stopped changing|did not settle|never rendered|rendered an error)|^the bake timed out$|^too many effects|^an effect larger than/.test(error);
669
- /** Compile many frames as ONE operation (one browser, `shotConcurrency()` at a time), the cache
670
- * first. `urlFor(ask)` gives the frame's own URL; `urlBase` is where textures are served from;
671
- * `live()` is the source generation NOW - a compile the source outran is not published. */
672
- async function bakeBatch(opts) {
673
- const { root, gen, asks, urlFor, urlBase, live, log, waitMs } = opts;
674
- if (!cacheInside(root)) return asks.map((ask) => ({
675
- ...ask,
676
- ok: false,
677
- error: "design/.local/bakes resolves outside the project"
678
- }));
679
- const failedKey = (ask) => `${root}|${gen}|${bakeKey(ask)}`;
680
- const answers = asks.map((ask) => {
681
- const error = failed.get(failedKey(ask));
682
- return error !== void 0 ? {
683
- ...ask,
684
- ok: false,
685
- error
686
- } : readCached(root, gen, ask, urlBase);
687
- });
688
- const protect = new Set(asks.map(bakeKey));
689
- const misses = /* @__PURE__ */ new Map();
690
- asks.forEach((ask, i) => {
691
- if (answers[i]) return;
692
- const k = `${root}|${gen}|${bakeKey(ask)}`;
693
- const m = misses.get(k);
694
- if (m) m.at.push(i);
695
- else misses.set(k, {
696
- ask,
697
- at: [i]
698
- });
699
- });
700
- const mine = [];
701
- const waits = [...misses.entries()].map(([k, m]) => {
702
- let p = inflight.get(k);
703
- if (!p) {
704
- p = new Promise((resolve) => mine.push({
705
- ask: m.ask,
706
- resolve,
707
- done: false
708
- }));
709
- inflight.set(k, p);
710
- p.then(() => inflight.delete(k));
711
- }
712
- return p.then((a) => {
713
- for (const i of m.at) answers[i] = {
714
- ...a,
715
- ...m.ask
716
- };
717
- });
718
- });
719
- async function compile() {
720
- const settle = (job, a) => {
721
- job.done = true;
722
- job.resolve(a);
723
- };
724
- try {
725
- await withBrowser("shot", (b) => pool(shotConcurrency(), mine, async (job) => {
726
- const cached = readCached(root, gen, job.ask, urlBase);
727
- if (cached) return settle(job, cached);
728
- const r = await bakeIn(b, {
729
- url: urlFor(job.ask),
730
- width: Math.round(job.ask.w),
731
- height: Math.round(job.ask.h)
732
- }).catch((e) => ({
733
- ok: false,
734
- error: e.message
735
- }));
736
- if (live && live() !== gen) return settle(job, {
737
- ...job.ask,
738
- ok: false,
739
- error: "the source changed during the compile"
740
- });
741
- let a;
742
- try {
743
- a = r.ok ? writeCached(root, gen, job.ask, r, urlBase, protect) : {
744
- ...job.ask,
745
- ...r
746
- };
747
- } catch (e) {
748
- a = {
749
- ...job.ask,
750
- ok: false,
751
- error: e.message
752
- };
753
- }
754
- if (!a.ok && ofTheFrame(a.error)) {
755
- if (failed.size >= FAILED_MAX) failed.clear();
756
- failed.set(failedKey(job.ask), a.error);
757
- }
758
- log?.(a);
759
- settle(job, a);
760
- }));
761
- } catch (e) {
762
- for (const job of mine) if (!job.done) settle(job, {
763
- ...job.ask,
764
- ok: false,
765
- error: e.message
766
- });
767
- }
768
- }
769
- const all = (mine.length ? compile() : Promise.resolve()).then(() => Promise.all(waits));
770
- if (waitMs === void 0) {
771
- await all;
772
- return answers;
773
- }
774
- let timer;
775
- await Promise.race([all, new Promise((r) => {
776
- timer = setTimeout(r, waitMs);
777
- })]);
778
- clearTimeout(timer);
779
- return answers.map((a, i) => a ?? {
780
- ...asks[i],
781
- ok: false,
782
- error: "compiling - ask again"
783
- });
784
- }
785
- //#endregion
786
- export { ASK_MAX, bakeBatch, pruneBakes };