shapewall 0.0.0-stage → 0.2.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 (304) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/Dockerfile.agent +45 -0
  3. package/LICENSE +202 -0
  4. package/NOTICE +12 -0
  5. package/README.md +651 -2
  6. package/THIRD_PARTY.md +165 -0
  7. package/bin/shapewall.js +29 -0
  8. package/dist/agent/package-lock.json +8384 -0
  9. package/dist/client/assets/BoardChat-D5SFd8HE.js +28 -0
  10. package/dist/client/assets/BuzzDialog-HWXBy52W.js +1 -0
  11. package/dist/client/assets/ChecksPanel-DTdImWoD.js +1 -0
  12. package/dist/client/assets/History-CEv6b-av.js +1 -0
  13. package/dist/client/assets/LocalSettings-C4vriEVQ.js +1 -0
  14. package/dist/client/assets/Management-DCfhcEUY.js +1 -0
  15. package/dist/client/assets/QuickConnect-DQGgUsl1.js +1 -0
  16. package/dist/client/assets/ShareDialog-C_plIto0.js +2 -0
  17. package/dist/client/assets/app-update-dialog-2hPz_N9G.js +1 -0
  18. package/dist/client/assets/circle-x-BZMPi8Zf.js +1 -0
  19. package/dist/client/assets/index-ByQRKVit.css +2 -0
  20. package/dist/client/assets/index-DweQ8Qtu.js +29 -0
  21. package/dist/client/assets/refresh-cw-CRow0Nbq.js +1 -0
  22. package/dist/client/assets/runtime-Bft6x_6E.js +4 -0
  23. package/dist/client/assets/square-A8EnIYLR.js +1 -0
  24. package/dist/client/assets/tts-dist-DYlBQmwG.js +18 -0
  25. package/dist/client/assets/tts-en-g2p-BPUtBFGG.js +1 -0
  26. package/dist/client/assets/tts-ort-wasm-simd-threaded-qh98TCA_.wasm +0 -0
  27. package/dist/client/assets/tts-ort.wasm.bundle.min-rEkcs_ow.js +12 -0
  28. package/dist/client/assets/tts-rolldown-runtime-D8NudN84.js +1 -0
  29. package/dist/client/assets/tts-spacy-en-tokenizer-6SNMl--A.json +1 -0
  30. package/dist/client/assets/tts-tts.worker-Bzm6aWbv.js +1 -0
  31. package/dist/client/assets/tts-us_gold-DcjeNMH1.json +92589 -0
  32. package/dist/client/assets/tts-us_silver-C964mEB5.json +93363 -0
  33. package/dist/client/assets/ui-CLbws0rx.js +41 -0
  34. package/dist/client/build-info.json +1 -0
  35. package/dist/client/favicon.svg +7 -0
  36. package/dist/client/icons/apple-touch-icon.png +0 -0
  37. package/dist/client/icons/icon-192.png +0 -0
  38. package/dist/client/icons/icon-512.png +0 -0
  39. package/dist/client/icons/maskable-512.png +0 -0
  40. package/dist/client/index.html +25 -0
  41. package/dist/client/manifest.webmanifest +15 -0
  42. package/dist/client/sw.js +53 -0
  43. package/dist/client/theme-boot.js +27 -0
  44. package/dist/console/assets/LocalAccountsApp-BQCcmj3x.js +1 -0
  45. package/dist/console/assets/LocalConsole-Bb2FUDs7.js +1 -0
  46. package/dist/console/assets/app-update-dialog-DIeYepLZ.js +1 -0
  47. package/dist/console/assets/console-C7uJLLOn.js +51 -0
  48. package/dist/console/assets/console-R8IBY3Am.css +2 -0
  49. package/dist/console/build-info.json +1 -0
  50. package/dist/console/console.html +21 -0
  51. package/dist/console/favicon.svg +7 -0
  52. package/dist/console/icons/apple-touch-icon.png +0 -0
  53. package/dist/console/icons/icon-192.png +0 -0
  54. package/dist/console/icons/icon-512.png +0 -0
  55. package/dist/console/icons/maskable-512.png +0 -0
  56. package/dist/console/manifest.webmanifest +15 -0
  57. package/dist/console/theme-boot.js +27 -0
  58. package/docs/agent-hardening.md +342 -0
  59. package/docs/agent-recipes.md +187 -0
  60. package/docs/agent-workflow.md +320 -0
  61. package/docs/agents.md +894 -0
  62. package/docs/architecture.md +242 -0
  63. package/docs/buzz.md +140 -0
  64. package/docs/capture-warnings.md +57 -0
  65. package/docs/config.md +489 -0
  66. package/docs/deployment.md +289 -0
  67. package/docs/design-system.md +162 -0
  68. package/docs/github.md +107 -0
  69. package/docs/hosted.md +764 -0
  70. package/docs/images/board-overview.png +0 -0
  71. package/docs/images/journeys.png +0 -0
  72. package/docs/images/live-comment.png +0 -0
  73. package/docs/images/phone-comment.png +0 -0
  74. package/docs/images/phone-overview.png +0 -0
  75. package/docs/images/variant.png +0 -0
  76. package/docs/interaction-audits.md +40 -0
  77. package/docs/journeys.md +137 -0
  78. package/docs/local-accounts.md +80 -0
  79. package/docs/notifications.md +237 -0
  80. package/docs/page-checks.md +69 -0
  81. package/docs/performance.md +174 -0
  82. package/docs/starter-agent.md +325 -0
  83. package/docs/updates.md +87 -0
  84. package/examples/audits/interaction.audit.json +17 -0
  85. package/package.json +132 -4
  86. package/src/accounts/avatar.js +121 -0
  87. package/src/accounts/local.js +464 -0
  88. package/src/agent/acp/command.js +204 -0
  89. package/src/agent/acp/detect.js +75 -0
  90. package/src/agent/acp/sandbox.js +160 -0
  91. package/src/agent/agent-health.js +75 -0
  92. package/src/agent/backends/acp.js +1297 -0
  93. package/src/agent/backends/index.js +61 -0
  94. package/src/agent/backends/openai.js +308 -0
  95. package/src/agent/composer.js +221 -0
  96. package/src/agent/config.js +338 -0
  97. package/src/agent/context.js +191 -0
  98. package/src/agent/control.js +122 -0
  99. package/src/agent/errors.js +17 -0
  100. package/src/agent/feedback-loop.js +137 -0
  101. package/src/agent/manage.js +94 -0
  102. package/src/agent/next-steps.js +51 -0
  103. package/src/agent/owner-mcp.js +38 -0
  104. package/src/agent/plain-text.js +52 -0
  105. package/src/agent/ratings-core.js +213 -0
  106. package/src/agent/ratings.js +100 -0
  107. package/src/agent/reply-text.js +67 -0
  108. package/src/agent/routes.js +1065 -0
  109. package/src/agent/run.js +326 -0
  110. package/src/agent/settings-routes.js +704 -0
  111. package/src/agent/showable.js +23 -0
  112. package/src/agent/starter/approvals.js +181 -0
  113. package/src/agent/starter/build-image.js +90 -0
  114. package/src/agent/starter/cli.js +163 -0
  115. package/src/agent/starter/disk.js +53 -0
  116. package/src/agent/starter/doctor.js +180 -0
  117. package/src/agent/starter/egress-proxy.js +351 -0
  118. package/src/agent/starter/gate.js +90 -0
  119. package/src/agent/starter/loop.js +114 -0
  120. package/src/agent/starter/model-relay.js +289 -0
  121. package/src/agent/starter/pause.js +14 -0
  122. package/src/agent/starter/probe.js +272 -0
  123. package/src/agent/starter/prompt.js +41 -0
  124. package/src/agent/starter/push-guard.js +146 -0
  125. package/src/agent/starter/rpc.js +164 -0
  126. package/src/agent/starter/runtime.js +287 -0
  127. package/src/agent/starter/sandbox-main.js +121 -0
  128. package/src/agent/starter/settings.js +290 -0
  129. package/src/agent/starter/source.js +69 -0
  130. package/src/agent/starter/supervisor.js +755 -0
  131. package/src/agent/starter/sweep.js +46 -0
  132. package/src/agent/starter/tools.js +524 -0
  133. package/src/agent/starter/watch.js +84 -0
  134. package/src/agent/starter/worktree.js +409 -0
  135. package/src/agent/text-diff.js +210 -0
  136. package/src/agent/thread-history.js +223 -0
  137. package/src/agent/threads.js +399 -0
  138. package/src/agent/tools.js +200 -0
  139. package/src/agent/turn-changes.js +424 -0
  140. package/src/agent/undo-state.js +26 -0
  141. package/src/agent/user-settings.js +308 -0
  142. package/src/auth/record.js +375 -0
  143. package/src/broken-links.js +164 -0
  144. package/src/buzz/client.js +75 -0
  145. package/src/buzz/config.js +151 -0
  146. package/src/buzz/environment.js +13 -0
  147. package/src/buzz/gateway.js +192 -0
  148. package/src/buzz/routes.js +61 -0
  149. package/src/buzz/signer-child.js +205 -0
  150. package/src/buzz/store.js +89 -0
  151. package/src/buzz/transport.js +60 -0
  152. package/src/buzz/verify.js +140 -0
  153. package/src/capture/actions.js +159 -0
  154. package/src/capture/capture.js +776 -0
  155. package/src/capture/dom-names.js +189 -0
  156. package/src/capture/element-map.js +509 -0
  157. package/src/capture/live.js +827 -0
  158. package/src/capture/media-scheme.js +317 -0
  159. package/src/capture/network-summary.js +86 -0
  160. package/src/capture/pacing.js +34 -0
  161. package/src/capture/requests.js +167 -0
  162. package/src/capture/sanitize.js +752 -0
  163. package/src/checks/accessibility.js +134 -0
  164. package/src/checks/budgets.js +58 -0
  165. package/src/checks/cli.js +55 -0
  166. package/src/checks/comparison.js +113 -0
  167. package/src/checks/environments.js +32 -0
  168. package/src/checks/flow-config.js +82 -0
  169. package/src/checks/flow-origin.js +53 -0
  170. package/src/checks/flows.js +398 -0
  171. package/src/checks/lighthouse-auth.js +145 -0
  172. package/src/checks/lighthouse-findings.js +130 -0
  173. package/src/checks/lighthouse.js +395 -0
  174. package/src/checks/robots.js +85 -0
  175. package/src/checks/routes.js +52 -0
  176. package/src/checks/run-control.js +259 -0
  177. package/src/checks/runner.js +724 -0
  178. package/src/checks/schema.js +133 -0
  179. package/src/checks/seo-analysis.js +443 -0
  180. package/src/checks/seo-probe.js +190 -0
  181. package/src/checks/seo-snapshot.js +99 -0
  182. package/src/checks/store.js +214 -0
  183. package/src/checks/transport.js +47 -0
  184. package/src/cli/args.js +319 -0
  185. package/src/cli/capture.js +79 -0
  186. package/src/cli/commands.js +92 -0
  187. package/src/cli/comments.js +84 -0
  188. package/src/cli/help.js +243 -0
  189. package/src/cli/init.js +214 -0
  190. package/src/cli/misc.js +64 -0
  191. package/src/cli/notify.js +87 -0
  192. package/src/cli/open.js +22 -0
  193. package/src/cli/serve.js +274 -0
  194. package/src/cli/variant.js +82 -0
  195. package/src/cli/watch.js +70 -0
  196. package/src/cli.js +130 -0
  197. package/src/comment-fields.js +76 -0
  198. package/src/comments-cli.js +208 -0
  199. package/src/config-reload.js +100 -0
  200. package/src/config.js +1061 -0
  201. package/src/devices-cli.js +21 -0
  202. package/src/diff.js +95 -0
  203. package/src/discover.js +284 -0
  204. package/src/doctor.js +295 -0
  205. package/src/event-log.js +268 -0
  206. package/src/events-cli.js +102 -0
  207. package/src/events.js +113 -0
  208. package/src/export.js +119 -0
  209. package/src/feedback.js +246 -0
  210. package/src/github.js +551 -0
  211. package/src/hosted/LICENSE.md +105 -0
  212. package/src/hosted/access-cli.js +78 -0
  213. package/src/hosted/admin.js +682 -0
  214. package/src/hosted/agent-approvals.js +163 -0
  215. package/src/hosted/agent-policy.js +189 -0
  216. package/src/hosted/app.js +510 -0
  217. package/src/hosted/auth-routes.js +540 -0
  218. package/src/hosted/auth.js +536 -0
  219. package/src/hosted/backup.js +483 -0
  220. package/src/hosted/board-context.js +35 -0
  221. package/src/hosted/board-routes.js +486 -0
  222. package/src/hosted/board-view.js +94 -0
  223. package/src/hosted/clean-worker.js +24 -0
  224. package/src/hosted/cleaner.js +89 -0
  225. package/src/hosted/comments.js +355 -0
  226. package/src/hosted/console-routes.js +401 -0
  227. package/src/hosted/cookies.js +18 -0
  228. package/src/hosted/crypto.js +80 -0
  229. package/src/hosted/db.js +496 -0
  230. package/src/hosted/device-routes.js +175 -0
  231. package/src/hosted/device.js +233 -0
  232. package/src/hosted/events.js +63 -0
  233. package/src/hosted/guards.js +172 -0
  234. package/src/hosted/guest-view.js +65 -0
  235. package/src/hosted/http.js +39 -0
  236. package/src/hosted/import.js +300 -0
  237. package/src/hosted/mail.js +73 -0
  238. package/src/hosted/mcp-http.js +71 -0
  239. package/src/hosted/membership.js +114 -0
  240. package/src/hosted/operator.js +478 -0
  241. package/src/hosted/ops-cli.js +345 -0
  242. package/src/hosted/pages.js +146 -0
  243. package/src/hosted/permissions.js +113 -0
  244. package/src/hosted/presence.js +372 -0
  245. package/src/hosted/projects.js +124 -0
  246. package/src/hosted/public.js +109 -0
  247. package/src/hosted/push.js +622 -0
  248. package/src/hosted/quotas.js +115 -0
  249. package/src/hosted/ratelimit.js +96 -0
  250. package/src/hosted/rebind.js +316 -0
  251. package/src/hosted/retention.js +128 -0
  252. package/src/hosted/server.js +260 -0
  253. package/src/hosted/setup-link.js +64 -0
  254. package/src/hosted/setup.js +323 -0
  255. package/src/hosted/shares.js +444 -0
  256. package/src/hosted/tailscale.js +204 -0
  257. package/src/hosted/tenancy.js +301 -0
  258. package/src/hosted/token-api.js +455 -0
  259. package/src/hosted/token-events.js +60 -0
  260. package/src/hosted/tokens.js +57 -0
  261. package/src/hosted/turnstile.js +49 -0
  262. package/src/hosted/usercontent.js +154 -0
  263. package/src/hosted/zip.js +155 -0
  264. package/src/invocation.js +58 -0
  265. package/src/journey-paths.js +282 -0
  266. package/src/journeys.js +189 -0
  267. package/src/links.js +106 -0
  268. package/src/local-projects.js +182 -0
  269. package/src/lock.js +193 -0
  270. package/src/mcp.js +417 -0
  271. package/src/mentions.js +151 -0
  272. package/src/net.js +15 -0
  273. package/src/notify/config.js +275 -0
  274. package/src/notify/index.js +301 -0
  275. package/src/notify/lease.js +73 -0
  276. package/src/notify/messages.js +212 -0
  277. package/src/notify/run.js +174 -0
  278. package/src/pixeldiff.js +49 -0
  279. package/src/png.js +143 -0
  280. package/src/reactions.js +111 -0
  281. package/src/remote/cli.js +133 -0
  282. package/src/remote/credentials.js +62 -0
  283. package/src/remote/ids.js +12 -0
  284. package/src/remote/login.js +155 -0
  285. package/src/remote/remote-mcp.js +237 -0
  286. package/src/remote/remote-watch.js +291 -0
  287. package/src/remote/remote.js +313 -0
  288. package/src/remote/share-state.js +78 -0
  289. package/src/remote/share.js +369 -0
  290. package/src/remote/terminal.js +13 -0
  291. package/src/serve-state.js +64 -0
  292. package/src/server/app.js +824 -0
  293. package/src/server/devices.js +186 -0
  294. package/src/server/local-console.js +28 -0
  295. package/src/server/local-user.js +59 -0
  296. package/src/server/pairing-routes.js +159 -0
  297. package/src/server/share-routes.js +89 -0
  298. package/src/server/tailscale.js +97 -0
  299. package/src/sitemap.js +431 -0
  300. package/src/store.js +983 -0
  301. package/src/tokens.js +11 -0
  302. package/src/update/routes.js +245 -0
  303. package/src/watch.js +403 -0
  304. package/src/which.js +58 -0
