@flanksource/page-runtime 0.0.0-stage → 0.1.0

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 (312) hide show
  1. package/LICENSE +17 -0
  2. package/README.md +494 -2
  3. package/dist/build/README.md +96 -0
  4. package/dist/build/cjs-export-names.mjs +24 -0
  5. package/dist/build/dependencies.mjs +279 -0
  6. package/dist/build/dependencies.mjs.map +1 -0
  7. package/dist/build/dependency-cache-Zg-FGasE.mjs +2130 -0
  8. package/dist/build/dependency-cache-Zg-FGasE.mjs.map +1 -0
  9. package/dist/build/index.mjs +42 -0
  10. package/dist/build/index.mjs.map +1 -0
  11. package/dist/build/package.json +19 -0
  12. package/dist/build/types/activity-schema.d.ts +62 -0
  13. package/dist/build/types/build/barrels.d.ts +70 -0
  14. package/dist/build/types/build/base.d.ts +2 -0
  15. package/dist/build/types/build/browser-runtime-exports.d.ts +19 -0
  16. package/dist/build/types/build/check-fragment.d.ts +5 -0
  17. package/dist/build/types/build/commonjs-exports.d.ts +5 -0
  18. package/dist/build/types/build/convert-commonjs.d.ts +12 -0
  19. package/dist/build/types/build/dependencies.d.ts +6 -0
  20. package/dist/build/types/build/dependency-barrel-index.d.ts +5 -0
  21. package/dist/build/types/build/dependency-barrels.d.ts +7 -0
  22. package/dist/build/types/build/dependency-cache.d.ts +7 -0
  23. package/dist/build/types/build/dependency-optional.d.ts +4 -0
  24. package/dist/build/types/build/dependency-plugin.d.ts +8 -0
  25. package/dist/build/types/build/dependency-runtime.d.ts +20 -0
  26. package/dist/build/types/build/dependency-workers.d.ts +8 -0
  27. package/dist/build/types/build/errors.d.ts +9 -0
  28. package/dist/build/types/build/fragment.d.ts +13 -0
  29. package/dist/build/types/build/index.d.ts +7 -0
  30. package/dist/build/types/build/library-runtime.d.ts +21 -0
  31. package/dist/build/types/build/module-utils.d.ts +3 -0
  32. package/dist/build/types/build/recipe-dependencies.d.ts +2 -0
  33. package/dist/build/types/build/runtime-entries.d.ts +4 -0
  34. package/dist/build/types/build/runtime-layer.d.ts +17 -0
  35. package/dist/build/types/build/trace.d.ts +140 -0
  36. package/dist/build/types/design-schema.d.ts +98 -0
  37. package/dist/build/types/host/agent-source.d.ts +2 -0
  38. package/dist/build/types/host/agent-validation.d.ts +3 -0
  39. package/dist/build/types/host/design-validation.d.ts +2 -0
  40. package/dist/build/types/host/message-values.d.ts +8 -0
  41. package/dist/build/types/host/review/validation.d.ts +5 -0
  42. package/dist/build/types/host/validation.d.ts +6 -0
  43. package/dist/build/types/link/page-sources.d.ts +31 -0
  44. package/dist/build/types/link/types.d.ts +62 -0
  45. package/dist/build/types/link/validation.d.ts +9 -0
  46. package/dist/build/types/markers.d.ts +10 -0
  47. package/dist/build/types/review-schema.d.ts +60 -0
  48. package/dist/build/types/schema.d.ts +319 -0
  49. package/dist/build/types/sw/barrels.d.ts +9 -0
  50. package/dist/build/types/sw/compiler-plugins.d.ts +6 -0
  51. package/dist/build/types/sw/composition.d.ts +8 -0
  52. package/dist/build/types/sw/module-transform.d.ts +68 -0
  53. package/dist/build/types/sw/profile.d.ts +7 -0
  54. package/dist/build/types/sw/source-provider.d.ts +7 -0
  55. package/dist/build/types/sw/versions.d.ts +10 -0
  56. package/dist/node/catalog.mjs +1 -0
  57. package/dist/node/chunks/publication-RchcQvxD.mjs +229 -0
  58. package/dist/node/chunks/publication-RchcQvxD.mjs.map +1 -0
  59. package/dist/node/chunks/schema-CaRTfg2x.mjs +12 -0
  60. package/dist/node/chunks/schema-CaRTfg2x.mjs.map +1 -0
  61. package/dist/node/dev.mjs +410 -0
  62. package/dist/node/dev.mjs.map +1 -0
  63. package/dist/node/publication/cli.mjs +13 -0
  64. package/dist/node/publication/cli.mjs.map +1 -0
  65. package/dist/node/publication.mjs +1 -0
  66. package/dist/node/schema.mjs +1 -0
  67. package/dist/node/styles.mjs +49 -0
  68. package/dist/node/styles.mjs.map +1 -0
  69. package/dist/static/boot.js +40938 -0
  70. package/dist/static/boot.js.map +1 -0
  71. package/dist/static/bootstrap.html +1 -0
  72. package/dist/static/devtools-hook.js +118 -0
  73. package/dist/static/document-bundle.js +1 -0
  74. package/dist/static/document.js +2621 -0
  75. package/dist/static/editing.js +37 -0
  76. package/dist/static/export-compiler.js +81521 -0
  77. package/dist/static/export-compiler.js.map +1 -0
  78. package/dist/static/page-agent.js +17193 -0
  79. package/dist/static/page-agent.js.map +1 -0
  80. package/dist/static/sw.js +86112 -0
  81. package/dist/static/sw.js.map +1 -0
  82. package/package.json +110 -3
  83. package/scripts/build-builder.ts +27 -0
  84. package/scripts/build-library-runtime.ts +9 -0
  85. package/scripts/build-node.ts +26 -0
  86. package/scripts/build-static.ts +86 -0
  87. package/scripts/build.ts +7 -0
  88. package/scripts/check-fragment.ts +12 -0
  89. package/scripts/local-workspaces.ts +55 -0
  90. package/scripts/react-externals.ts +18 -0
  91. package/scripts/release-version.ts +47 -0
  92. package/scripts/run-package-build.ts +8 -0
  93. package/scripts/serve-packages.ts +8 -0
  94. package/src/activity-schema.ts +92 -0
  95. package/src/build/README.md +96 -0
  96. package/src/build/barrels.ts +306 -0
  97. package/src/build/base.ts +2 -0
  98. package/src/build/browser-runtime-exports.ts +52 -0
  99. package/src/build/check-fragment.ts +45 -0
  100. package/src/build/cjs-export-names.mjs +24 -0
  101. package/src/build/commonjs-exports.ts +24 -0
  102. package/src/build/convert-commonjs.ts +183 -0
  103. package/src/build/dependencies.ts +6 -0
  104. package/src/build/dependency-barrel-index.ts +48 -0
  105. package/src/build/dependency-barrels.ts +80 -0
  106. package/src/build/dependency-cache.ts +40 -0
  107. package/src/build/dependency-optional.ts +15 -0
  108. package/src/build/dependency-plugin.ts +58 -0
  109. package/src/build/dependency-runtime.ts +182 -0
  110. package/src/build/dependency-workers.ts +41 -0
  111. package/src/build/errors.ts +9 -0
  112. package/src/build/fragment.ts +89 -0
  113. package/src/build/index.ts +7 -0
  114. package/src/build/library-runtime.ts +101 -0
  115. package/src/build/module-utils.ts +11 -0
  116. package/src/build/recipe-dependencies.ts +14 -0
  117. package/src/build/runtime-entries.ts +10 -0
  118. package/src/build/runtime-layer.ts +99 -0
  119. package/src/build/trace.ts +431 -0
  120. package/src/design-schema.ts +25 -0
  121. package/src/dev/README.md +78 -0
  122. package/src/dev/catalog.ts +79 -0
  123. package/src/dev/cli.ts +25 -0
  124. package/src/dev/index.ts +118 -0
  125. package/src/dev/runtime-origin.ts +63 -0
  126. package/src/editing.ts +25 -0
  127. package/src/form/entry-source.ts +68 -0
  128. package/src/form/form-page.ts +63 -0
  129. package/src/form/index.ts +2 -0
  130. package/src/form/source-update.ts +17 -0
  131. package/src/frame/activity.browser.ts +34 -0
  132. package/src/frame/activity.ts +52 -0
  133. package/src/frame/agent/README.md +47 -0
  134. package/src/frame/agent/agent.browser.ts +127 -0
  135. package/src/frame/agent/design.ts +62 -0
  136. package/src/frame/agent/frame-layout.ts +54 -0
  137. package/src/frame/agent/index.ts +151 -0
  138. package/src/frame/agent/overlay.ts +104 -0
  139. package/src/frame/agent/owner.ts +61 -0
  140. package/src/frame/agent/provider.tsx +14 -0
  141. package/src/frame/agent/react-override.ts +55 -0
  142. package/src/frame/agent/review.browser.ts +65 -0
  143. package/src/frame/agent/review.ts +108 -0
  144. package/src/frame/agent/testing/callsite.tsx +5 -0
  145. package/src/frame/agent/testing/client.ts +99 -0
  146. package/src/frame/agent/testing/library.ts +3 -0
  147. package/src/frame/agent/testing/modal.tsx +5 -0
  148. package/src/frame/agent/testing/review-client.ts +43 -0
  149. package/src/frame/agent/testing/review-server.ts +31 -0
  150. package/src/frame/agent/testing/server.ts +72 -0
  151. package/src/frame/agent/testing/vocabulary-host.ts +20 -0
  152. package/src/frame/agent/testing/vocabulary.tsx +10 -0
  153. package/src/frame/agent/vitest.browser.config.ts +6 -0
  154. package/src/frame/agent/vocabulary.browser.ts +30 -0
  155. package/src/frame/agent/vocabulary.ts +13 -0
  156. package/src/frame/agent.ts +3 -0
  157. package/src/frame/boot-styles.ts +50 -0
  158. package/src/frame/boot.ts +269 -0
  159. package/src/frame/bridge.ts +27 -0
  160. package/src/frame/devtools-hook.ts +1 -0
  161. package/src/frame/document-assets.ts +76 -0
  162. package/src/frame/document-entry.ts +68 -0
  163. package/src/frame/document-modules.ts +113 -0
  164. package/src/frame/document-mount.ts +32 -0
  165. package/src/frame/entry.ts +4 -0
  166. package/src/frame/export-compiler.ts +18 -0
  167. package/src/frame/export-page.ts +61 -0
  168. package/src/frame/export.ts +89 -0
  169. package/src/frame/index.ts +8 -0
  170. package/src/frame/local-runtime.browser.ts +36 -0
  171. package/src/frame/mount-page.ts +36 -0
  172. package/src/frame/page-agent.ts +2 -0
  173. package/src/frame/readiness.ts +51 -0
  174. package/src/frame/render-job.ts +101 -0
  175. package/src/frame/review-integration.browser.ts +48 -0
  176. package/src/frame/runtime.browser.ts +90 -0
  177. package/src/frame/tailwind/README.md +49 -0
  178. package/src/frame/tailwind/boot-styles.browser.ts +18 -0
  179. package/src/frame/tailwind/cache.ts +20 -0
  180. package/src/frame/tailwind/load.ts +75 -0
  181. package/src/frame/tailwind/recipe.ts +76 -0
  182. package/src/frame/tailwind/runtime.ts +113 -0
  183. package/src/frame/tailwind/store.ts +55 -0
  184. package/src/frame/tailwind/stylesheets.ts +42 -0
  185. package/src/frame/tailwind/tailwind.browser.ts +71 -0
  186. package/src/frame/tailwind/testing/client.ts +133 -0
  187. package/src/frame/tailwind/testing/compare.ts +91 -0
  188. package/src/frame/tailwind/testing/pages.ts +14 -0
  189. package/src/frame/tailwind/testing/server.ts +89 -0
  190. package/src/frame/tailwind/vitest.browser.config.ts +7 -0
  191. package/src/frame/testing/boot-layout.ts +3 -0
  192. package/src/frame/testing/boot-page.ts +3 -0
  193. package/src/frame/testing/host.ts +78 -0
  194. package/src/frame/testing/local-host.tsx +33 -0
  195. package/src/frame/testing/server.ts +135 -0
  196. package/src/host/BuildLog.tsx +28 -0
  197. package/src/host/DEBUG_CONSOLE.md +13 -0
  198. package/src/host/PageForm.tsx +63 -0
  199. package/src/host/PageFrame.tsx +49 -0
  200. package/src/host/RuntimeActivity.tsx +77 -0
  201. package/src/host/RuntimeDebugPanel.tsx +18 -0
  202. package/src/host/activity-state.ts +69 -0
  203. package/src/host/agent-source.ts +14 -0
  204. package/src/host/agent-validation.ts +73 -0
  205. package/src/host/bridge.ts +56 -0
  206. package/src/host/build-log.ts +29 -0
  207. package/src/host/clear-cache.ts +66 -0
  208. package/src/host/debug-runtime.tsx +17 -0
  209. package/src/host/design-validation.ts +96 -0
  210. package/src/host/index.ts +12 -0
  211. package/src/host/link/index.ts +66 -0
  212. package/src/host/link/transport.ts +68 -0
  213. package/src/host/link/watch.ts +62 -0
  214. package/src/host/message-values.ts +55 -0
  215. package/src/host/origin.ts +7 -0
  216. package/src/host/review/README.md +32 -0
  217. package/src/host/review/index.ts +43 -0
  218. package/src/host/review/validation.ts +55 -0
  219. package/src/host/runtime-diagnostics.ts +41 -0
  220. package/src/host/validation.ts +148 -0
  221. package/src/link/README.md +115 -0
  222. package/src/link/barrels.ts +5 -0
  223. package/src/link/build-cli.ts +12 -0
  224. package/src/link/build.ts +99 -0
  225. package/src/link/commonjs.ts +39 -0
  226. package/src/link/examples/server.ts +18 -0
  227. package/src/link/index.ts +6 -0
  228. package/src/link/link.browser.ts +66 -0
  229. package/src/link/local-relay.browser.ts +22 -0
  230. package/src/link/overrides.ts +69 -0
  231. package/src/link/page-sources.ts +69 -0
  232. package/src/link/source.ts +25 -0
  233. package/src/link/storage.ts +32 -0
  234. package/src/link/testing/client.ts +96 -0
  235. package/src/link/testing/folder.ts +19 -0
  236. package/src/link/testing/local-client.ts +30 -0
  237. package/src/link/testing/local-server.ts +26 -0
  238. package/src/link/testing/local-worker.ts +17 -0
  239. package/src/link/testing/server.ts +131 -0
  240. package/src/link/testing/worker.ts +32 -0
  241. package/src/link/testing-cache.ts +20 -0
  242. package/src/link/testing-fixtures.ts +16 -0
  243. package/src/link/types.ts +27 -0
  244. package/src/link/validation.ts +44 -0
  245. package/src/link/vitest.browser.config.ts +3 -0
  246. package/src/markers.ts +18 -0
  247. package/src/publication/build.ts +27 -0
  248. package/src/publication/fixtures/build.mjs +2 -0
  249. package/src/publication/index.ts +3 -0
  250. package/src/publication/lock.ts +32 -0
  251. package/src/publication/manifest.ts +14 -0
  252. package/src/publication/publish.ts +80 -0
  253. package/src/publication/runtime.ts +28 -0
  254. package/src/publication/schema.ts +13 -0
  255. package/src/review-schema.ts +17 -0
  256. package/src/schema.ts +175 -0
  257. package/src/storage/db.ts +64 -0
  258. package/src/styles.ts +40 -0
  259. package/src/sw/activity.ts +66 -0
  260. package/src/sw/barrels.ts +44 -0
  261. package/src/sw/candidates.ts +14 -0
  262. package/src/sw/compile.ts +92 -0
  263. package/src/sw/compiler-columns.ts +44 -0
  264. package/src/sw/compiler-internals.d.ts +8 -0
  265. package/src/sw/compiler-plugins.ts +18 -0
  266. package/src/sw/compiler.ts +93 -0
  267. package/src/sw/composition.ts +86 -0
  268. package/src/sw/content-types.ts +28 -0
  269. package/src/sw/converted.browser.ts +31 -0
  270. package/src/sw/converted.ts +64 -0
  271. package/src/sw/editable-sites.ts +42 -0
  272. package/src/sw/errors.ts +30 -0
  273. package/src/sw/esm-sh-fixtures/browser-client.ts +18 -0
  274. package/src/sw/esm-sh-fixtures/browser-server.ts +104 -0
  275. package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-entry.headers +15 -0
  276. package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-entry.mjs.txt +3 -0
  277. package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-module.headers +13 -0
  278. package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-module.mjs.txt +142 -0
  279. package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-entry.headers +15 -0
  280. package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-entry.mjs.txt +3 -0
  281. package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-module.headers +11 -0
  282. package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-module.mjs.txt +222 -0
  283. package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-entry.headers +14 -0
  284. package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-entry.mjs.txt +3 -0
  285. package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-module.headers +11 -0
  286. package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-module.mjs.txt +76 -0
  287. package/src/sw/esm-sh-fixtures/fixtures.ts +54 -0
  288. package/src/sw/esm-sh-fixtures/redact.ts +1 -0
  289. package/src/sw/index.ts +7 -0
  290. package/src/sw/integrity.ts +10 -0
  291. package/src/sw/legacy-storage.ts +18 -0
  292. package/src/sw/link-activity.ts +21 -0
  293. package/src/sw/link-cache.ts +19 -0
  294. package/src/sw/link-compiler.ts +120 -0
  295. package/src/sw/link-folder.ts +29 -0
  296. package/src/sw/link-relay.ts +40 -0
  297. package/src/sw/link-route.ts +239 -0
  298. package/src/sw/link-source.ts +41 -0
  299. package/src/sw/markers.ts +128 -0
  300. package/src/sw/module-transform.ts +364 -0
  301. package/src/sw/page-clients.ts +45 -0
  302. package/src/sw/profile.ts +90 -0
  303. package/src/sw/resolver.ts +224 -0
  304. package/src/sw/router.ts +360 -0
  305. package/src/sw/runtime-exports.ts +39 -0
  306. package/src/sw/runtime-module.ts +13 -0
  307. package/src/sw/source-hash.ts +37 -0
  308. package/src/sw/source-provider.ts +20 -0
  309. package/src/sw/versions.ts +96 -0
  310. package/src/sw/worker.ts +91 -0
  311. package/static/README.md +15 -0
  312. package/static/profile.example.json +15 -0
