@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,80 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { lstat, mkdir, mkdtemp, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
4
+ import { dirname, resolve, sep } from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { readManifest } from "./manifest.ts";
7
+ import { validateRuntime } from "./runtime.ts";
8
+ import { BUILD_ID, type PackageBuild } from "./schema.ts";
9
+ import { withPackageLock } from "./lock.ts";
10
+
11
+ export type Publication = PackageBuild & { directory: string };
12
+ export const publicationRoot = (libraryDir: string): string => resolve(libraryDir, ".tmp/package-publications");
13
+ export async function atomicJson(file: string, value: unknown): Promise<void> {
14
+ await mkdir(dirname(file), { recursive: true });
15
+ const temporary = `${file}.${randomUUID()}`;
16
+ try { await writeFile(temporary, JSON.stringify(value)); await rename(temporary, file); }
17
+ finally { await rm(temporary, { force: true }); }
18
+ }
19
+ export async function readPublication(libraryDir: string): Promise<Publication> {
20
+ const root = publicationRoot(libraryDir);
21
+ const current = JSON.parse(await readFile(resolve(root, "current.json"), "utf8")) as PackageBuild;
22
+ if (typeof current.build !== "string" || !BUILD_ID.test(current.build)) throw new Error(`${libraryDir}: invalid published build`);
23
+ const directory = await realpath(resolve(root, "generations", current.build, "package"));
24
+ const manifest = await readManifest(directory);
25
+ if (manifest.name !== current.name || manifest.version !== current.version) throw new Error(`${libraryDir}: publication identity mismatch`);
26
+ return { ...current, directory };
27
+ }
28
+
29
+ async function copyPublishable(libraryDir: string, directory: string): Promise<string[]> {
30
+ const archive = resolve(directory, "..", "package.tgz");
31
+ const { stdout } = await promisify(execFile)("pnpm", ["--config.ignoreScripts=true", "pack", "--json", "--out", archive], { cwd: libraryDir, env: process.env, maxBuffer: 16 * 1024 * 1024 });
32
+ const packed = JSON.parse(stdout) as { files: { path: string }[] };
33
+ if (!Array.isArray(packed.files) || !packed.files.length) throw new Error(`${libraryDir}: native package file list is empty`);
34
+ const files = packed.files.map(file => file.path).sort();
35
+ for (const path of files) {
36
+ if (typeof path !== "string" || path.startsWith("/") || path.split(/[\\/]/).includes("..")) throw new Error(`Invalid publishable path: ${path}`);
37
+ }
38
+ const listed = await promisify(execFile)("tar", ["-tzf", archive], { maxBuffer: 16 * 1024 * 1024 });
39
+ for (const path of listed.stdout.trim().split("\n")) if (!path.startsWith("package/") || path.split("/").includes("..")) throw new Error(`Invalid archive path: ${path}`);
40
+ await promisify(execFile)("tar", ["-xzf", archive, "-C", dirname(directory)]);
41
+ await rm(archive);
42
+ for (const path of files) {
43
+ const file = resolve(directory, path);
44
+ if (!(await lstat(file)).isFile() || !(await realpath(file)).startsWith(`${directory}${sep}`)) throw new Error(`Invalid published file: ${path}`);
45
+ }
46
+ return files;
47
+ }
48
+
49
+ function exportedPaths(value: unknown): string[] {
50
+ if (typeof value === "string") return value.startsWith("./") && !value.includes("*") ? [value.slice(2)] : [];
51
+ return value && typeof value === "object" ? Object.values(value).flatMap(exportedPaths) : [];
52
+ }
53
+
54
+ export async function publishPackage(options: { libraryDir: string }): Promise<Publication> {
55
+ return withPackageLock({ ...options, run: () => createPublication(options) });
56
+ }
57
+
58
+ export async function createPublication(options: { libraryDir: string }): Promise<Publication> {
59
+ const libraryDir = await realpath(options.libraryDir);
60
+ const root = publicationRoot(libraryDir);
61
+ await mkdir(resolve(root, "generations"), { recursive: true });
62
+ const staging = await realpath(await mkdtemp(resolve(root, "staging-")));
63
+ const directory = resolve(staging, "package");
64
+ try {
65
+ const files = await copyPublishable(libraryDir, directory);
66
+ const manifest = await readManifest(directory);
67
+ for (const path of exportedPaths(manifest.exports)) if (!files.includes(path)) throw new Error(`${manifest.name}: missing exported file ${path}`);
68
+ await validateRuntime({ directory, manifest, files: new Set(files) });
69
+ const hash = createHash("sha256");
70
+ for (const path of files) hash.update(JSON.stringify([path, createHash("sha256").update(await readFile(resolve(directory, path))).digest("hex")]));
71
+ const build = hash.digest("hex");
72
+ const entry = { name: manifest.name, version: manifest.version, build };
73
+ await writeFile(resolve(staging, "publication.json"), JSON.stringify(entry));
74
+ try { await rename(staging, resolve(root, "generations", build)); }
75
+ catch (error) { if (!["ENOTEMPTY", "EEXIST"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error; }
76
+ await atomicJson(resolve(root, "current.json"), entry);
77
+ return { ...entry, directory: await realpath(resolve(root, "generations", build, "package")) };
78
+ } finally { await rm(staging, { recursive: true, force: true }); }
79
+ }
80
+
@@ -0,0 +1,28 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import { resolve } from "node:path";
4
+ import type { BarrelIndex, Fragment } from "../schema.ts";
5
+ import type { PackageManifest } from "./manifest.ts";
6
+
7
+ export async function validateRuntime(options: { directory: string; manifest: PackageManifest; files: Set<string> }): Promise<void> {
8
+ const { directory, manifest, files } = options;
9
+ const expected = manifest.exports !== undefined && JSON.stringify(manifest.exports).includes("dist/runtime/");
10
+ if (!expected && !files.has("dist/runtime/importmap.json")) return;
11
+ if (!files.has("dist/runtime/importmap.json") || !files.has("dist/runtime/barrels.json")) throw new Error(`${manifest.name}: runtime importmap.json and barrels.json must both exist`);
12
+ const fragment = JSON.parse(await readFile(resolve(directory, "dist/runtime/importmap.json"), "utf8")) as Fragment;
13
+ const barrels = JSON.parse(await readFile(resolve(directory, "dist/runtime/barrels.json"), "utf8")) as BarrelIndex;
14
+ if (fragment.fragment !== 1 || fragment.name !== manifest.name || !fragment.integrity || !fragment.imports || !fragment.scopes || !fragment.remaps || !fragment.aliases || !Array.isArray(fragment.inherits)) throw new Error(`${manifest.name}: invalid runtime fragment`);
15
+ if (!Array.isArray(barrels.modules) || barrels.modules.some(value => typeof value !== "string") || !barrels.barrels || typeof barrels.barrels !== "object") throw new Error(`${manifest.name}: invalid barrel index`);
16
+ for (const table of Object.values(barrels.barrels)) for (const value of Object.values(table)) {
17
+ const index = Array.isArray(value) ? value[0] : value;
18
+ if (!Number.isInteger(index) || index < 0 || index >= barrels.modules.length) throw new Error(`${manifest.name}: invalid barrel module index`);
19
+ }
20
+ const prefix = `${manifest.name}@${manifest.version}/`;
21
+ for (const [url, integrity] of Object.entries(fragment.integrity)) {
22
+ if (!url.startsWith(prefix)) continue;
23
+ const path = url.slice(prefix.length);
24
+ if (!files.has(path)) throw new Error(`${manifest.name}: missing integrity file ${path}`);
25
+ const hash = `sha384-${createHash("sha384").update(await readFile(resolve(directory, path))).digest("base64")}`;
26
+ if (hash !== integrity) throw new Error(`${manifest.name}: integrity mismatch for ${path}`);
27
+ }
28
+ }
@@ -0,0 +1,13 @@
1
+ export type PackageBuild = { name: string; version: string; build: string };
2
+ export type PackageCatalog = { revision: string; packages: Record<string, PackageBuild> };
3
+ export const BUILD_ID = /^[a-f0-9]{64}$/;
4
+
5
+ export function validateCatalog(value: unknown): PackageCatalog {
6
+ if (!value || typeof value !== "object") throw new Error("Invalid package catalog");
7
+ const catalog = value as PackageCatalog;
8
+ if (!BUILD_ID.test(catalog.revision) || !catalog.packages || typeof catalog.packages !== "object" || Array.isArray(catalog.packages)) throw new Error("Invalid package catalog revision or packages");
9
+ for (const [name, entry] of Object.entries(catalog.packages)) {
10
+ if (!entry || entry.name !== name || typeof entry.version !== "string" || !BUILD_ID.test(entry.build)) throw new Error(`Invalid package catalog entry ${name}`);
11
+ }
12
+ return catalog;
13
+ }
@@ -0,0 +1,17 @@
1
+ import type { AgentSelection } from "./schema.ts";
2
+
3
+ export type ReviewAction = "mark" | "approved" | "rejected" | "revision_requested" | "delete" | "export";
4
+ export type ReviewElement = { id: string; selection: AgentSelection; domId?: string };
5
+ export type ReviewContent = { html: string; svg?: string };
6
+ export type ReviewHostMessage =
7
+ | { type: "review-remove"; requestId: string; id: string; removed: boolean }
8
+ | { type: "review-list"; requestId: string }
9
+ | { type: "review-select"; requestId: string; id: string | null }
10
+ | { type: "review-visibility"; requestId: string; visible: boolean; showRejected: boolean }
11
+ | { type: "review-action"; requestId: string; id: string; action: ReviewAction };
12
+ export type ReviewState = { type: "review-state"; requestId?: string; elements: ReviewElement[]; selected: string | null; visible: boolean; showRejected: boolean };
13
+ export type ReviewActionRequest = { type: "review-action-request"; requestId: string; element: ReviewElement } & (
14
+ | { action: "delete"; containedAnchors: string[]; content?: never }
15
+ | { action: Exclude<ReviewAction, "delete">; content?: ReviewContent; containedAnchors?: never }
16
+ );
17
+ export type ReviewFrameMessage = ReviewState | ReviewActionRequest | { type: "review-error"; requestId: string; error: string };
package/src/schema.ts ADDED
@@ -0,0 +1,175 @@
1
+ // Contracts shared across @flanksource/page-runtime: what a library build publishes (src/build) and what the service
2
+ // worker, frame and host read (src/sw, src/frame, src/host). Each slice extends this file only through the owner named
3
+ // in the plan's Execution section.
4
+
5
+ export type PageStylesRecipe = {
6
+ name: string;
7
+ layer: string;
8
+ /** Published precompiled stylesheet specifiers, linked on every page in library order. */
9
+ base: string[];
10
+ /** Compiler inputs only (theme, utilities, `@config`/`@plugin`, `@theme`); it must not import any `base` stylesheet. */
11
+ entry: string;
12
+ theme: string;
13
+ /** Package specifiers or recipe-relative files loaded by the CSS compiler outside the JS import graph. */
14
+ runtimeDependencies: string[];
15
+ /** Managed libraries whose preset this one extends: only the most-derived recipe is compiled, every base is linked. */
16
+ extends?: string[];
17
+ transform?: (css: string) => string;
18
+ };
19
+
20
+ /** What a library publishes as `runtime/importmap.json`: its closure as package-relative import-map entries. */
21
+ export type Fragment = {
22
+ fragment: 1;
23
+ name: string;
24
+ /** Top-level specifiers, including the shared development runtime set. */
25
+ imports: Record<string, string>;
26
+ /** One scope per package version: the bare imports that package's files make. */
27
+ scopes: Record<string, Record<string, string>>;
28
+ /** URL remaps for CommonJS files that ESM code imports by a relative path: file URL to converted URL. */
29
+ remaps: Record<string, string>;
30
+ /** Page-facing specifier prefixes that stand for another prefix, such as facet's `@facet`. */
31
+ aliases: Record<string, string>;
32
+ /** Specifiers the closure imports but leaves to another fragment's top level. */
33
+ inherits: string[];
34
+ /** Subresource integrity for every traced and converted file, by package-relative URL. */
35
+ integrity: Record<string, string>;
36
+ /** Compiler plugins the library contributes to HTML and PDF exports, declared in package.json `pageRuntime.compiler`. */
37
+ compiler?: CompilerPlugins;
38
+ };
39
+
40
+ /** A remark plugin: a module the library exports, whose default export is the plugin, with the options it is applied with. */
41
+ export type CompilerPlugin = { module: string; options?: JsonValue };
42
+ export type CompilerPlugins = { remark: CompilerPlugin[] };
43
+
44
+ export type ImportMap ={ imports: Record<string, string>; scopes: Record<string, Record<string, string>> };
45
+
46
+ export type DocumentSource = {
47
+ page: string;
48
+ layout: string;
49
+ files: Record<string, { text: string } | { base64: string }>;
50
+ dependencies: Record<string, string>;
51
+ managed: Record<string, string>;
52
+ profileUrl?: string;
53
+ dynamicStyles?: boolean;
54
+ };
55
+
56
+ /**
57
+ * A library's barrel export index, published as `runtime/barrels.json`: for each entry barrel, the defining module of
58
+ * every named export (`modules[pos]`, or `[pos, importName]` when the name is re-exported under another one).
59
+ */
60
+ export type BarrelIndex = {
61
+ modules: string[];
62
+ barrels: Record<string, Record<string, number | [number, string]>>;
63
+ };
64
+
65
+ export type DependencyPolicy = "any" | "ask" | "strict";
66
+ export type RuntimePolicy = { dependencies: DependencyPolicy; allow?: string[] };
67
+
68
+ export type RuntimeExports = Pick<Fragment, "imports" | "scopes" | "remaps" | "integrity"> & { versions: Record<string, string> };
69
+
70
+ export type RuntimeProfile = {
71
+ renderJobs?: true;
72
+ runtimeDomain: string;
73
+ embedders: string[];
74
+ packageOrigin: string;
75
+ registry: string;
76
+ managed: Record<string, string>;
77
+ dependencies?: Record<string, string>;
78
+ runtimeExports?: true;
79
+ /** `any` allows every declared package; `ask` and `strict` allow only the names (or `*` globs) in `allow`. */
80
+ policy: RuntimePolicy;
81
+ /** CommonJS-to-ESM converter for packages without ESM entries; also added to `connect-src`. */
82
+ convert?: { origin: string };
83
+ minReleaseAgeDays: number;
84
+ network: { allow: string[] };
85
+ /** `wasm` lets frames compile WebAssembly (`'wasm-unsafe-eval'`); off by default, and it never enables JS `eval`. */
86
+ csp: { add: Record<string, string[]>; wasm?: boolean };
87
+ links: "allow" | "deny";
88
+ sources: Array<"host" | "opfs" | "folder" | "url" | "hash">;
89
+ readinessTimeoutMs: number;
90
+ };
91
+
92
+ export type PageLock = {
93
+ lock: 2;
94
+ packageOrigin: string;
95
+ page: string;
96
+ versions: Record<string, string>;
97
+ map: ImportMap;
98
+ integrity: Record<string, string>;
99
+ remaps: Record<string, string>;
100
+ barrels: BarrelIndex;
101
+ listings?: Record<string, string>;
102
+ pageSources?: import("./link/page-sources.ts").PageSourceRoot[];
103
+ /** Each library's export compiler plugins, in library order. */
104
+ compiler?: Record<string, CompilerPlugins>;
105
+ };
106
+
107
+ export type FolderManifest = {
108
+ dependencies: Record<string, string>;
109
+ pageRuntime?: { pages?: Record<string, Record<string, string>> };
110
+ };
111
+
112
+ export type RuntimePhase = "resolve" | "fetch" | "compile" | "link" | "render" | "readiness";
113
+ export type RuntimeError = { phase: RuntimePhase; message: string; file: string; line?: number; column?: number };
114
+ export type Theme = { theme: "light" | "dark"; density: "compact" | "comfortable" | "spacious" };
115
+ export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };
116
+ export type SourceProvider = { url: string; paths: string[] };
117
+ export type HostMessage =
118
+ | AgentHostMessage
119
+ | { type: "open"; page: string; layout?: string; manifest: FolderManifest; lock?: PageLock; files: Record<string, string>; sourceProvider?: SourceProvider; policy?: RuntimePolicy }
120
+ | { type: "prepare-render"; open: OpenMessage }
121
+ | { type: "render"; data: JsonValue }
122
+ | { type: "sources"; files: Record<string, string | null>; data?: JsonValue }
123
+ | { type: "reload" }
124
+ | ({ type: "theme" } & Theme)
125
+ | { type: "data"; data: JsonValue }
126
+ | { type: "export"; format: "html" | "print" };
127
+ /** The `open` host message without its `type`: what `PageFrame` takes as `open` and what `formPageOpen` builds. */
128
+ export type OpenMessage = Omit<Extract<HostMessage, { type: "open" }>, "type">;
129
+ export type FrameMessage =
130
+ | import("./activity-schema.ts").ActivityMessage
131
+ | AgentFrameMessage
132
+ | { type: "lock"; lock: PageLock }
133
+ | { type: "status"; state: "connecting" | "booting" | "mounted" | "fonts" | "images" | "stylesheets" | "diagrams" | "hook" | "quiescence" | "ready" }
134
+ | { type: "error"; error: RuntimeError }
135
+ | { type: "snapshot"; html: string }
136
+ | { type: "prepared-render"; lock: PageLock; navigate: boolean; runtimeVersion: string }
137
+ | { type: "rendered"; html: string; modulesMs: number; readinessMs: number; snapshotMs: number }
138
+ /** A page-defined event with a JSON payload, sent through `host.emit` (see `PageHost`). */
139
+ | { type: "emit"; event: string; payload: JsonValue }
140
+ /** The rendered height of the page root in CSS pixels, sent whenever it changes. */
141
+ | { type: "size"; height: number };
142
+ /** What the runtime gives a page component next to its data: the page-to-host half of the bridge. */
143
+ export type PageHost = { emit(event: string, payload: JsonValue): void };
144
+ export type BridgeEnvelope<M = HostMessage | FrameMessage> = { bridge: "page-runtime-v1"; session: string; id?: string; re?: string; message: M };
145
+
146
+ export type FrameConfig = { page: string; entry: string; layout?: string; lock: PageLock; profile: RuntimeProfile; runtimeVersion: string };
147
+
148
+ export type AgentRect = { left: number; top: number; width: number; height: number };
149
+ export type AgentLocator = import("@flanksource/clicky-ui/comments").CommentLocator;
150
+ export type AgentSourceContext = { mode: "external-document"; url: string };
151
+ export type AgentElementContext = { source: string; sourceContext?: AgentSourceContext; componentName: string; html: string; locators: AgentLocator[] };
152
+ export type AgentSelection = { anchor: string; label: string; element: AgentElementContext; rect: AgentRect };
153
+ export type AgentPin = { anchor: string; count: number; locators: AgentLocator[] };
154
+ export type AgentAnchorState = { anchor: string; state: "found" | "moved" | "orphaned"; label: string; rect: AgentRect | null };
155
+ export type AgentHostMessage =
156
+ | import("./review-schema.ts").ReviewHostMessage
157
+ | import("./design-schema.ts").DesignHostMessage
158
+ | { type: "mode"; mode: "off" | "comment" | "design" }
159
+ | { type: "pick" }
160
+ | { type: "page" }
161
+ | { type: "capture-vocabulary" }
162
+ | { type: "pins"; anchors: AgentPin[]; focus?: string | null }
163
+ | { type: "highlight"; anchor: string | null }
164
+ | { type: "scroll"; anchor: string; behavior?: ScrollBehavior; block?: "start" | "center"; offset?: number };
165
+ export type AgentFrameMessage =
166
+ | import("./review-schema.ts").ReviewFrameMessage
167
+ | import("./design-schema.ts").DesignFrameMessage
168
+ | { type: "selection"; selection: AgentSelection }
169
+ | { type: "vocabulary-previews"; images: { id: string; image: string; width: number; height: number }[] }
170
+ | { type: "anchors"; anchors: AgentAnchorState[] }
171
+ | { type: "focus"; anchor: string }
172
+ | { type: "keys"; key: "Escape" | "c"; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean; altKey: boolean }
173
+ | { type: "geometry"; scrollX: number; scrollY: number; width: number; height: number };
174
+
175
+ export type { DesignEdit, DesignWriteRequest, DesignWriteCandidate, DesignWriteResult, DesignHostMessage, DesignFrameMessage } from "./design-schema.ts";
@@ -0,0 +1,64 @@
1
+ export const RUNTIME_DB = "page-runtime";
2
+ const RUNTIME_DB_VERSION = 1;
3
+ export const TAILWIND_ROUTE = "/__runtime/tailwind/";
4
+ export const tailwindCacheName = (version: string) => `page-runtime-${version}-tailwind`;
5
+
6
+ /** The classes one module of a page contributes. `module` is the module's request path. */
7
+ export type CandidatesRecord = { page: string; module: string; sourceHash: string; candidates: string[] };
8
+ /**
9
+ * Metadata for one generated stylesheet, which lives in Cache Storage at `url`. `candidates` are the sorted source
10
+ * classes its `key` was derived from; `domClasses` are classes the page's DOM added afterwards.
11
+ */
12
+ export type TailwindRecord = { key: string; libraryKey: string; candidates: string[]; domClasses: string[]; bytes: number; url: string; createdAt: number; lastUsedAt: number };
13
+ export type OpenRuntimeDb = { factory?: IDBFactory; onVersionChange?: () => void };
14
+
15
+ const migrations: Array<(db: IDBDatabase) => void> = [
16
+ (db) => {
17
+ db.createObjectStore("candidates", { keyPath: ["page", "module"] }).createIndex("page", "page");
18
+ db.createObjectStore("tailwind", { keyPath: "key" }).createIndex("libraryKey+lastUsedAt", ["libraryKey", "lastUsedAt"]);
19
+ },
20
+ ];
21
+
22
+ /** The single `page-runtime` database, shared by the service worker and the frame. Stores are created by versioned migrations. */
23
+ export function openRuntimeDb(options: OpenRuntimeDb = {}): Promise<IDBDatabase> {
24
+ const factory = options.factory ?? (typeof indexedDB === "undefined" ? undefined : indexedDB);
25
+ if (!factory) return Promise.reject(new Error("IndexedDB is unavailable"));
26
+ return new Promise((resolve, reject) => {
27
+ const request = factory.open(RUNTIME_DB, RUNTIME_DB_VERSION);
28
+ request.onupgradeneeded = (event) => { for (const migrate of migrations.slice(event.oldVersion)) migrate(request.result); };
29
+ request.onsuccess = () => {
30
+ const db = request.result;
31
+ db.onversionchange = () => { db.close(); options.onVersionChange?.(); };
32
+ resolve(db);
33
+ };
34
+ request.onerror = () => reject(request.error);
35
+ request.onblocked = () => reject(new Error(`${RUNTIME_DB} database upgrade is blocked by another open connection; close other tabs of this runtime`));
36
+ });
37
+ }
38
+
39
+ /** One connection per owner, opened on first use. */
40
+ export function lazyRuntimeDb(options: OpenRuntimeDb = {}): () => Promise<IDBDatabase> {
41
+ let opened: Promise<IDBDatabase> | undefined;
42
+ return () => opened ??= openRuntimeDb(options);
43
+ }
44
+
45
+ export const result = <T>(request: IDBRequest<T>): Promise<T> => new Promise((resolve, reject) => {
46
+ request.onsuccess = () => resolve(request.result);
47
+ request.onerror = () => reject(request.error);
48
+ });
49
+
50
+ export const committed = (tx: IDBTransaction): Promise<void> => new Promise((resolve, reject) => {
51
+ tx.oncomplete = () => resolve();
52
+ tx.onerror = () => reject(tx.error);
53
+ tx.onabort = () => reject(tx.error ?? new Error("page-runtime database transaction aborted"));
54
+ });
55
+
56
+ export async function putCandidates(db: IDBDatabase, record: CandidatesRecord): Promise<void> {
57
+ const tx = db.transaction("candidates", "readwrite");
58
+ tx.objectStore("candidates").put(record);
59
+ await committed(tx);
60
+ }
61
+
62
+ export async function candidatesForPage(db: IDBDatabase, page: string): Promise<CandidatesRecord[]> {
63
+ return result(db.transaction("candidates").objectStore("candidates").index("page").getAll(page));
64
+ }
package/src/styles.ts ADDED
@@ -0,0 +1,40 @@
1
+ /** Normal declarations: dependencies first, derived libraries next, utilities last. */
2
+ export function cascadeOrder(layers: string[] = ['components', 'facet']): string {
3
+ const ordered = [...new Set(layers)];
4
+ for (const layer of ordered) if (!/^[a-zA-Z_][\w-]*$/.test(layer) || ['theme', 'base', 'utilities'].includes(layer)) throw new Error(`Invalid library cascade layer: ${layer}`);
5
+ return `@layer theme, base, ${ordered.join(', ')}, utilities;`;
6
+ }
7
+
8
+ export const layerOrder = cascadeOrder();
9
+
10
+ export function inspectStyles(document: Document): Record<string, string> {
11
+ const view = document.defaultView;
12
+ if (!view) throw new Error('Style inspection requires a live document');
13
+ const root = view.getComputedStyle(document.documentElement);
14
+ const body = view.getComputedStyle(document.body);
15
+ const documentRoot = document.querySelector('[data-facet-theme]') ?? document.body;
16
+ const documentStyle = view.getComputedStyle(documentRoot);
17
+ const heading = document.querySelector('h2');
18
+ const page = documentRoot.querySelector('[data-page-size]');
19
+ return {
20
+ order: [...document.querySelectorAll('style')].map(style => style.textContent?.match(/@layer\s+[^{};]+;/)?.[0]).find(Boolean) ?? 'No explicit layer order',
21
+ theme: documentRoot.getAttribute('data-facet-theme') ?? 'facet',
22
+ '--text-xl': root.getPropertyValue('--text-xl').trim(),
23
+ '--text-sm': root.getPropertyValue('--text-sm').trim(),
24
+ ...Object.fromEntries([...new Set([...Array.from(root), ...Array.from(documentStyle)])]
25
+ .filter(name => /^--(?:facet|text)-/.test(name))
26
+ .map(name => [name, (documentStyle.getPropertyValue(name) || root.getPropertyValue(name)).trim()])),
27
+ 'body font size': body.fontSize,
28
+ 'document font size': documentStyle.fontSize,
29
+ 'document font family': documentStyle.fontFamily,
30
+ 'document line height': documentStyle.lineHeight,
31
+ 'document text color': documentStyle.color,
32
+ 'document background': documentStyle.backgroundColor === 'rgba(0, 0, 0, 0)' ? body.backgroundColor : documentStyle.backgroundColor,
33
+ 'heading font size': heading ? view.getComputedStyle(heading).fontSize : 'No h2',
34
+ ...(page ? {
35
+ 'page size': page.getAttribute('data-page-size') ?? '',
36
+ ...Object.fromEntries(['top', 'right', 'bottom', 'left'].map(side => [`page margin ${side}`, page.getAttribute(`data-margin-${side}`) ?? ''])),
37
+ } : {}),
38
+ stylesheets: [...document.querySelectorAll('[data-page-runtime-base]')].map(style => style.getAttribute('data-page-runtime-base')).join('\n'),
39
+ };
40
+ }
@@ -0,0 +1,66 @@
1
+ import { ACTIVITY_HEADERS, validateActivity, type WorkerActivity } from "../activity-schema.ts";
2
+ import { keys, record as object } from "./profile.ts";
3
+
4
+ export function createRequestActivity(href: string): WorkerActivity {
5
+ const url = new URL(href);
6
+ const kind = (url.pathname.startsWith("/esm/") ? "npm" : /^\/(frame|src|npm|link)\//.exec(url.pathname)?.[1]) as WorkerActivity["kind"] | undefined;
7
+ const pkg = kind === "npm" ? /^\/(?:npm|esm)\/((?:@[^/]+\/)?[^/@]+)@([^/]+)\/(.+)$/.exec(decodeURIComponent(url.pathname)) : null;
8
+ return { id: crypto.randomUUID(), kind: kind ?? "static", url: href, package: pkg ? { name: pkg[1]!, version: pkg[2]!, path: pkg[3]! } : null,
9
+ source: "generated", cache: "miss", origin: null, generated: null, transferredBytes: 0, decodedBytes: null, outputBytes: null,
10
+ startedAt: performance.timeOrigin + performance.now(), fetchMs: 0, integrityMs: 0, compileMs: 0, rewriteMs: 0, totalMs: 0, status: 0, contentType: "", headers: {}, unavailable: [], error: null };
11
+ }
12
+
13
+ export function serverTiming(record: WorkerActivity): string {
14
+ return ([ ["fetch", record.fetchMs], ["integrity", record.integrityMs], ["compile", record.compileMs], ["rewrite", record.rewriteMs], ["total", record.totalMs] ] as const).map(([name, ms]) => name !== "total" && record.unavailable.includes(name) ? `${name};desc="unavailable"` : `${name};dur=${ms.toFixed(2)}`).join(", ") + `, cache;desc="${record.cache === "miss" ? "miss" : "hit"}"`;
15
+ }
16
+
17
+ export function activityResponse(options: { response: Response; record: WorkerActivity; start: number }): Response {
18
+ const { response, record } = options;
19
+ record.totalMs = performance.now() - options.start; record.status = response.status;
20
+ record.contentType = response.headers.get("content-type") ?? "";
21
+ if (response.type === "opaque" || response.type === "opaqueredirect") return response;
22
+ const headers = new Headers(response.headers);
23
+ headers.set("server-timing", [headers.get("server-timing"), serverTiming(record)].filter(Boolean).join(", "));
24
+ record.headers = Object.fromEntries(ACTIVITY_HEADERS.flatMap((name) => headers.has(name) ? [[name, headers.get(name)!.slice(0, 2048)]] : []));
25
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
26
+ }
27
+
28
+ export function createActivityBatcher(options: { send: (client: string, records: WorkerActivity[]) => Promise<void>; delayMs?: number }) {
29
+ const pending = new Map<string, { records: WorkerActivity[]; resolve: () => void; reject: (error: unknown) => void; promise: Promise<void> }>();
30
+ let timer: ReturnType<typeof setTimeout> | undefined;
31
+ async function flush(): Promise<void> {
32
+ timer = undefined;
33
+ const batches = [...pending]; pending.clear();
34
+ for (const [client, batch] of batches) {
35
+ try {
36
+ for (let index = 0; index < batch.records.length; index += 32) await options.send(client, batch.records.slice(index, index + 32));
37
+ batch.resolve();
38
+ } catch (error) { batch.reject(error); }
39
+ }
40
+ }
41
+ return { push: ({ client, record }: { client: string; record: WorkerActivity }): Promise<void> => {
42
+ let batch = pending.get(client);
43
+ if (!batch) {
44
+ let resolve!: () => void; let reject!: (error: unknown) => void;
45
+ const promise = new Promise<void>((yes, no) => { resolve = yes; reject = no; });
46
+ batch = { records: [], resolve, reject, promise }; pending.set(client, batch);
47
+ }
48
+ batch.records.push(record);
49
+ timer ??= setTimeout(() => { void flush(); }, options.delayMs ?? 40);
50
+ return batch.promise;
51
+ } };
52
+ }
53
+
54
+ export const byteLength = (value: string): number => new TextEncoder().encode(value).byteLength;
55
+
56
+ export function applyLinkActivity(options: { response: Response; record: WorkerActivity }): boolean {
57
+ const header = options.response.headers.get("x-link-activity");
58
+ if (header === null) return false;
59
+ const metrics = object(JSON.parse(decodeURIComponent(header)), "link activity");
60
+ const fields = ["source", "cache", "origin", "generated", "transferredBytes", "decodedBytes", "outputBytes", "fetchMs", "integrityMs", "compileMs", "rewriteMs", "unavailable"];
61
+ keys(metrics, fields, "link activity");
62
+ for (const field of fields) if (!Object.hasOwn(metrics, field)) throw new Error(`link activity: missing ${field}`);
63
+ const checked = validateActivity({ type: "activity", load: "link", navigationStart: 0, records: [{ ...options.record, ...metrics }], timeline: [], tailwind: [] });
64
+ Object.assign(options.record, checked.records[0]);
65
+ return true;
66
+ }
@@ -0,0 +1,44 @@
1
+ import type { BarrelIndex } from "../schema.ts";
2
+
3
+ function sideEffectsPattern(pattern: string, id: string): RegExp {
4
+ const glob = pattern.replace(/^\.\//, "");
5
+ const full = glob.includes("/") ? glob : `**/${glob}`;
6
+ let source = "";
7
+ let braces = 0;
8
+ for (let i = 0; i < full.length; i += 1) {
9
+ const char = full[i] ?? "";
10
+ if (char === "*" && full[i + 1] === "*") {
11
+ const slash = full[i + 2] === "/";
12
+ source += slash ? "(?:.*/)?" : ".*";
13
+ i += slash ? 2 : 1;
14
+ } else if (char === "*") source += "[^/]*";
15
+ else if (char === "?") source += "[^/]";
16
+ else if (char === "{") {
17
+ braces += 1;
18
+ source += "(?:";
19
+ } else if (char === "}" && braces > 0) {
20
+ braces -= 1;
21
+ source += ")";
22
+ } else if (char === "," && braces > 0) source += "|";
23
+ else if (char === "[" || char === "]") throw new Error(`${id}: sideEffects pattern ${pattern} uses a character class, which the index does not support`);
24
+ else source += char.replace(/[.+^$()|\\]/g, "\\$&");
25
+ }
26
+ return new RegExp(`^${source}$`);
27
+ }
28
+
29
+ /** Whether a package's `sideEffects` declaration lets a bundler skip the file at a package-relative path. */
30
+ export function sideEffectsRule(declaration: unknown, id: string): (path: string) => boolean {
31
+ if (declaration === false) return () => true;
32
+ if (declaration === undefined || declaration === true) return () => false;
33
+ if (Array.isArray(declaration) && declaration.every((item) => typeof item === "string")) {
34
+ const patterns = declaration.map((item: string) => sideEffectsPattern(item, id));
35
+ return (path) => !patterns.some((pattern) => pattern.test(path));
36
+ }
37
+ throw new Error(`${id} declares sideEffects as ${JSON.stringify(declaration)}, which is neither a boolean nor a list of globs`);
38
+ }
39
+
40
+ export function guardedBarrels(options: { index: BarrelIndex; name: string; version: string; sideEffects?: boolean | string[] }): BarrelIndex {
41
+ const root = `${options.name}@${options.version}/`;
42
+ const free = sideEffectsRule(options.sideEffects, root);
43
+ return { modules: options.index.modules, barrels: Object.fromEntries(Object.entries(options.index.barrels).filter(([url]) => !url.startsWith(root) || free(url.slice(root.length)))) };
44
+ }
@@ -0,0 +1,14 @@
1
+ import { parse } from "sucrase/dist/parser";
2
+ import { TokenType } from "sucrase/dist/parser/tokenizer/types";
3
+
4
+ export function sourceCandidates(options: { path: string; code: string }): string[] {
5
+ const javascript = /\.(?:tsx?|jsx?|mjs)$/.test(options.path);
6
+ let start = 0;
7
+ const parts: string[] = [];
8
+ if (javascript) for (const token of parse(options.code, true, /\.tsx?$/.test(options.path), false).tokens) {
9
+ if (token.type !== TokenType.jsxText) continue;
10
+ parts.push(options.code.slice(start, token.start)); start = token.end;
11
+ }
12
+ const text = [...parts, options.code.slice(start)].join(" ");
13
+ return [...new Set(text.match(/[A-Za-z0-9_!:@/.[\]#%(),=+-]+/g) ?? [])];
14
+ }