@@ -0,0 +1,317 @@
1
+ // Freezes a live HTML snapshot to the preferences it was captured with. The
2
+ // board opens the snapshot in the viewer's browser, so a site's
3
+ // `@media (prefers-color-scheme: dark)` rules would follow the viewer, not
4
+ // the capture, and the live view would stop matching its own screenshot.
5
+ // Here media queries are rewritten at capture time: a condition on a
6
+ // resolved feature that matched becomes always true, one that did not
7
+ // becomes never true. Only `prefers-color-scheme` and (when the capture
8
+ // forced it) `prefers-reduced-motion` are resolved; every other feature, and
9
+ // any query that cannot be parsed safely, is left exactly as written.
10
+ //
11
+ // `env` is { colorScheme: 'light' | 'dark', reducedMotion?: 'reduce' |
12
+ // 'no-preference' }. A missing value is not resolved.
13
+
14
+ const TRUE = { kind: 'true' }
15
+ const FALSE = { kind: 'false' }
16
+ const expr = (text) => ({ kind: 'expr', text })
17
+ const MAX_PRELUDE = 4000
18
+
19
+ const RESOLVED = {
20
+ 'prefers-color-scheme': { key: 'colorScheme', values: ['light', 'dark'] },
21
+ 'prefers-reduced-motion': { key: 'reducedMotion', values: ['reduce', 'no-preference'] },
22
+ }
23
+
24
+ // `(name: value)` for a resolved feature: true or false; anything else
25
+ // (other features, range syntax, the boolean form, unknown values): null.
26
+ function featureTruth(inner, env) {
27
+ const match = /^\s*([a-zA-Z-]+)\s*:\s*([a-zA-Z-]+)\s*$/.exec(inner)
28
+ if (!match) return null
29
+ const feature = RESOLVED[match[1].toLowerCase()]
30
+ if (!feature) return null
31
+ const want = env?.[feature.key]
32
+ const value = match[2].toLowerCase()
33
+ if (!feature.values.includes(want) || !feature.values.includes(value)) return null
34
+ return value === want
35
+ }
36
+
37
+ // The index of the `)` closing the `(` at `open`, honouring nested parens and
38
+ // strings; -1 when it is not closed.
39
+ function closingParen(text, open) {
40
+ let depth = 0
41
+ for (let i = open; i < text.length; i += 1) {
42
+ const char = text[i]
43
+ if (char === '"' || char === "'") {
44
+ const end = text.indexOf(char, i + 1)
45
+ if (end === -1) return -1
46
+ i = end
47
+ } else if (char === '(') depth += 1
48
+ else if (char === ')') {
49
+ depth -= 1
50
+ if (depth === 0) return i
51
+ }
52
+ }
53
+ return -1
54
+ }
55
+
56
+ // Words and balanced (...) groups; null for anything else (a stray
57
+ // character, a comment, an unclosed paren), which leaves the query as is.
58
+ function tokenize(text) {
59
+ const tokens = []
60
+ let i = 0
61
+ while (i < text.length) {
62
+ const char = text[i]
63
+ if (/\s/.test(char)) i += 1
64
+ else if (char === '(') {
65
+ const close = closingParen(text, i)
66
+ if (close === -1) return null
67
+ tokens.push({ group: true, raw: text.slice(i, close + 1), inner: text.slice(i + 1, close) })
68
+ i = close + 1
69
+ } else {
70
+ const word = /^[a-zA-Z_-][a-zA-Z0-9_-]*/.exec(text.slice(i, i + 200))
71
+ if (!word) return null
72
+ tokens.push({ word: word[0], lower: word[0].toLowerCase() })
73
+ i += word[0].length
74
+ }
75
+ }
76
+ return tokens
77
+ }
78
+
79
+ // <media-in-parens>: a nested condition or a feature (kept opaque).
80
+ function inParens(token, env, state) {
81
+ const inner = token.inner.trim()
82
+ if (inner.startsWith('(') || /^not\s*\(/i.test(inner)) {
83
+ const tokens = tokenize(inner)
84
+ const node = tokens && condition(tokens, env, state, true)
85
+ if (!node) return null
86
+ if (node.kind !== 'expr') return node
87
+ return expr(`(${node.text})`)
88
+ }
89
+ const truth = featureTruth(inner, env)
90
+ if (truth === null) return expr(token.raw)
91
+ state.changed = true
92
+ return truth ? TRUE : FALSE
93
+ }
94
+
95
+ // <media-condition> (allowOr) or <media-condition-without-or>, the whole of
96
+ // `tokens`. Returns TRUE, FALSE, an expr, or null when it does not parse.
97
+ function condition(tokens, env, state, allowOr) {
98
+ if (!tokens.length) return null
99
+ if (tokens[0].lower === 'not') {
100
+ if (tokens.length !== 2 || !tokens[1].group) return null
101
+ const child = inParens(tokens[1], env, state)
102
+ if (!child) return null
103
+ if (child.kind === 'true') return FALSE
104
+ if (child.kind === 'false') return TRUE
105
+ return expr(`not ${child.text}`)
106
+ }
107
+ if (!tokens[0].group || tokens.length % 2 === 0) return null
108
+ const op = tokens.length > 1 ? tokens[1].lower : 'and'
109
+ if (op !== 'and' && !(allowOr && op === 'or')) return null
110
+ const parts = []
111
+ for (let i = 0; i < tokens.length; i += 2) {
112
+ if (!tokens[i].group || (i > 0 && tokens[i - 1].lower !== op)) return null
113
+ const part = inParens(tokens[i], env, state)
114
+ if (!part) return null
115
+ parts.push(part)
116
+ }
117
+ const decisive = op === 'and' ? 'false' : 'true'
118
+ if (parts.some((part) => part.kind === decisive)) return decisive === 'true' ? TRUE : FALSE
119
+ const left = parts.filter((part) => part.kind === 'expr')
120
+ if (!left.length) return op === 'and' ? TRUE : FALSE
121
+ return expr(left.map((part) => part.text).join(` ${op} `))
122
+ }
123
+
124
+ // One <media-query> (no top-level commas): TRUE, FALSE, its new text, or
125
+ // null when it does not parse.
126
+ function query(text, env, state) {
127
+ const tokens = tokenize(text)
128
+ if (!tokens || !tokens.length) return null
129
+ const first = tokens[0]
130
+ if (first.group || (first.lower === 'not' && tokens[1]?.group)) {
131
+ const node = condition(tokens, env, state, true)
132
+ if (!node) return null
133
+ return node.kind === 'expr' ? expr(node.text) : node
134
+ }
135
+ // [not | only] <media-type> [and <media-condition-without-or>]
136
+ let index = 0
137
+ let prefix = ''
138
+ if (first.lower === 'not' || first.lower === 'only') {
139
+ prefix = first.lower
140
+ index = 1
141
+ }
142
+ const type = tokens[index]
143
+ if (!type?.word || ['and', 'or', 'not', 'only'].includes(type.lower)) return null
144
+ index += 1
145
+ let rest = TRUE
146
+ if (index < tokens.length) {
147
+ if (tokens[index].lower !== 'and') return null
148
+ rest = condition(tokens.slice(index + 1), env, state, false)
149
+ if (!rest) return null
150
+ }
151
+ const negate = prefix === 'not'
152
+ if (rest.kind === 'false') return negate ? TRUE : FALSE
153
+ if (rest.kind === 'true' && type.lower === 'all') return negate ? FALSE : TRUE
154
+ const head = `${prefix ? `${prefix} ` : ''}${type.word}`
155
+ return expr(rest.kind === 'true' ? head : `${head} and ${rest.text}`)
156
+ }
157
+
158
+ // Top-level comma split (not inside parens or strings).
159
+ function splitList(text) {
160
+ const parts = []
161
+ let depth = 0
162
+ let start = 0
163
+ for (let i = 0; i < text.length; i += 1) {
164
+ const char = text[i]
165
+ if (char === '"' || char === "'") {
166
+ const end = text.indexOf(char, i + 1)
167
+ if (end === -1) return null
168
+ i = end
169
+ } else if (char === '(') depth += 1
170
+ else if (char === ')') depth -= 1
171
+ else if (char === ',' && depth === 0) {
172
+ parts.push(text.slice(start, i))
173
+ start = i + 1
174
+ }
175
+ }
176
+ parts.push(text.slice(start))
177
+ return parts
178
+ }
179
+
180
+ // A media query list, as in `@media <list> {`, `<link media="<list>">` or a
181
+ // CSSOM mediaText. Returns the rewritten list ('all' when it always matches,
182
+ // 'not all' when it never does), or the text unchanged when nothing in it
183
+ // is resolved or it cannot be parsed safely.
184
+ export function resolveMediaList(text, env) {
185
+ const source = String(text ?? '')
186
+ if (!source.trim() || source.length > MAX_PRELUDE || !/prefers-/i.test(source)) return source
187
+ const parts = splitList(source)
188
+ if (!parts) return source
189
+ const state = { changed: false }
190
+ const results = []
191
+ for (const part of parts) {
192
+ // An unparsable query stays as written (browsers treat it as not all).
193
+ results.push(query(part, env, state) || expr(part.trim()))
194
+ }
195
+ if (!state.changed) return source
196
+ if (results.some((result) => result.kind === 'true')) return 'all'
197
+ const left = results.filter((result) => result.kind === 'expr')
198
+ return left.length ? left.map((result) => result.text).join(', ') : 'not all'
199
+ }
200
+
201
+ // Every `@media` prelude and `@import ... <media>` in a stylesheet, nested
202
+ // ones included (inside @supports, @layer, other @media). One pass; strings
203
+ // and comments are skipped.
204
+ export function resolveMediaInCss(css, env) {
205
+ const text = String(css ?? '')
206
+ if (!/prefers-/i.test(text)) return text
207
+ let out = ''
208
+ let last = 0
209
+ let i = 0
210
+ while (i < text.length) {
211
+ const char = text[i]
212
+ if (char === '/' && text[i + 1] === '*') {
213
+ const end = text.indexOf('*/', i + 2)
214
+ i = end === -1 ? text.length : end + 2
215
+ continue
216
+ }
217
+ if (char === '"' || char === "'") {
218
+ i = skipString(text, i)
219
+ continue
220
+ }
221
+ if (char === '@') {
222
+ const name = /^@(media|import)(?![a-zA-Z0-9_-])/i.exec(text.slice(i, i + 8))
223
+ if (name) {
224
+ const start = i + name[0].length
225
+ const end = preludeEnd(text, start)
226
+ if (end === -1) break
227
+ const prelude = text.slice(start, end)
228
+ const rewritten = name[1].toLowerCase() === 'media' ? rewriteMediaPrelude(prelude, env) : rewriteImportPrelude(prelude, env)
229
+ if (rewritten !== prelude) {
230
+ out += text.slice(last, start) + rewritten
231
+ last = end
232
+ }
233
+ i = end
234
+ continue
235
+ }
236
+ }
237
+ i += 1
238
+ }
239
+ return out + text.slice(last)
240
+ }
241
+
242
+ function skipString(text, open) {
243
+ const quote = text[open]
244
+ let i = open + 1
245
+ while (i < text.length && text[i] !== quote && text[i] !== '\n') i += text[i] === '\\' ? 2 : 1
246
+ return i + 1
247
+ }
248
+
249
+ // The `{` or `;` that ends an at-rule prelude starting at `start`, or -1.
250
+ function preludeEnd(text, start) {
251
+ let depth = 0
252
+ let i = start
253
+ while (i < text.length) {
254
+ const char = text[i]
255
+ if (char === '"' || char === "'") {
256
+ i = skipString(text, i)
257
+ continue
258
+ }
259
+ if (char === '/' && text[i + 1] === '*') {
260
+ const end = text.indexOf('*/', i + 2)
261
+ if (end === -1) return -1
262
+ i = end + 2
263
+ continue
264
+ }
265
+ if (char === '(') depth += 1
266
+ else if (char === ')') depth = Math.max(0, depth - 1)
267
+ else if ((char === '{' || char === ';' || char === '}') && depth === 0) return i
268
+ i += 1
269
+ }
270
+ return -1
271
+ }
272
+
273
+ function rewriteMediaPrelude(prelude, env) {
274
+ if (prelude.includes('/*')) return prelude
275
+ const resolved = resolveMediaList(prelude, env)
276
+ return resolved === prelude ? prelude : ` ${resolved} `
277
+ }
278
+
279
+ // `@import <url> [layer[(...)]] [supports(...)] <media-list>`.
280
+ function rewriteImportPrelude(prelude, env) {
281
+ if (prelude.includes('/*')) return prelude
282
+ const head = /^\s*(?:url\(\s*(?:"[^"]*"|'[^']*'|[^)'"\s]*)\s*\)|"[^"]*"|'[^']*')\s*/i.exec(prelude)
283
+ if (!head) return prelude
284
+ let index = head[0].length
285
+ const layer = /^layer(?![a-zA-Z0-9_-])\s*/i.exec(prelude.slice(index))
286
+ if (layer) {
287
+ index += layer[0].length
288
+ if (prelude[index] === '(') {
289
+ const close = closingParen(prelude, index)
290
+ if (close === -1) return prelude
291
+ index = close + 1
292
+ }
293
+ index += /^\s*/.exec(prelude.slice(index))[0].length
294
+ }
295
+ if (/^supports\(/i.test(prelude.slice(index))) {
296
+ const close = closingParen(prelude, index + 'supports'.length)
297
+ if (close === -1) return prelude
298
+ index = close + 1
299
+ index += /^\s*/.exec(prelude.slice(index))[0].length
300
+ }
301
+ const media = prelude.slice(index)
302
+ if (!media.trim()) return prelude
303
+ const resolved = resolveMediaList(media, env)
304
+ return resolved === media ? prelude : `${prelude.slice(0, index)}${resolved}`
305
+ }
306
+
307
+ // The `color-scheme` the snapshot root is pinned to, so form controls,
308
+ // scrollbars and the canvas match the capture: the captured scheme when the
309
+ // root supports it ('normal' supports only light), else the one it declared.
310
+ export function pinnedColorScheme(rootValue, captured = 'light') {
311
+ const words = String(rootValue || 'normal')
312
+ .toLowerCase()
313
+ .split(/\s+/)
314
+ .filter((word) => word === 'light' || word === 'dark')
315
+ if (!words.length) return 'light'
316
+ return words.includes(captured) ? captured : words[0]
317
+ }
@@ -0,0 +1,86 @@
1
+ // Aggregate observations only. Resource identities, headers, payloads and
2
+ // browser error text must never enter capture metadata or its warnings.
3
+ export const NETWORK_EVENT_MAX = 10000
4
+ const COUNTS = ['responses', 'http4xx', 'http5xx', 'apiErrors', 'rateLimited', 'apiRateLimited', 'failedRequests']
5
+
6
+ export function cleanNetworkSummary(value) {
7
+ if (!value || value.schemaVersion !== 1 || value.window !== 'navigation-through-screenshot' || typeof value.capped !== 'boolean')
8
+ return null
9
+ if (COUNTS.some((key) => !Number.isInteger(value[key]) || value[key] < 0 || value[key] > NETWORK_EVENT_MAX)) return null
10
+ if (
11
+ value.responses + value.failedRequests > NETWORK_EVENT_MAX ||
12
+ value.http4xx + value.http5xx > value.responses ||
13
+ value.apiErrors > value.http4xx + value.http5xx ||
14
+ value.rateLimited > value.http4xx ||
15
+ value.apiRateLimited > Math.min(value.rateLimited, value.apiErrors)
16
+ )
17
+ return null
18
+ return {
19
+ schemaVersion: 1,
20
+ window: 'navigation-through-screenshot',
21
+ ...Object.fromEntries(COUNTS.map((key) => [key, value[key]])),
22
+ capped: value.capped,
23
+ }
24
+ }
25
+
26
+ export function captureWarningText(value) {
27
+ const summary = cleanNetworkSummary(value)
28
+ if (!summary) return ''
29
+ const parts = []
30
+ if (summary.rateLimited) parts.push(`${summary.rateLimited} HTTP 429${summary.apiRateLimited ? ` (${summary.apiRateLimited} API)` : ''}`)
31
+ const other = summary.http4xx + summary.http5xx - summary.rateLimited
32
+ if (other) parts.push(`${other} other HTTP error${other === 1 ? '' : 's'}`)
33
+ if (summary.failedRequests) parts.push(`${summary.failedRequests} failed request${summary.failedRequests === 1 ? '' : 's'}`)
34
+ if (summary.capped) parts.push('observation limit reached')
35
+ return parts.join('; ')
36
+ }
37
+
38
+ // `isBlocked(request)`: requests the capture's block list aborted on purpose,
39
+ // which are not failures.
40
+ export function observeCaptureNetwork(page, expectedStatus = [], { isBlocked = () => false } = {}) {
41
+ const value = {
42
+ schemaVersion: 1,
43
+ window: 'navigation-through-screenshot',
44
+ ...Object.fromEntries(COUNTS.map((key) => [key, 0])),
45
+ capped: false,
46
+ }
47
+ let events = 0,
48
+ stopped = false
49
+ const admit = () => {
50
+ if (stopped) return false
51
+ if (events >= NETWORK_EVENT_MAX) {
52
+ value.capped = true
53
+ return false
54
+ }
55
+ events += 1
56
+ return true
57
+ }
58
+ const response = (item) => {
59
+ if (!admit()) return
60
+ value.responses += 1
61
+ const status = item.status()
62
+ if (status < 400 || status > 599) return
63
+ const request = item.request()
64
+ if (request.isNavigationRequest() && item.frame() === page.mainFrame() && expectedStatus.includes(status)) return
65
+ if (status < 500) value.http4xx += 1
66
+ else value.http5xx += 1
67
+ const api = ['xhr', 'fetch'].includes(request.resourceType())
68
+ if (api) value.apiErrors += 1
69
+ if (status === 429) {
70
+ value.rateLimited += 1
71
+ if (api) value.apiRateLimited += 1
72
+ }
73
+ }
74
+ const failed = (request) => {
75
+ if (request && isBlocked(request)) return
76
+ if (admit()) value.failedRequests += 1
77
+ }
78
+ page.on('response', response)
79
+ page.on('requestfailed', failed)
80
+ return () => {
81
+ stopped = true
82
+ page.off('response', response)
83
+ page.off('requestfailed', failed)
84
+ return cleanNetworkSummary(value)
85
+ }
86
+ }
@@ -0,0 +1,34 @@
1
+ // A foreground run spaces navigation starts and cools down future shots after
2
+ // an observed 429. It never retries a page or cancels a usable screenshot.
3
+ export const CAPTURE_PACING_DEFAULTS = Object.freeze({ intervalMs: 250, rateLimitCooldownMs: 1000 })
4
+ export const CAPTURE_PACING_MAX = Object.freeze({ intervalMs: 5000, rateLimitCooldownMs: 30000 })
5
+
6
+ export function capturePacer(settings = {}, { now = Date.now, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) } = {}) {
7
+ const pacing = { ...CAPTURE_PACING_DEFAULTS, ...settings }
8
+ for (const key of Object.keys(CAPTURE_PACING_DEFAULTS))
9
+ if (!Number.isInteger(pacing[key]) || pacing[key] < 0 || pacing[key] > CAPTURE_PACING_MAX[key])
10
+ throw new Error('Invalid capture pacing.')
11
+ let nextAt = 0,
12
+ blockedUntil = 0,
13
+ tail = Promise.resolve()
14
+ return {
15
+ wait() {
16
+ const pending = tail.then(async () => {
17
+ // Concurrent observations may extend a cooldown, but one admission
18
+ // cannot wait longer than the configured interval plus cooldown.
19
+ const deadline = now() + pacing.intervalMs + pacing.rateLimitCooldownMs
20
+ for (;;) {
21
+ const delay = Math.min(Math.max(nextAt, blockedUntil), deadline) - now()
22
+ if (delay <= 0) break
23
+ await sleep(delay)
24
+ }
25
+ nextAt = now() + pacing.intervalMs
26
+ })
27
+ tail = pending.catch(() => {})
28
+ return pending
29
+ },
30
+ rateLimited() {
31
+ blockedUntil = Math.max(blockedUntil, now() + pacing.rateLimitCooldownMs)
32
+ },
33
+ }
34
+ }
@@ -0,0 +1,167 @@
1
+ // What a capture browser may fetch, and what it starts with.
2
+ //
3
+ // - The private-host guard: a public page must not make the capture browser
4
+ // fetch from this machine or its network (a router page, a local dev
5
+ // server, cloud metadata). With a public root URL, requests to loopback,
6
+ // private and internal hosts are refused. A local or private root (the usual
7
+ // dev site) keeps them. A host counts as internal by its name or address,
8
+ // and also when its name resolves to an internal address (a public name
9
+ // pointed at 127.0.0.1 or cloud metadata). Lookups are cached for the run.
10
+ // Redirect hops are not routed by the browser, so the capture also asks
11
+ // `isInternal(url)` before it inlines a response (src/capture/live.js).
12
+ // - The block list (config `block`): analytics and other requests a capture
13
+ // should not make. Blocked requests are aborted and remembered, so the
14
+ // network summary does not count them as failures.
15
+ // - localStorage seeds (config `localStorage`), set before the page's own
16
+ // scripts run, on the page's origin only.
17
+
18
+ import dns from 'node:dns'
19
+ import { isIP } from 'node:net'
20
+ import { internalHostname } from './live.js'
21
+
22
+ const LOOKUP_TTL_MS = 5 * 60 * 1000
23
+ const LOOKUP_TIMEOUT_MS = 4000
24
+ const LOOKUP_CACHE_MAX = 2000
25
+ const LOOKUP_TIMED_OUT = Symbol('lookup timed out')
26
+ // One cache per process: a capture run is one process, and each shot's
27
+ // context asks about the same few hosts.
28
+ const sharedCache = new Map()
29
+
30
+ // hostChecker() -> async (hostname) => is it internal? By name and literal
31
+ // address first (no lookup); else every address the name resolves to: one
32
+ // internal address is enough. A name that does not resolve is not internal
33
+ // (the browser cannot reach it either). A lookup that does not answer in time
34
+ // is treated as internal, and asked again next time: a slow answer must never
35
+ // be the way past the guard.
36
+ export function hostChecker({ lookup = dns.promises.lookup, cache = sharedCache, now = Date.now, timeoutMs = LOOKUP_TIMEOUT_MS } = {}) {
37
+ return (hostname) => {
38
+ let host = String(hostname || '')
39
+ .toLowerCase()
40
+ .replace(/\.+$/, '')
41
+ if (!host) return Promise.resolve(false)
42
+ if (internalHostname(host)) return Promise.resolve(true)
43
+ if (host.startsWith('[') && host.endsWith(']')) host = host.slice(1, -1)
44
+ if (isIP(host)) return Promise.resolve(false)
45
+ const hit = cache.get(host)
46
+ if (hit && hit.until > now()) return hit.answer
47
+ let timer = null
48
+ const answer = Promise.race([
49
+ Promise.resolve()
50
+ .then(() => lookup(host, { all: true }))
51
+ .then((found) =>
52
+ (Array.isArray(found) ? found : [found]).some(
53
+ (item) => item?.address && internalHostname(String(item.address).replace(/%.*$/, '')),
54
+ ),
55
+ ),
56
+ new Promise((resolve) => {
57
+ timer = setTimeout(() => resolve(LOOKUP_TIMED_OUT), timeoutMs)
58
+ timer.unref?.()
59
+ }),
60
+ ])
61
+ .then((found) => {
62
+ if (found !== LOOKUP_TIMED_OUT) return found
63
+ if (cache.get(host)?.answer === answer) cache.delete(host)
64
+ return true
65
+ })
66
+ .catch(() => false)
67
+ .finally(() => clearTimeout(timer))
68
+ if (cache.size >= LOOKUP_CACHE_MAX) cache.clear()
69
+ cache.set(host, { answer, until: now() + LOOKUP_TTL_MS })
70
+ return answer
71
+ }
72
+ }
73
+
74
+ const hostOf = (url) => {
75
+ try {
76
+ return new URL(url).hostname
77
+ } catch {
78
+ return null
79
+ }
80
+ }
81
+
82
+ const escapeRegExp = (value) => value.replace(/[.+?^${}()|[\]\\]/g, '\\$&')
83
+
84
+ // A pattern list -> url => blocked? Bare host names ("plausible.io") match
85
+ // the host and its subdomains; a pattern with "*" or "/" matches the whole
86
+ // URL, "*" standing for any run of characters.
87
+ export function blockMatcher(patterns = []) {
88
+ const hosts = []
89
+ const globs = []
90
+ for (const pattern of patterns) {
91
+ if (/[*/]/.test(pattern)) globs.push(new RegExp(`^${pattern.split('*').map(escapeRegExp).join('.*')}$`, 'i'))
92
+ else hosts.push(pattern.toLowerCase().replace(/^\.+/, ''))
93
+ }
94
+ if (!hosts.length && !globs.length) return null
95
+ return (url) => {
96
+ let host = ''
97
+ try {
98
+ host = new URL(url).hostname.toLowerCase()
99
+ } catch {
100
+ return false
101
+ }
102
+ if (hosts.some((item) => host === item || host.endsWith(`.${item}`))) return true
103
+ return globs.some((glob) => glob.test(url))
104
+ }
105
+ }
106
+
107
+ // Installs the guard and the block list on a context. Returns
108
+ // { guarded, isBlocked(request), isInternal(url) }; nothing is routed when
109
+ // neither applies. `guard: false` installs the block list alone (page
110
+ // checks). `isInternal(url)` is the guard's answer for a URL (always false
111
+ // without the guard): the capture asks it for responses the route never saw.
112
+ // `lookup` and `cache` are for tests (hostChecker).
113
+ export async function installRequestRules(context, rootUrl, { block = [], guard = true, lookup, cache } = {}) {
114
+ const internal = hostChecker({ ...(lookup ? { lookup } : {}), ...(cache ? { cache } : {}) })
115
+ let guarded = false
116
+ if (guard) {
117
+ const rootHost = hostOf(rootUrl)
118
+ // No host (not a URL): nothing to compare with, as before.
119
+ guarded = rootHost ? !(await internal(rootHost)) : false
120
+ }
121
+ const blocks = blockMatcher(block)
122
+ const blocked = new WeakSet()
123
+ if (guarded || blocks) {
124
+ await context.route('**/*', async (route) => {
125
+ const request = route.request()
126
+ const url = request.url()
127
+ const host = hostOf(url)
128
+ let refuse = Boolean(guarded && host && (await internal(host)))
129
+ if (!refuse && blocks && host && blocks(url)) {
130
+ blocked.add(request)
131
+ refuse = true
132
+ }
133
+ // A context closed meanwhile (timeout) makes either call fail: nothing to do then.
134
+ return (refuse ? route.abort('blockedbyclient') : route.continue()).catch(() => {})
135
+ })
136
+ }
137
+ return {
138
+ guarded,
139
+ isBlocked: (request) => blocked.has(request),
140
+ isInternal: async (url) => {
141
+ const host = guarded ? hostOf(url) : null
142
+ return Boolean(host && (await internal(host)))
143
+ },
144
+ }
145
+ }
146
+
147
+ // The init script that seeds localStorage on `origin` before any page script.
148
+ export function localStorageScript(origin, entries) {
149
+ return `(() => {
150
+ try {
151
+ if (location.origin !== ${JSON.stringify(origin)}) return;
152
+ const entries = ${JSON.stringify(Object.entries(entries))};
153
+ for (const [key, value] of entries) localStorage.setItem(key, value);
154
+ } catch {}
155
+ })();`
156
+ }
157
+
158
+ export async function seedLocalStorage(context, url, entries) {
159
+ if (!entries || !Object.keys(entries).length) return
160
+ let origin
161
+ try {
162
+ origin = new URL(url).origin
163
+ } catch {
164
+ return
165
+ }
166
+ await context.addInitScript(localStorageScript(origin, entries))
167
+ }