@@ -0,0 +1,128 @@
1
+ import { parse } from "sucrase/dist/parser";
2
+ import { TokenType } from "sucrase/dist/parser/tokenizer/types";
3
+ import { formatEditableSource, parseEditableSource } from "../markers.ts";
4
+ import { editableTags, openingEnd } from "./editable-sites.ts";
5
+ import { sourceHash } from "./source-hash.ts";
6
+
7
+ // Design-mode source markers: `data-source="<path>:<line>:<column>"` on host elements, line and column 1-based at the
8
+ // element's `<`. Sucrase's development output gives jsxDEV a `lineNumber` but no `columnNumber`, so for TS, TSX and
9
+ // JSX the compiler writes the attribute into each host tag before Sucrase runs, using Sucrase's own tokenizer.
10
+
11
+ export type MarkerSite = { line: number; column: number; tag: string };
12
+
13
+ function afterTypeArguments(tokens: ReturnType<typeof parse>["tokens"], nameIndex: number): number {
14
+ let end = nameIndex;
15
+ while (tokens[end + 1]?.isType) end += 1;
16
+ return tokens[end]!.end;
17
+ }
18
+
19
+ /** Offsets where each line starts, for turning an offset into a 1-based line and column. */
20
+ function lineStarts(code: string): number[] {
21
+ const starts = [0];
22
+ for (let index = 0; index < code.length; index += 1) if (code[index] === "\n") starts.push(index + 1);
23
+ return starts;
24
+ }
25
+
26
+ function position(starts: number[], offset: number): { line: number; column: number } {
27
+ let low = 0;
28
+ let high = starts.length - 1;
29
+ while (low < high) {
30
+ const middle = Math.ceil((low + high) / 2);
31
+ if ((starts[middle] ?? 0) <= offset) low = middle;
32
+ else high = middle - 1;
33
+ }
34
+ return { line: low + 1, column: offset - (starts[low] ?? 0) + 1 };
35
+ }
36
+
37
+ /** Every host JSX opening tag (lowercase name, not a member expression) with its position. */
38
+ export function hostSites(code: string, typescript: boolean): Array<MarkerSite & { nameEnd: number }> {
39
+ const { tokens } = parse(code, true, typescript, false);
40
+ const starts = lineStarts(code);
41
+ const sites: Array<MarkerSite & { nameEnd: number }> = [];
42
+ tokens.forEach((token, index) => {
43
+ const name = tokens[index + 1];
44
+ const after = tokens[index + 2];
45
+ if (token.type !== TokenType.jsxTagStart || name?.type !== TokenType.jsxName) return;
46
+ if (after?.type === TokenType.dot || after?.type === TokenType.colon) return;
47
+ const tag = code.slice(name.start, name.end);
48
+ if (!/^[a-z]/.test(tag)) return;
49
+ sites.push({ ...position(starts, token.start), tag, nameEnd: afterTypeArguments(tokens, index + 1) });
50
+ });
51
+ return sites;
52
+ }
53
+
54
+ /** Writes `data-source` into every host JSX opening tag of a module. */
55
+ export function insertSourceMarkers(code: string, path: string, typescript: boolean): { code: string; sites: MarkerSite[]; sourceProperty: string } {
56
+ const sites = hostSites(code, typescript);
57
+ let sourceProperty = "__pageRuntimeSource";
58
+ while (code.includes(sourceProperty)) sourceProperty += "_";
59
+ const { tokens } = parse(code, true, typescript, false);
60
+ const starts = lineStarts(code);
61
+ const editable = editableTags(code, tokens);
62
+ const hash = sourceHash(code);
63
+ let ordinal = 0;
64
+ const insertions = sites.map((site) => ({ at: site.nameEnd, text: ` data-source=${JSON.stringify(`${path}:${site.line}:${site.column}`)}` }));
65
+ tokens.forEach((token, index) => {
66
+ const name = tokens[index + 1];
67
+ if (token.type !== TokenType.jsxTagStart || name?.type !== TokenType.jsxName) return;
68
+ let end = index + 2;
69
+ while (tokens[end]?.type === TokenType.dot && tokens[end + 1]?.type === TokenType.jsxName) end += 2;
70
+ const { line, column } = position(starts, token.start);
71
+ const tag = code.slice(name.start, tokens[end - 1]!.end);
72
+ if (editable.has(tag)) {
73
+ const at = openingEnd(tokens, index);
74
+ if (tokens.slice(end, tokens.findIndex((item) => item.start === at)).some((item) => code.slice(item.start, item.end) === "data-source")) throw new Error(`${path}:${line}:${column}: source markers are compiler-owned`);
75
+ const previous = insertions.findIndex((item) => item.at === afterTypeArguments(tokens, end - 1));
76
+ if (previous >= 0) insertions.splice(previous, 1);
77
+ insertions.push({ at, text: ` data-source=${JSON.stringify(formatEditableSource({ file: path, line, column, ordinal: ordinal++, hash }))} ` });
78
+ }
79
+ if (/^[a-z]/.test(tag) && tokens[index + 2]?.type !== TokenType.dot) return;
80
+ insertions.push({ at: afterTypeArguments(tokens, end - 1), text: ` ${sourceProperty}={{fileName:${JSON.stringify(path)},lineNumber:${line},columnNumber:${column}}}` });
81
+ });
82
+ let marked = code;
83
+ for (const insertion of insertions.sort((a, b) => b.at - a.at)) {
84
+ marked = `${marked.slice(0, insertion.at)}${insertion.text}${marked.slice(insertion.at)}`;
85
+ }
86
+ return { code: marked, sites: sites.map(({ line, column, tag }) => ({ line, column, tag })), sourceProperty };
87
+ }
88
+
89
+ export type MarkerCheck = { valid: number; invalid: string[] };
90
+
91
+ /**
92
+ * Checks rendered markers against the sources: a TS/TSX/JSX marker must name a host tag's `<`, and an MDX marker
93
+ * (from MDX's jsxDEV positions, which point at markdown constructs too) a position inside its file.
94
+ */
95
+ export function checkMarkers(markers: string[], sources: Map<string, string>): MarkerCheck {
96
+ const sites = new Map<string, Set<string>>();
97
+ const result: MarkerCheck = { valid: 0, invalid: [] };
98
+ for (const marker of markers) {
99
+ const match = /^(.+):(\d+):(\d+)(?:#\d+@[0-9a-f]{12})?$/.exec(marker);
100
+ const code = match ? sources.get(match[1] ?? "") : undefined;
101
+ if (!match || code === undefined) {
102
+ result.invalid.push(`${marker}: not a known <path>:<line>:<column>`);
103
+ continue;
104
+ }
105
+ const [, path = "", line, column] = match;
106
+ if (marker.includes("#")) {
107
+ const editable = parseEditableSource(marker);
108
+ if (editable.hash !== sourceHash(code) || !insertSourceMarkers(code, path, /\.tsx?$/.test(path)).code.includes(`data-source=${JSON.stringify(marker)}`)) result.invalid.push(`${marker}: no matching editable call site`);
109
+ else result.valid += 1;
110
+ continue;
111
+ }
112
+ const at = `${line}:${column}`;
113
+ if (/\.mdx?$/.test(path)) {
114
+ const text = code.split("\n")[Number(line) - 1];
115
+ if (text === undefined || Number(column) < 1 || Number(column) > text.length + 1) result.invalid.push(`${marker}: outside ${path}`);
116
+ else result.valid += 1;
117
+ continue;
118
+ }
119
+ let known = sites.get(path);
120
+ if (!known) {
121
+ known = new Set(hostSites(code, /\.tsx?$/.test(path)).map((site) => `${site.line}:${site.column}`));
122
+ sites.set(path, known);
123
+ }
124
+ if (known.has(at)) result.valid += 1;
125
+ else result.invalid.push(`${marker}: no host tag starts there`);
126
+ }
127
+ return result;
128
+ }
@@ -0,0 +1,364 @@
1
+ import { parse, type Import, type StaticImport } from "es-module-lexer";
2
+
3
+ // Pure transforms the runtime applies to served modules. The service worker bundles this file, so it imports
4
+ // nothing from Node. Callers await es-module-lexer's `init` before calling `transformModule`.
5
+
6
+ /**
7
+ * A library version's barrel index, published with its fragment: for each module that forwards exports, the
8
+ * module that defines each name, as a position in `modules`, plus the name to import there when it differs.
9
+ */
10
+ import type { BarrelIndex } from "../schema.ts";
11
+ export type { BarrelIndex } from "../schema.ts";
12
+
13
+ export type SpecifierKind = "relative" | "url" | "builtin" | "bare";
14
+
15
+ export function specifierKind(specifier: string): SpecifierKind {
16
+ if (/^(\.{1,2}\/|\/)/.test(specifier)) return "relative";
17
+ if (specifier.startsWith("node:")) return "builtin";
18
+ if (/^[a-z][a-z0-9+.-]*:/i.test(specifier)) return "url";
19
+ return "bare";
20
+ }
21
+
22
+ export const NPM_PREFIX = "/npm/";
23
+
24
+ /** Suffixes tried for a relative import that names no file, in the build tool's resolution order. */
25
+ export const CANONICAL_CANDIDATES = ["", ".mjs", ".js", ".cjs", ".json", "/index.mjs", "/index.js", "/index.cjs"];
26
+
27
+ export function stylesheetModule(css: string, url: string): string {
28
+ return [
29
+ `const link = document.createElement("link");`,
30
+ `link.rel = "stylesheet"; link.href = ${JSON.stringify(url)};`,
31
+ 'link.dataset.pageRuntimeStylesheet = new URL(link.href).pathname;',
32
+ 'const previous = [...document.querySelectorAll("link[data-page-runtime-stylesheet]")].filter(item => item.dataset.pageRuntimeStylesheet === link.dataset.pageRuntimeStylesheet);',
33
+ `link.dataset.pageRuntime = "loading";`,
34
+ `const ready = new Promise((resolve, reject) => { link.onload = () => { for (const item of previous) item.remove(); link.dataset.pageRuntime = "loaded"; resolve(link.sheet); }; link.onerror = () => { link.dataset.pageRuntime = "error"; reject(new Error("stylesheet failed: " + link.href)); }; });`,
35
+ "document.head.append(link);",
36
+ `export const source = ${JSON.stringify(css)};`,
37
+ "export default ready;",
38
+ "",
39
+ ].join("\n");
40
+ }
41
+
42
+ export type ImportBinding = { imported: string; local: string };
43
+ export type ImportClause = { bindings: ImportBinding[]; namespace: string | null };
44
+
45
+ const IDENTIFIER = String.raw`[\p{ID_Start}$_][\p{ID_Continue}$‌‍]*`;
46
+ const MODULE_NAME = String.raw`(?:${IDENTIFIER}|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')`;
47
+ const DEFAULT_BINDING = new RegExp(String.raw`^(${IDENTIFIER})\s*(?:,\s*|$)`, "u");
48
+ const NAMESPACE_BINDING = new RegExp(String.raw`^\*\s*as\s+(${IDENTIFIER})$`, "u");
49
+ const NAMED_BINDING = new RegExp(String.raw`^(${MODULE_NAME})(?:\s+as\s+(${MODULE_NAME}))?$`, "u");
50
+ const PLAIN_NAME = new RegExp(String.raw`^${IDENTIFIER}$`, "u");
51
+
52
+ function unquote(name: string): string {
53
+ if (name.startsWith('"')) return JSON.parse(name) as string;
54
+ if (name.startsWith("'")) {
55
+ let json = '"';
56
+ for (let i = 1; i < name.length - 1; i += 1) {
57
+ const char = name[i]!;
58
+ if (char === "\\") {
59
+ const escaped = name[++i]!;
60
+ json += escaped === "'" ? "'" : `\\${escaped}`;
61
+ } else json += char === '"' ? '\\"' : char;
62
+ }
63
+ return JSON.parse(`${json}"`) as string;
64
+ }
65
+ return name;
66
+ }
67
+
68
+ function nameText(name: string): string {
69
+ return PLAIN_NAME.test(name) ? name : JSON.stringify(name);
70
+ }
71
+
72
+ function bindingText({ imported, local }: ImportBinding): string {
73
+ return imported === local ? nameText(local) : `${nameText(imported)} as ${nameText(local)}`;
74
+ }
75
+
76
+ /**
77
+ * Parses the bindings between `import` (or `export`) and `from`. Returns null for anything it does not fully
78
+ * understand, comments included, so the caller leaves that statement as written.
79
+ */
80
+ export function parseClause(text: string): ImportClause | null {
81
+ if (/\/[/*]/.test(text)) return null;
82
+ let rest = text.trim();
83
+ const clause: ImportClause = { bindings: [], namespace: null };
84
+ const defaultBinding = DEFAULT_BINDING.exec(rest);
85
+ if (defaultBinding?.[1]) {
86
+ clause.bindings.push({ imported: "default", local: defaultBinding[1] });
87
+ rest = rest.slice(defaultBinding[0].length);
88
+ if (rest === "") return clause;
89
+ }
90
+ const namespace = NAMESPACE_BINDING.exec(rest);
91
+ if (namespace?.[1]) return { ...clause, namespace: namespace[1] };
92
+ const named = /^\{([^}]*)\}$/.exec(rest);
93
+ if (!named) return null;
94
+ for (const part of (named[1] ?? "").split(",")) {
95
+ const item = part.trim();
96
+ if (item === "") continue;
97
+ const match = NAMED_BINDING.exec(item);
98
+ if (!match?.[1]) return null;
99
+ clause.bindings.push({ imported: unquote(match[1]), local: unquote(match[2] ?? match[1]) });
100
+ }
101
+ return clause;
102
+ }
103
+
104
+ export type TransformStats = {
105
+ /** Relative imports rewritten to the canonical URL of the file they mean. */
106
+ canonical: number;
107
+ /** Import and export-from statements rewritten from a barrel to defining modules. */
108
+ statements: number;
109
+ /** Bindings moved from a barrel to the module that defines them. */
110
+ rewritten: number;
111
+ /** Bindings left on the barrel: names it defines itself, or names outside its index. */
112
+ kept: number;
113
+ /** Barrel statements that cannot be split: namespace imports and `export *`. */
114
+ whole: number;
115
+ /** Barrel statements whose bindings the clause parser did not understand. */
116
+ unparsed: number;
117
+ };
118
+
119
+ export function emptyTransformStats(): TransformStats {
120
+ return { canonical: 0, statements: 0, rewritten: 0, kept: 0, whole: 0, unparsed: 0 };
121
+ }
122
+
123
+ export function addTransformStats(total: TransformStats, more: TransformStats): void {
124
+ for (const key of Object.keys(total) as Array<keyof TransformStats>) total[key] += more[key];
125
+ }
126
+
127
+ export type ModuleTransformOptions = {
128
+ /** The module's URL path: `/npm/<package-relative URL>` for package files, anything else for page files. */
129
+ url: string;
130
+ /** Whether a package-relative URL names a file the runtime serves. */
131
+ known: (packageUrl: string) => boolean;
132
+ /** Resolves a bare specifier through the page's import map, as the browser would from `referrer`. */
133
+ resolveBare: (specifier: string, referrer: string) => string | null;
134
+ barrels: BarrelIndex | null;
135
+ };
136
+
137
+ type Edit = { start: number; end: number; text: string };
138
+ type Target = { url: string | null; canonical: string | null };
139
+
140
+ function targetOf(specifier: string, options: ModuleTransformOptions): Target {
141
+ const kind = specifierKind(specifier);
142
+ if (kind === "bare") return { url: options.resolveBare(specifier, options.url), canonical: null };
143
+ if (kind !== "relative") return { url: null, canonical: null };
144
+ const path = new URL(specifier, `https://runtime.invalid${options.url}`).pathname;
145
+ if (!path.startsWith(NPM_PREFIX) || !options.url.startsWith(NPM_PREFIX)) return { url: path, canonical: null };
146
+ const resolved = path.slice(NPM_PREFIX.length);
147
+ const found = CANONICAL_CANDIDATES.map((suffix) => `${resolved}${suffix}`).find(options.known);
148
+ if (!found) return { url: path, canonical: null };
149
+ return { url: `${NPM_PREFIX}${found}`, canonical: found === resolved ? null : `${NPM_PREFIX}${found}` };
150
+ }
151
+
152
+ function specifierEdit(code: string, item: Import, specifier: string): Edit {
153
+ const quoted = /^['"`]/.test(code.slice(item.start, item.end));
154
+ return { start: item.start, end: item.end, text: quoted ? JSON.stringify(specifier) : specifier };
155
+ }
156
+
157
+ function rewriteStatement(
158
+ code: string,
159
+ item: StaticImport,
160
+ entries: Record<string, number | [number, string]>,
161
+ modules: string[],
162
+ specifier: string,
163
+ stats: TransformStats,
164
+ ): string | null {
165
+ if (item.attributes !== null || item.phase !== null || item.typeOnly) return null;
166
+ const head = code.slice(item.importStart, item.start - 1);
167
+ if (/^import\s*$/.test(head)) return null;
168
+ const statement = /^(import|export)\s*([\s\S]*?)\s*from\s*$/.exec(head);
169
+ const clause = statement ? parseClause(statement[2] ?? "") : null;
170
+ if (!statement || !clause) {
171
+ stats.unparsed += 1;
172
+ return null;
173
+ }
174
+ const keyword = statement[1] ?? "import";
175
+ if (keyword === "export" && clause.namespace) {
176
+ stats.whole += 1;
177
+ return null;
178
+ }
179
+ const groups = new Map<string, string[]>();
180
+ const kept: string[] = [];
181
+ for (const binding of clause.bindings) {
182
+ const entry = entries[binding.imported];
183
+ if (entry === undefined) {
184
+ kept.push(bindingText(binding));
185
+ continue;
186
+ }
187
+ const [position, name] = typeof entry === "number" ? [entry, binding.imported] : entry;
188
+ const module = modules[position];
189
+ if (module === undefined) throw new Error(`barrel index entry for ${binding.imported} points at missing module ${position}`);
190
+ groups.set(module, [...(groups.get(module) ?? []), bindingText({ imported: name, local: binding.local })]);
191
+ }
192
+ stats.kept += kept.length;
193
+ if (clause.namespace) stats.whole += 1;
194
+ if (groups.size === 0) return null;
195
+ const from = JSON.stringify(specifier);
196
+ const statements = [
197
+ ...(clause.namespace ? [`import * as ${clause.namespace} from ${from}`] : []),
198
+ ...(kept.length > 0 ? [`${keyword} { ${kept.join(", ")} } from ${from}`] : []),
199
+ ...[...groups].map(([module, names]) => `${keyword} { ${names.join(", ")} } from ${JSON.stringify(`${NPM_PREFIX}${module}`)}`),
200
+ ];
201
+ stats.statements += 1;
202
+ stats.rewritten += clause.bindings.length - kept.length;
203
+ return `${statements.join("; ")};`;
204
+ }
205
+
206
+ /**
207
+ * Rewrites a served module's imports: relative imports in package files that name no file become canonical URLs,
208
+ * and named imports from an indexed barrel move to the modules that define them. Everything else stays as written.
209
+ */
210
+ export function transformModule(code: string, options: ModuleTransformOptions): { code: string; stats: TransformStats } {
211
+ const stats = emptyTransformStats();
212
+ const [imports] = parse(code);
213
+ const edits: Edit[] = [];
214
+ for (const item of imports) {
215
+ if (item.type === "import-meta" || item.specifier === undefined || (item.type === "dynamic" && item.glob)) continue;
216
+ const target = targetOf(item.specifier, options);
217
+ const barrel = target.url?.startsWith(NPM_PREFIX) ? options.barrels?.barrels[target.url.slice(NPM_PREFIX.length)] : undefined;
218
+ if (barrel && options.barrels && item.type === "static") {
219
+ const statement = rewriteStatement(code, item, barrel, options.barrels.modules, target.canonical ?? item.specifier, stats);
220
+ if (statement !== null) {
221
+ edits.push({ start: item.importStart, end: item.importEnd, text: statement });
222
+ continue;
223
+ }
224
+ } else if (barrel && item.type === "reexport-star") stats.whole += 1;
225
+ if (target.canonical) {
226
+ edits.push(specifierEdit(code, item, target.canonical));
227
+ stats.canonical += 1;
228
+ }
229
+ }
230
+ edits.sort((a, b) => b.start - a.start);
231
+ let rewritten = code;
232
+ let limit = code.length;
233
+ for (const edit of edits) {
234
+ if (edit.end > limit) throw new Error(`${options.url}: overlapping import edits at ${edit.start}`);
235
+ rewritten = `${rewritten.slice(0, edit.start)}${edit.text}${rewritten.slice(edit.end)}`;
236
+ limit = edit.start;
237
+ }
238
+ return { code: rewritten, stats };
239
+ }
240
+
241
+ const NODE_ENV = "process.env.NODE_ENV";
242
+ const NODE_ENV_TAIL = ".env.NODE_ENV";
243
+ // After these words an expression starts, so a `/` begins a regular expression rather than a division.
244
+ const EXPRESSION_KEYWORDS = new Set(["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else", "yield", "await"]);
245
+ const IDENTIFIER_START = /[\p{ID_Start}$_\\]/u;
246
+ const IDENTIFIER_PART = /[\p{ID_Continue}$\\]|‌|‍/u;
247
+
248
+ function skipQuoted(code: string, start: number): number {
249
+ const quote = code[start];
250
+ for (let i = start + 1; i < code.length; i += 1) {
251
+ const char = code[i];
252
+ if (char === "\\") i += 1;
253
+ else if (char === quote) return i + 1;
254
+ else if (char === "\n") break;
255
+ }
256
+ throw new Error(`unterminated string at offset ${start}`);
257
+ }
258
+
259
+ function skipRegExp(code: string, start: number): number {
260
+ let inClass = false;
261
+ for (let i = start + 1; i < code.length; i += 1) {
262
+ const char = code[i];
263
+ if (char === "\\") i += 1;
264
+ else if (char === "[") inClass = true;
265
+ else if (char === "]") inClass = false;
266
+ else if (char === "/" && !inClass) {
267
+ let end = i + 1;
268
+ while (end < code.length && /[a-z]/i.test(code[end] ?? "")) end += 1;
269
+ return end;
270
+ } else if (char === "\n") break;
271
+ }
272
+ throw new Error(`unterminated regular expression at offset ${start}`);
273
+ }
274
+
275
+ /** Scans template text from `start` to its closing backtick or its next `${`. */
276
+ function scanTemplate(code: string, start: number): { end: number; opened: boolean } {
277
+ for (let i = start; i < code.length; i += 1) {
278
+ const char = code[i];
279
+ if (char === "\\") i += 1;
280
+ else if (char === "`") return { end: i + 1, opened: false };
281
+ else if (char === "$" && code[i + 1] === "{") return { end: i + 2, opened: true };
282
+ }
283
+ throw new Error(`unterminated template literal at offset ${start}`);
284
+ }
285
+
286
+ function precededByDot(code: string, start: number): boolean {
287
+ let i = start - 1;
288
+ while (i >= 0 && /\s/.test(code[i] ?? "")) i -= 1;
289
+ return code[i] === "." && code[i - 1] !== ".";
290
+ }
291
+
292
+ /**
293
+ * Offsets of `process.env.NODE_ENV` references, skipping comments, strings, template text and regular expressions.
294
+ * A lexer, not a parser: the harness checks it against oxc's AST on every file of the library set.
295
+ */
296
+ export function nodeEnvReferences(code: string): number[] {
297
+ const found: number[] = [];
298
+ const templates: number[] = [];
299
+ let depth = 0;
300
+ let regExpAllowed = true;
301
+ let i = 0;
302
+ while (i < code.length) {
303
+ const char = code[i] ?? "";
304
+ if (/\s/.test(char)) {
305
+ i += 1;
306
+ } else if (char === "/" && code[i + 1] === "/") {
307
+ const end = code.indexOf("\n", i);
308
+ i = end === -1 ? code.length : end;
309
+ } else if (char === "/" && code[i + 1] === "*") {
310
+ const end = code.indexOf("*/", i + 2);
311
+ if (end === -1) throw new Error(`unterminated comment at offset ${i}`);
312
+ i = end + 2;
313
+ } else if (char === "/") {
314
+ i = regExpAllowed ? skipRegExp(code, i) : i + 1;
315
+ regExpAllowed = !regExpAllowed;
316
+ } else if (char === "'" || char === '"') {
317
+ i = skipQuoted(code, i);
318
+ regExpAllowed = false;
319
+ } else if (char === "`" || (char === "}" && templates.at(-1) === depth - 1 && templates.length > 0)) {
320
+ if (char === "}") {
321
+ templates.pop();
322
+ depth -= 1;
323
+ }
324
+ const scanned = scanTemplate(code, i + 1);
325
+ i = scanned.end;
326
+ regExpAllowed = scanned.opened;
327
+ if (scanned.opened) {
328
+ templates.push(depth);
329
+ depth += 1;
330
+ }
331
+ } else if (char === "{" || char === "}") {
332
+ depth += char === "{" ? 1 : -1;
333
+ i += 1;
334
+ regExpAllowed = true;
335
+ } else if (IDENTIFIER_START.test(char)) {
336
+ const start = i;
337
+ i += 1;
338
+ while (i < code.length && IDENTIFIER_PART.test(code[i] ?? "")) i += 1;
339
+ const word = code.slice(start, i);
340
+ const reference = word === "process" && code.startsWith(NODE_ENV_TAIL, i) && !IDENTIFIER_PART.test(code[i + NODE_ENV_TAIL.length] ?? "");
341
+ if (reference && !precededByDot(code, start)) {
342
+ found.push(start);
343
+ i += NODE_ENV_TAIL.length;
344
+ regExpAllowed = false;
345
+ } else regExpAllowed = EXPRESSION_KEYWORDS.has(word);
346
+ } else if (/[0-9]/.test(char) || (char === "." && /[0-9]/.test(code[i + 1] ?? ""))) {
347
+ while (i < code.length && /[\w.]/.test(code[i] ?? "")) i += 1;
348
+ regExpAllowed = false;
349
+ } else {
350
+ i += 1;
351
+ regExpAllowed = char !== ")" && char !== "]";
352
+ }
353
+ }
354
+ return found;
355
+ }
356
+
357
+ /** Defines `process.env.NODE_ENV` as development in every served package. */
358
+ export function defineNodeEnv(code: string): { code: string; replaced: number } {
359
+ if (!code.includes(NODE_ENV)) return { code, replaced: 0 };
360
+ const references = nodeEnvReferences(code);
361
+ let defined = code;
362
+ for (const start of [...references].reverse()) defined = `${defined.slice(0, start)}${JSON.stringify("development")}${defined.slice(start + NODE_ENV.length)}`;
363
+ return { code: defined, replaced: references.length };
364
+ }
@@ -0,0 +1,45 @@
1
+ import { LINK_CONTEXT_HEADER } from "./link-route.ts";
2
+
3
+ type Client = { id: string; url: string };
4
+ type Clients<C extends Client> = { get(id: string): Promise<C | undefined>; matchAll(options: { type: "all"; includeUncontrolled: boolean }): Promise<{ id: string }[]> };
5
+ type PageClient = { page: string; context: string | null };
6
+ export type PageFetchEvent = { request: Request; clientId: string; resultingClientId: string };
7
+
8
+ // Module URLs name no page, so each request's page and link context come from the client that made it:
9
+ // frames are recorded when their document is served, and workers inherit the client that created them.
10
+ // After a worker restart, a client falls back to the page in its URL and its link context is recomputed.
11
+ export function createPageClients<C extends Client>(options: { origin: string; clients: Clients<C> }) {
12
+ const known = new Map<string, PageClient>();
13
+ const fromUrl = (client: Client): PageClient | undefined => {
14
+ const location = new URL(client.url);
15
+ const page = location.searchParams.get("page") ?? (location.pathname.startsWith("/frame/") ? decodeURIComponent(location.pathname.slice(7)) : null);
16
+ return page ? { page, context: null } : undefined;
17
+ };
18
+ async function remember(id: string, client: PageClient): Promise<void> {
19
+ known.set(id, client);
20
+ const live = new Set((await options.clients.matchAll({ type: "all", includeUncontrolled: true })).map((item) => item.id));
21
+ for (const previous of known.keys()) if (previous !== id && !live.has(previous)) known.delete(previous);
22
+ }
23
+ return {
24
+ /** The request with the page and link context of the client that made it. */
25
+ async request(event: PageFetchEvent): Promise<{ request: Request; client: C | undefined; owner: PageClient | undefined }> {
26
+ const url = new URL(event.request.url);
27
+ const client = event.clientId ? await options.clients.get(event.clientId) : undefined;
28
+ const owner = client ? known.get(client.id) ?? fromUrl(client) : undefined;
29
+ if (["GET", "HEAD"].includes(event.request.method) && url.origin === options.origin && /^\/(src|npm|esm|link|__runtime)\//.test(url.pathname) && owner) {
30
+ if (!url.searchParams.has("page")) url.searchParams.set("page", owner.page);
31
+ if (owner.context && !url.searchParams.has("link-context")) url.searchParams.set("link-context", owner.context);
32
+ }
33
+ const request = url.href === event.request.url ? event.request : new Request(url, { method: event.request.method, headers: event.request.headers, credentials: event.request.credentials, mode: "same-origin" });
34
+ return { request, client, owner };
35
+ },
36
+ /** Records the client a frame document or page-spawned worker creates. */
37
+ async served(options_: { event: PageFetchEvent; owner: PageClient | undefined; response: Response }): Promise<void> {
38
+ const { event, owner, response } = options_;
39
+ if (!event.resultingClientId) return;
40
+ const url = new URL(event.request.url);
41
+ if (url.pathname.startsWith("/frame/")) await remember(event.resultingClientId, { page: decodeURIComponent(url.pathname.slice(7)), context: response.headers.get(LINK_CONTEXT_HEADER) });
42
+ else if (owner && ["worker", "sharedworker"].includes(event.request.destination)) await remember(event.resultingClientId, owner);
43
+ },
44
+ };
45
+ }
@@ -0,0 +1,90 @@
1
+ import type { RuntimePolicy, RuntimeProfile } from "../schema.ts";
2
+ import { validateVersionRange } from "./versions.ts";
3
+
4
+ export function validateDependencies(value: unknown, path = "dependencies"): Record<string, string> {
5
+ const dependencies = record(value, path);
6
+ for (const [name, version] of Object.entries(dependencies)) {
7
+ if (!/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(name) || typeof version !== "string") throw new Error(`${path}.${name}: expected package name and version range`);
8
+ validateVersionRange(version);
9
+ }
10
+ return dependencies as Record<string, string>;
11
+ }
12
+
13
+ export function record(value: unknown, path: string): Record<string, unknown> {
14
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${path}: expected an object`);
15
+ return value as Record<string, unknown>;
16
+ }
17
+
18
+ export function keys(value: Record<string, unknown>, allowed: string[], path: string): void {
19
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new Error(`${path}.${key}: unknown key`);
20
+ }
21
+
22
+ function strings(value: unknown, path: string): asserts value is string[] {
23
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string" || !item)) throw new Error(`${path}: expected strings`);
24
+ }
25
+
26
+ function choice(value: unknown, allowed: string[], path: string): void {
27
+ if (typeof value !== "string" || !allowed.includes(value)) throw new Error(`${path}: expected ${allowed.join(" | ")}`);
28
+ }
29
+
30
+ function url(value: unknown, path: string, originOnly = false): void {
31
+ if (typeof value !== "string") throw new Error(`${path}: expected URL`);
32
+ const parsed = new URL(value);
33
+ if (!["https:", "http:"].includes(parsed.protocol) || parsed.username || parsed.password || (originOnly && parsed.origin !== value)) throw new Error(`${path}: invalid URL ${value}`);
34
+ }
35
+
36
+ export function validateProfile(value: unknown): RuntimeProfile {
37
+ const p = record(value, "profile");
38
+ keys(p, ["runtimeDomain", "embedders", "packageOrigin", "registry", "managed", "dependencies", "runtimeExports", "policy", "convert", "minReleaseAgeDays", "network", "csp", "links", "sources", "readinessTimeoutMs", "renderJobs"], "profile");
39
+ if (p.renderJobs !== undefined && p.renderJobs !== true) throw new Error("profile.renderJobs: expected true");
40
+ if (typeof p.runtimeDomain !== "string" || !/^[a-z0-9.-]+(?::\d+)?$/i.test(p.runtimeDomain)) throw new Error("profile.runtimeDomain: invalid domain");
41
+ url(p.packageOrigin, "packageOrigin");
42
+ url(p.registry, "registry");
43
+ strings(p.embedders, "embedders");
44
+ p.embedders.forEach((v) => url(v, "embedders", true));
45
+ const managed = record(p.managed, "managed");
46
+ for (const [name, range] of Object.entries(managed)) if (!name || typeof range !== "string" || !range.trim()) throw new Error(`managed.${name}: expected range`);
47
+ if (p.dependencies !== undefined) validateDependencies(p.dependencies, "profile.dependencies");
48
+ if (p.runtimeExports !== undefined && p.runtimeExports !== true) throw new Error("profile.runtimeExports: expected true");
49
+ validatePolicy(p.policy);
50
+ if (p.convert !== undefined) {
51
+ const convert = record(p.convert, "convert");
52
+ keys(convert, ["origin"], "convert");
53
+ url(convert.origin, "convert.origin", true);
54
+ }
55
+ const network = record(p.network, "network");
56
+ keys(network, ["allow"], "network");
57
+ strings(network.allow, "network.allow");
58
+ network.allow.forEach((v) => url(v.replaceAll("*", "x"), "network.allow"));
59
+ const csp = record(p.csp, "csp");
60
+ keys(csp, ["add", "wasm"], "csp");
61
+ if (csp.wasm !== undefined && typeof csp.wasm !== "boolean") throw new Error("csp.wasm: expected boolean");
62
+ for (const [directive, sources] of Object.entries(record(csp.add, "csp.add"))) {
63
+ if (!/^[a-z]+(?:-[a-z]+)*$/.test(directive)) throw new Error(`csp.add: invalid directive ${directive}`);
64
+ strings(sources, `csp.add.${directive}`);
65
+ if (sources.some((v) => /[;\r\n]/.test(v))) throw new Error(`csp.add.${directive}: invalid source`);
66
+ }
67
+ choice(p.links, ["allow", "deny"], "links");
68
+ strings(p.sources, "sources");
69
+ p.sources.forEach((v) => choice(v, ["host", "opfs", "folder", "url", "hash"], "sources"));
70
+ for (const name of ["minReleaseAgeDays", "readinessTimeoutMs"] as const) {
71
+ const n = p[name];
72
+ if (typeof n !== "number" || !Number.isFinite(n) || n < (name === "readinessTimeoutMs" ? 1 : 0)) throw new Error(`${name}: invalid duration`);
73
+ }
74
+ return p as RuntimeProfile;
75
+ }
76
+
77
+ export function validatePolicy(value: unknown, path = "policy"): RuntimePolicy {
78
+ const policy = record(value, path);
79
+ keys(policy, ["dependencies", "allow"], path);
80
+ choice(policy.dependencies, ["any", "ask", "strict"], `${path}.dependencies`);
81
+ if (policy.allow !== undefined) {
82
+ strings(policy.allow, `${path}.allow`);
83
+ if (policy.dependencies === "any") throw new Error(`${path}.allow contradicts dependencies any`);
84
+ }
85
+ return policy as RuntimePolicy;
86
+ }
87
+
88
+ export function permitsNetwork(profile: RuntimeProfile, target: string): boolean {
89
+ return profile.network.allow.some((pattern) => new RegExp(`^${pattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`).test(target));
90
+ }