@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,118 @@
1
+ import { readFile, realpath } from "node:fs/promises";
2
+ import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
3
+ import type { AddressInfo } from "node:net";
4
+ import { extname, resolve, sep } from "node:path";
5
+ import { createCatalogStore, type LocalPackage } from "./catalog.ts";
6
+
7
+ export { serveRuntime, type RuntimeOriginOptions } from "./runtime-origin.ts";
8
+
9
+ export type PackageOriginOptions = { packages: string[]; upstreamRegistry: string; upstreamOrigin: string; stateDir: string };
10
+ export type PackageHandler = (request: IncomingMessage, response: ServerResponse) => Promise<void>;
11
+ export const LOCAL_RELEASE_TIME = "2000-01-01T00:00:00.000Z";
12
+
13
+ type Served = { body: string | Uint8Array; type: string; status: number; cache: string };
14
+ const types: Record<string, string> = {
15
+ ".js": "text/javascript", ".mjs": "text/javascript", ".cjs": "text/javascript",
16
+ ".json": "application/json", ".map": "application/json", ".css": "text/css",
17
+ ".html": "text/html", ".txt": "text/plain", ".md": "text/markdown",
18
+ ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
19
+ ".gif": "image/gif", ".webp": "image/webp", ".avif": "image/avif", ".ico": "image/x-icon",
20
+ ".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf", ".otf": "font/otf", ".wasm": "application/wasm",
21
+ };
22
+ const textResponse = (status: number, body: string): Served => ({ status, body, type: "text/plain; charset=utf-8", cache: "no-store" });
23
+
24
+ function upstreamBase(value: string): string {
25
+ const url = new URL(value);
26
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error(`upstream must be an HTTP(S) URL without credentials, query or hash: ${value}`);
27
+ return url.href.replace(/\/$/, "");
28
+ }
29
+
30
+ async function localFile(local: LocalPackage, path: string): Promise<Served> {
31
+ if (!path || path.split(/[\\/]/).some((part) => part === "..") || path.includes("\0")) return textResponse(404, "Invalid local package file path");
32
+ try {
33
+ const file = await realpath(resolve(local.directory, path));
34
+ if (!file.startsWith(`${local.directory}${sep}`)) return textResponse(404, "File is outside the local package directory");
35
+ return { body: await readFile(file), status: 200, type: types[extname(file)] ?? "application/octet-stream", cache: "no-store" };
36
+ } catch (error) {
37
+ if (["ENOENT", "ENOTDIR", "EISDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) return textResponse(404, `${local.manifest.name}@${local.manifest.version}: file not found: ${path}`);
38
+ throw error;
39
+ }
40
+ }
41
+
42
+ async function serveRequest(options: { url: string; method: string; locals: Map<string, LocalPackage>; registry: string; origin: string; immutable: boolean }): Promise<Served> {
43
+ const { url, method, locals, registry, origin } = options;
44
+ if (method === "OPTIONS") return textResponse(204, "");
45
+ if (!["GET", "HEAD"].includes(method)) return textResponse(405, "Only GET, HEAD and OPTIONS are supported");
46
+ let path: string;
47
+ try { path = decodeURIComponent(url.split("?")[0]!); }
48
+ catch { return textResponse(400, "Invalid URL encoding"); }
49
+ if (path === "/") return { status: 200, body: JSON.stringify({ packages: [...locals.keys()] }), type: "application/json", cache: "no-store" };
50
+ const match = path.match(/^\/((?:@[^/@]+\/)?[^/@]+)(?:@([^/]+)(?:\/(.*))?)?$/);
51
+ if (!match) return textResponse(404, `Invalid package path: ${path}`);
52
+ const [, name, version, file] = match;
53
+ const local = locals.get(name!);
54
+ if (local) {
55
+ const manifest = local.manifest;
56
+ if (!version) return { status: 200, body: JSON.stringify({ name, versions: { [manifest.version]: manifest }, time: { [manifest.version]: LOCAL_RELEASE_TIME }, "dist-tags": { latest: manifest.version } }), type: "application/json", cache: options.immutable ? "public, max-age=31536000, immutable" : "no-store" };
57
+ if (version !== manifest.version) return textResponse(404, `Requested ${name}@${version}; local package is ${name}@${manifest.version}`);
58
+ const served = await localFile(local, file ?? "");
59
+ if (options.immutable && served.status === 200) served.cache = "public, max-age=31536000, immutable";
60
+ return served;
61
+ }
62
+ const target = `${version ? origin : registry}${url}`;
63
+ try {
64
+ const response = await fetch(target, { method, signal: AbortSignal.timeout(30_000) });
65
+ return { status: response.status, body: new Uint8Array(await response.arrayBuffer()), type: response.headers.get("content-type") ?? "application/octet-stream", cache: response.headers.get("cache-control") ?? "no-store" };
66
+ } catch (error) {
67
+ return textResponse(502, `Proxy ${target}: ${error instanceof Error ? error.message : String(error)}`);
68
+ }
69
+ }
70
+
71
+ export async function createPackageHandler(options: PackageOriginOptions) {
72
+ const registry = upstreamBase(options.upstreamRegistry);
73
+ const origin = upstreamBase(options.upstreamOrigin);
74
+ if (!options.packages.length) throw new Error("At least one local package directory is required");
75
+ const store = await createCatalogStore(options);
76
+ const handle: PackageHandler = async (request, response) => {
77
+ response.setHeader("access-control-allow-origin", "*");
78
+ response.setHeader("access-control-allow-methods", "GET, HEAD, OPTIONS");
79
+ response.setHeader("access-control-allow-headers", "*");
80
+ try {
81
+ const raw = request.url ?? "/";
82
+ const generation = raw.match(/^\/_generations\/([^/]+)(\/.*)$/);
83
+ const selected = await store.get(generation?.[1]);
84
+ const url = generation?.[2] ?? raw;
85
+ const served = ["GET", "HEAD"].includes(request.method ?? "GET") && url.split("?")[0] === "/__catalog.json"
86
+ ? { status: 200, body: JSON.stringify(selected.catalog), type: "application/json", cache: generation ? "public, max-age=31536000, immutable" : "no-store" }
87
+ : await serveRequest({ url, method: request.method ?? "GET", locals: selected.locals, registry, origin, immutable: Boolean(generation) });
88
+ response.writeHead(served.status, {
89
+ "content-type": served.type,
90
+ "cache-control": served.cache,
91
+ ...(served.status === 204 || served.status === 304 ? {} : { "content-length": typeof served.body === "string" ? Buffer.byteLength(served.body) : served.body.byteLength }),
92
+ "timing-allow-origin": "*",
93
+ "access-control-expose-headers": "content-length, content-encoding, server-timing",
94
+ });
95
+ response.end(request.method === "HEAD" ? undefined : served.body);
96
+ } catch (error) {
97
+ console.error("Package request failed", error);
98
+ response.writeHead((error as NodeJS.ErrnoException).code === "ENOENT" ? 404 : 500, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
99
+ response.end((error as NodeJS.ErrnoException).code === "ENOENT" ? "Package not found" : "Package request failed");
100
+ }
101
+ };
102
+ return { handle, current: store.current, subscribe: store.subscribe, close: store.close };
103
+ }
104
+
105
+ export async function servePackages(options: PackageOriginOptions & { port: number }): Promise<{ origin: string; close: () => Promise<void> }> {
106
+ if (!Number.isInteger(options.port) || options.port < 0 || options.port > 65535) throw new Error(`Invalid port: ${options.port}`);
107
+ const handler = await createPackageHandler(options);
108
+ const server = createServer((request, response) => { void handler.handle(request, response); });
109
+ await new Promise<void>((done, fail) => { server.once("error", fail); server.listen(options.port, "127.0.0.1", done); });
110
+ return {
111
+ origin: `http://127.0.0.1:${(server.address() as AddressInfo).port}`,
112
+ close: () => new Promise<void>((done, fail) => {
113
+ handler.close();
114
+ server.closeAllConnections();
115
+ server.close((error) => error ? fail(error) : done());
116
+ }),
117
+ };
118
+ }
@@ -0,0 +1,63 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { createServer } from "node:http";
4
+ import type { AddressInfo } from "node:net";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import type { RuntimeProfile } from "../schema.ts";
8
+ import { createPackageHandler, type PackageOriginOptions } from "./index.ts";
9
+
10
+ // This module runs from src/ in the workspace and from a bundle in dist/node/ when installed, so locate the package root.
11
+ function packageAssets(): string {
12
+ for (let dir = dirname(fileURLToPath(import.meta.url)); dir !== dirname(dir); dir = dirname(dir)) {
13
+ if (existsSync(join(dir, "package.json")) && existsSync(join(dir, "dist/static"))) return join(dir, "dist/static");
14
+ }
15
+ throw new Error("Cannot find the built page-runtime assets; run the page-runtime build");
16
+ }
17
+
18
+ export type RuntimeOriginOptions = PackageOriginOptions & { hostOrigin: string; assetsDir?: string };
19
+
20
+ /** Serves built browser assets and local package publications on a separate loopback origin. */
21
+ export async function serveRuntime(options: RuntimeOriginOptions): Promise<{ origin: string; dependencies: Record<string, string>; close: () => Promise<void> }> {
22
+ const host = new URL(options.hostOrigin);
23
+ if (host.origin !== options.hostOrigin || !["http:", "https:"].includes(host.protocol) || !["localhost", "127.0.0.1", "[::1]"].includes(host.hostname)) throw new Error("Local page runtime requires an exact loopback origin");
24
+ const assetsDir = options.assetsDir ?? packageAssets();
25
+ const assets = new Map(await Promise.all(["bootstrap.html", "sw.js", "boot.js", "page-agent.js", "editing.js", "export-compiler.js", "devtools-hook.js"].map(async (file) => [file, await readFile(resolve(assetsDir, file))] as const)));
26
+ const packages = await createPackageHandler(options);
27
+ const dependencies = () => Object.fromEntries(Object.entries(packages.current().packages).map(([name, entry]) => [name, entry.version]));
28
+ let origin: string;
29
+ const server = createServer((request, response) => {
30
+ try {
31
+ const path = new URL(request.url ?? "/", "http://localhost").pathname;
32
+ if (path.startsWith("/_generations/")) { void packages.handle(request, response); return; }
33
+ if (request.method !== "GET" && request.method !== "HEAD") { response.writeHead(405).end(); return; }
34
+ if (path === "/profile.json") {
35
+ const packageOrigin = `${origin}/_generations/${packages.current().revision}`;
36
+ const profile: RuntimeProfile = {
37
+ runtimeDomain: new URL(origin).host, embedders: [host.origin], packageOrigin, registry: packageOrigin, managed: dependencies(),
38
+ policy: { dependencies: "strict" }, minReleaseAgeDays: 0,
39
+ network: { allow: ["https://fonts.googleapis.com/*", "https://fonts.gstatic.com/*"] },
40
+ csp: { add: { "style-src": ["https://fonts.googleapis.com"], "font-src": ["'self'", "data:", "https://fonts.gstatic.com"] } },
41
+ links: "deny", sources: ["host"], readinessTimeoutMs: 30000,
42
+ };
43
+ response.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" }).end(request.method === "HEAD" ? undefined : JSON.stringify(profile));
44
+ return;
45
+ }
46
+ const file = path.startsWith("/frame/") ? "bootstrap.html" : path.slice(1);
47
+ const asset = assets.get(file);
48
+ if (!asset) { response.writeHead(404).end("Runtime asset not found"); return; }
49
+ response.writeHead(200, { "content-type": file.endsWith(".html") ? "text/html; charset=utf-8" : "text/javascript; charset=utf-8", "cache-control": "no-store", ...(file === "sw.js" ? { "service-worker-allowed": "/frame/" } : {}) });
50
+ response.end(request.method === "HEAD" ? undefined : asset);
51
+ } catch (error) {
52
+ response.writeHead(500, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" }).end(request.method === "HEAD" ? undefined : error instanceof Error ? error.message : String(error));
53
+ }
54
+ });
55
+ try { await new Promise<void>((done, fail) => { server.once("error", fail); server.listen(0, "127.0.0.1", done); }); }
56
+ catch (error) { packages.close(); throw error; }
57
+ origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
58
+ return { origin, get dependencies() { return dependencies(); }, close: () => new Promise<void>((done, fail) => {
59
+ packages.close();
60
+ server.closeAllConnections();
61
+ server.close((error) => error ? fail(error) : done());
62
+ }) };
63
+ }
package/src/editing.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { createContext, createElement, useContext, useSyncExternalStore, type ReactElement, type ReactNode } from "react";
2
+
3
+ const scope = globalThis as typeof globalThis & { __pageEditing?: { removed: Set<string>; listeners: Set<() => void> } };
4
+ const { removed, listeners } = scope.__pageEditing ??= { removed: new Set<string>(), listeners: new Set<() => void>() };
5
+ const subscribe = (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; };
6
+
7
+ const reviewScope = createContext("");
8
+ export function EditingScope({ scope, children }: { scope: string; children: ReactNode }) { return createElement(reviewScope.Provider, { value: scope }, children); }
9
+
10
+ export function setRemoved(identity: string, value: boolean): void {
11
+ if (value) removed.add(identity); else removed.delete(identity);
12
+ for (const listener of listeners) listener();
13
+ }
14
+
15
+ function EditableBoundary({ identities, children }: { identities: string[]; children: ReactNode }) {
16
+ const scope = useContext(reviewScope);
17
+ return useSyncExternalStore(subscribe, () => identities.some(identity => removed.has(scope && identity.startsWith("review:") ? `review:${scope}:${identity.slice(7)}` : identity)), () => false) ? null : children;
18
+ }
19
+
20
+ export function editableElement(element: ReactElement<Record<string, unknown>>): ReactElement {
21
+ const review = element.props["data-review-id"];
22
+ const source = element.props["data-source"];
23
+ const identities = [...(typeof review === "string" ? [`review:${review}`] : []), ...(typeof source === "string" && source.includes("#") ? [`source:${source}`] : [])];
24
+ return identities.length ? createElement(EditableBoundary, { identities, key: element.key, children: element }) : element;
25
+ }
@@ -0,0 +1,68 @@
1
+ /** Echoed values the entry remembers while waiting for the host to send them back; bounds memory when a host never does. */
2
+ export const PENDING_ECHO_LIMIT = 64;
3
+
4
+ /** A module the generated entry imports: its specifier from `__form/` and the label used in error messages. */
5
+ type ModuleRef = { specifier: string; label: string };
6
+
7
+ /**
8
+ * The source text of `__form/entry.tsx`. Host sources go through the form's `extensions` prop; sources the schema
9
+ * declares in `x-clicky-extensions` go only through `extensionLoader`, by their index in the declared list, so nothing
10
+ * registers twice. It runs inside the frame, so it can only import what the page's lock resolves:
11
+ * react, clicky-ui and the extension modules. Each extension's default export is validated when the module loads, so a
12
+ * bad export fails the page loudly instead of being ignored.
13
+ *
14
+ * The page keeps the form value in local state for typing latency and emits every change to the host. The host's
15
+ * `data.value` replaces the local value only when it is not one of the values this page emitted and has not yet seen
16
+ * echoed back, which is what prevents an echo loop.
17
+ */
18
+ export function formEntrySource(options: { host: ModuleRef[]; declared: ModuleRef[] }): string {
19
+ const imports = [
20
+ ...options.host.map(({ specifier }, index) => `import extension${index} from ${JSON.stringify(specifier)};`),
21
+ ...options.declared.map(({ specifier }, index) => `import declared${index} from ${JSON.stringify(specifier)};`),
22
+ ].join("\n");
23
+ const list = options.host.map(({ label }, index) => `[extension${index}, ${JSON.stringify(label)}]`).join(", ");
24
+ const declaredList = options.declared.map(({ label }, index) => `[declared${index}, ${JSON.stringify(label)}]`).join(", ");
25
+ return `import { useState } from "react";
26
+ import { JsonSchemaForm } from "@flanksource/clicky-ui/components";
27
+ ${imports}
28
+
29
+ const PENDING_ECHO_LIMIT = ${PENDING_ECHO_LIMIT};
30
+ const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
31
+
32
+ function assertFormExtension(value, label) {
33
+ const where = "form extension " + label + ": ";
34
+ if (!isObject(value)) throw new Error(where + "the default export must be a FormExtension object (use defineFormExtension)");
35
+ if (typeof value.name !== "string" || !value.name) throw new Error(where + "name must be a non-empty string");
36
+ for (const key of ["pre", "post"]) {
37
+ if (value[key] !== undefined && (!Array.isArray(value[key]) || value[key].some((hook) => typeof hook !== "function"))) throw new Error(where + key + " must be an array of functions");
38
+ }
39
+ for (const key of ["formats", "lookups", "layouts", "slots"]) {
40
+ if (value[key] !== undefined && !isObject(value[key])) throw new Error(where + key + " must be an object");
41
+ }
42
+ return value;
43
+ }
44
+
45
+ const extensions = [${list}].map(([value, label]) => assertFormExtension(value, label));
46
+ const schemaExtensions = [${declaredList}].map(([value, label]) => assertFormExtension(value, label));
47
+ const loadSchemaExtension = (_source, index) => index >= 0 && index < schemaExtensions.length
48
+ ? Promise.resolve(schemaExtensions[index])
49
+ : Promise.reject(new Error("schema-declared form extension " + index + " was not compiled into this page (it has " + schemaExtensions.length + ")"));
50
+
51
+ export default function FormPage({ data, host }) {
52
+ if (!isObject(data) || !isObject(data.schema) || !("value" in data)) throw new Error("form page data must be { schema, value, props }");
53
+ const incoming = JSON.stringify(data.value);
54
+ const [form, setForm] = useState(() => ({ local: data.value, seen: incoming, pending: [] }));
55
+ let current = form;
56
+ if (current.seen !== incoming) {
57
+ const echoed = current.pending.indexOf(incoming);
58
+ current = echoed >= 0 ? { ...current, seen: incoming, pending: current.pending.slice(echoed + 1) } : { local: data.value, seen: incoming, pending: [] };
59
+ setForm(current);
60
+ }
61
+ const onChange = (next) => {
62
+ host.emit("change", next);
63
+ setForm((state) => ({ ...state, local: next, pending: [...state.pending, JSON.stringify(next)].slice(-PENDING_ECHO_LIMIT) }));
64
+ };
65
+ return <JsonSchemaForm {...data.props} schema={data.schema} value={current.local} extensions={extensions} extensionLoader={loadSchemaExtension} onChange={onChange} />;
66
+ }
67
+ `;
68
+ }
@@ -0,0 +1,63 @@
1
+ import type { FormExtensionSource } from "@flanksource/clicky-ui/components";
2
+ import type { FolderManifest, JsonValue, OpenMessage, RuntimePolicy, SourceProvider } from "../schema.ts";
3
+ import { validateSourcePath } from "../host/validation.ts";
4
+ import { formEntrySource } from "./entry-source.ts";
5
+
6
+ /** An extension module, inline TSX or a `ref` path: clicky-ui's definition, re-exported so there is one. */
7
+ export type { FormExtensionSource };
8
+
9
+ export const FORM_ENTRY = "__form/entry.tsx";
10
+ export const SCHEMA_EXTENSIONS_KEYWORD = "x-clicky-extensions";
11
+ const CLICKY_UI = "@flanksource/clicky-ui";
12
+ const SCRIPT = /\.[cm]?[jt]sx?$/;
13
+ const isReserved = (path: string) => path === FORM_ENTRY || /^__form\/ext-\d+\.tsx$/.test(path);
14
+
15
+ /** The sources a schema declares in its root `x-clicky-extensions`, validated for shape; none when the keyword is absent. */
16
+ export function schemaExtensionSources(schema: JsonValue | undefined): FormExtensionSource[] {
17
+ if (schema === null || schema === undefined || typeof schema !== "object" || Array.isArray(schema)) return [];
18
+ const declared = schema[SCHEMA_EXTENSIONS_KEYWORD];
19
+ if (declared === undefined) return [];
20
+ if (!Array.isArray(declared)) throw new Error(`schema ${SCHEMA_EXTENSIONS_KEYWORD} must be an array of { tsx, name? } or { ref } sources`);
21
+ return declared.map((source, index) => {
22
+ const where = `schema ${SCHEMA_EXTENSIONS_KEYWORD}[${index}]`;
23
+ if (source === null || typeof source !== "object" || Array.isArray(source)) throw new Error(`${where} must be an object`);
24
+ const keys = Object.keys(source);
25
+ if ("ref" in source) {
26
+ if (typeof source.ref !== "string" || keys.some((key) => key !== "ref")) throw new Error(`${where} must be { ref: string } with no other keys`);
27
+ return { ref: source.ref };
28
+ }
29
+ if (typeof source.tsx !== "string" || keys.some((key) => key !== "tsx" && key !== "name") || (source.name !== undefined && typeof source.name !== "string")) throw new Error(`${where} must be { tsx: string, name?: string } or { ref: string }`);
30
+ return typeof source.name === "string" ? { tsx: source.tsx, name: source.name } : { tsx: source.tsx };
31
+ });
32
+ }
33
+
34
+ /**
35
+ * Builds the `open` message for a page that renders a `JsonSchemaForm` with runtime-compiled extensions. Pure: inline
36
+ * sources become `__form/ext-<i>.tsx`, refs stay relative paths the host's `files` or the worker's `sourceProvider`
37
+ * must serve, and `__form/entry.tsx` imports every extension's default export. Sources the `schema` declares in
38
+ * `x-clicky-extensions` follow `extensions`, so a source's index in the combined list fixes its file name.
39
+ */
40
+ export function formPageOpen(options: { extensions: FormExtensionSource[]; schema?: JsonValue; manifest: FolderManifest; files?: Record<string, string>; sourceProvider?: SourceProvider; policy?: RuntimePolicy }): OpenMessage {
41
+ const { extensions, manifest, sourceProvider, policy } = options;
42
+ const files = { ...options.files };
43
+ if (!manifest.dependencies[CLICKY_UI]) throw new Error(`formPageOpen: manifest.dependencies must declare ${CLICKY_UI}; the generated form page imports it`);
44
+ for (const path of Object.keys(files)) if (isReserved(path)) throw new Error(`formPageOpen: files.${path} is reserved for the generated form page`);
45
+ const declared = schemaExtensionSources(options.schema);
46
+ const resolve = (extension: FormExtensionSource, index: number, where: string) => {
47
+ if ("ref" in extension) {
48
+ validateSourcePath(extension.ref);
49
+ if (!SCRIPT.test(extension.ref)) throw new Error(`formPageOpen: ${where} ref ${extension.ref} must be a JavaScript/TypeScript source`);
50
+ if (Object.hasOwn(files, extension.ref)) return { specifier: `../${extension.ref}`, label: extension.ref };
51
+ if (!sourceProvider?.paths.includes(extension.ref)) throw new Error(`formPageOpen: ${where} ref ${extension.ref} is served by neither files nor sourceProvider.paths`);
52
+ // The worker roots sourceProvider paths in the page's directory (`__form/`), not at the files root.
53
+ return { specifier: `./${extension.ref}`, label: extension.ref };
54
+ }
55
+ if (!extension.tsx.trim()) throw new Error(`formPageOpen: ${where} has an empty tsx source`);
56
+ files[`__form/ext-${index}.tsx`] = extension.tsx;
57
+ return { specifier: `./ext-${index}.tsx`, label: extension.name ?? `inline-${index}` };
58
+ };
59
+ const host = extensions.map((extension, index) => resolve(extension, index, `extension ${index}`));
60
+ const fromSchema = declared.map((extension, index) => resolve(extension, extensions.length + index, `schema ${SCHEMA_EXTENSIONS_KEYWORD}[${index}]`));
61
+ files[FORM_ENTRY] = formEntrySource({ host, declared: fromSchema });
62
+ return { page: FORM_ENTRY, manifest, files, ...(sourceProvider ? { sourceProvider } : {}), ...(policy ? { policy } : {}) };
63
+ }
@@ -0,0 +1,2 @@
1
+ export { FORM_ENTRY, SCHEMA_EXTENSIONS_KEYWORD, formPageOpen, schemaExtensionSources, type FormExtensionSource } from "./form-page.ts";
2
+ export { formSourceUpdate } from "./source-update.ts";
@@ -0,0 +1,17 @@
1
+ import type { HostMessage, JsonValue, OpenMessage } from "../schema.ts";
2
+
3
+ /**
4
+ * The host message that takes a live form page from `before` to `after`: `sources` with only the changed files (and
5
+ * the current data, which a source replacement remounts with) when only files differ, `open` when the manifest, the
6
+ * source provider or the policy differ because a worker session cannot swap those, and null when nothing changed.
7
+ */
8
+ export function formSourceUpdate(options: { before: OpenMessage; after: OpenMessage; data: JsonValue }): Extract<HostMessage, { type: "sources" | "open" }> | null {
9
+ const { before, after, data } = options;
10
+ if (after.page !== before.page) throw new Error(`formSourceUpdate: page changed from ${before.page} to ${after.page}; remount the form instead`);
11
+ const same = (field: "manifest" | "sourceProvider" | "policy") => JSON.stringify(before[field]) === JSON.stringify(after[field]);
12
+ if (!same("manifest") || !same("sourceProvider") || !same("policy")) return { type: "open", ...after };
13
+ const files: Record<string, string | null> = {};
14
+ for (const [path, source] of Object.entries(after.files)) if (before.files[path] !== source) files[path] = source;
15
+ for (const path of Object.keys(before.files)) if (!Object.hasOwn(after.files, path)) files[path] = null;
16
+ return Object.keys(files).length ? { type: "sources", files, data } : null;
17
+ }
@@ -0,0 +1,34 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { afterAll, beforeAll, expect, it } from "vitest";
4
+ import { startRuntimeTestServer } from "./testing/server.ts";
5
+ import type { ActivityMessage } from "../activity-schema.ts";
6
+
7
+ const exec = promisify(execFile);
8
+ const session = `runtime-activity-${process.pid}`;
9
+ let server: Awaited<ReturnType<typeof startRuntimeTestServer>>;
10
+ let opened = false;
11
+ async function browser(...args: string[]) {
12
+ return (await exec("agent-browser", ["--engine", "chrome", "--session", session, ...args], { timeout: 45000, maxBuffer: 4_000_000 })).stdout.trim();
13
+ }
14
+ beforeAll(async () => { server = await startRuntimeTestServer(); });
15
+ afterAll(async () => { try { if (opened) await browser("close"); } finally { await server?.close(); } });
16
+
17
+ it("reports real page source, generated import map, npm network then cache, and boot phases ending in ready", async () => {
18
+ await browser("open", `${server.hostOrigin}/?case=ready`); opened = true;
19
+ await browser("wait", "--fn", 'document.title === "CASE-DONE" && document.querySelector("#activity").textContent.includes("ready") && JSON.parse(document.querySelector("#activity").textContent).some(m => m.records.some(r => r.kind === "frame"))');
20
+ const cold = JSON.parse(await browser("get", "text", "#activity")) as ActivityMessage[];
21
+ const result = JSON.parse(await browser("get", "text", "#result")) as { errors: Array<{ phase: string; message: string }> };
22
+ if (result.errors.length) throw new Error(JSON.stringify(result.errors));
23
+ const records = cold.flatMap((message) => message.records);
24
+ expect(records.find((record) => record.kind === "frame")?.generated).toContain("import map");
25
+ expect(records.find((record) => record.kind === "src" && record.url.includes("report.tsx"))).toMatchObject({ source: "compiled", status: 200 });
26
+ expect(records.find((record) => record.kind === "npm" && record.source === "network")).toMatchObject({ origin: expect.stringContaining("/packages/"), decodedBytes: expect.any(Number), headers: { "server-timing": expect.stringContaining("integrity;dur=") } });
27
+ expect(cold.flatMap((message) => message.timeline).map((mark) => mark.phase)).toEqual(expect.arrayContaining(["controlled", "libraries", "module", "styles", "agent", "render", "ready"]));
28
+ const load = cold.at(-1)!.load;
29
+ await browser("click", "#reload");
30
+ await browser("wait", "--fn", `JSON.parse(document.querySelector("#activity").textContent).some(m => m.load !== ${JSON.stringify(load)} && m.timeline.some(t => t.phase === "ready"))`);
31
+ const warm = (JSON.parse(await browser("get", "text", "#activity")) as ActivityMessage[]).filter((message) => message.load !== load);
32
+ expect(warm.flatMap((message) => message.records).some((record) => record.kind === "npm" && record.source === "cache" && record.transferredBytes === 0)).toBe(true);
33
+ expect(warm.flatMap((message) => message.timeline).at(-1)?.phase).toBe("ready");
34
+ });
@@ -0,0 +1,52 @@
1
+ import { randomUUID } from "@flanksource/clicky-ui/utils";
2
+ import type { FrameConfig, FrameMessage } from "../schema.ts";
3
+ import type { ActivityMessage, RuntimeResolution, TailwindActivity, WorkerActivity } from "../activity-schema.ts";
4
+ import { validateActivity } from "../activity-schema.ts";
5
+ import { inspectStyles } from '../styles.ts';
6
+
7
+ export function runtimeResolution(options: { config: FrameConfig; importMap: string }): RuntimeResolution {
8
+ const { config } = options;
9
+ const baseNames = ["react", "react-dom", "react/jsx-runtime", "react/jsx-dev-runtime", "react-dom/client", "scheduler", "@tanstack/react-query", "jotai"];
10
+ const base = Object.fromEntries(baseNames.flatMap((name) => config.lock.map.imports[name] ? [[name, config.lock.map.imports[name]!]] : []));
11
+ const react = /\/npm\/(?:react|@flanksource\/clicky-ui)@([^/]+)/.exec(config.lock.map.imports.react ?? "");
12
+ const versions = { ...config.lock.versions };
13
+ // Converted React lives inside clicky-ui's runtime set; report React's actual runtime version separately in boot.
14
+ if (react && config.lock.map.imports.react?.startsWith("/npm/react@")) versions.react = react[1]!;
15
+ return { versions, base, managed: Object.keys(config.profile.managed), importMapBytes: new TextEncoder().encode(options.importMap).byteLength, scopes: Object.keys(config.lock.map.scopes).length };
16
+ }
17
+
18
+ export function createFrameActivity(options: { send: (message: FrameMessage) => void; error: (error: Error) => void }) {
19
+ const load = randomUUID(); const navigationStart = performance.timeOrigin;
20
+ let runtime: RuntimeResolution | undefined;
21
+ let builds: TailwindActivity[] = [];
22
+ let records: WorkerActivity[] = [];
23
+ let timer: ReturnType<typeof setTimeout> | undefined;
24
+ const snapshot = (): ActivityMessage => ({ type: "activity", load, navigationStart, records: [], timeline: performance.getEntriesByType("mark").filter((mark) => mark.name.startsWith("page-runtime:")).slice(-64).map((mark) => ({ phase: mark.name.slice(13), atMs: mark.startTime })), tailwind: builds.splice(0, 32), ...(runtime ? { runtime } : {}) });
25
+ const flush = () => {
26
+ clearTimeout(timer); timer = undefined;
27
+ const message = { ...snapshot(), styles: inspectStyles(document) }; const pending = records; records = [];
28
+ options.send({ ...message, records: pending.slice(0, 32) });
29
+ for (let index = 32; index < pending.length; index += 32) options.send({ type: "activity", load, navigationStart, records: pending.slice(index, index + 32), timeline: [], tailwind: [] });
30
+ };
31
+ const schedule = () => { timer ??= setTimeout(flush, 40); };
32
+ const receive = (event: MessageEvent<unknown>) => {
33
+ if (event.source !== navigator.serviceWorker.controller) return;
34
+ if (!event.data || typeof event.data !== "object" || !("type" in event.data) || event.data.type !== "activity") return;
35
+ try {
36
+ const message = validateActivity(event.data);
37
+ if (message.load !== load || message.navigationStart !== navigationStart) throw new Error("worker activity belongs to a different frame load");
38
+ records.push(...message.records); schedule();
39
+ } catch (error) { options.error(error instanceof Error ? error : new Error(String(error))); }
40
+ };
41
+ navigator.serviceWorker.addEventListener("message", receive);
42
+ return {
43
+ load, navigationStart, flush, schedule,
44
+ resolve: (config: FrameConfig, versions: Record<string, string>) => {
45
+ const map = document.querySelector('script[type="importmap"]');
46
+ if (!map?.textContent) throw new Error("frame import map is missing");
47
+ runtime = runtimeResolution({ config, importMap: map.textContent }); Object.assign(runtime.versions, versions);
48
+ },
49
+ tailwind: (build: TailwindActivity) => { builds.push(build); if (builds.length === 32) flush(); else schedule(); },
50
+ stop: () => { clearTimeout(timer); navigator.serviceWorker.removeEventListener("message", receive); builds = []; records = []; },
51
+ };
52
+ }
@@ -0,0 +1,47 @@
1
+ # Page agent
2
+
3
+ `startPageAgent({ root, page, send, error })` installs the embedded `@flanksource/clicky-ui/react-grab` picker, a shadow-root overlay, DOM and resize observers, and shortcut forwarding. `root` is the mounted page wrapper, `page` is its source path, `send` sends an `AgentFrameMessage` through the existing authenticated bridge, and `error` reports failures through the frame's render-error path. An optional `picker` supplies an existing fork instance for the bookmarklet loader; disposal restores its toolbar action and enabled state. The loader must install `devtools-hook.js` as the first classic script before React.
4
+
5
+ The returned agent accepts `mode`, `pick`, `page`, `pins`, `highlight` and `scroll` messages through `receive`. The existing bridge validates these messages and every outbound frame message; the agent also validates incoming commands before acting. `mode: comment` activates the picker and `mode: off` deactivates it. Each saved pin has an `anchor`, a positive `count` and its captured `locators`; optional `focus` selects an anchor. Reported anchors retain their stored identity and explicitly report `found`, `moved` or `orphaned`, with a null rectangle for an orphan. Geometry uses frame viewport coordinates. The host adds the frame offset when cropping its own screenshot.
6
+
7
+ Wrap the rendered page in `<PageAgentProvider agent={agent}>` from `./provider.tsx`. It uses clicky-ui's comment contexts to forward component registrations and pin focus, without transferring comment storage or identity into the frame. `registerAnchor` is also available directly for non-React content. Call `dispose` on page teardown.
8
+
9
+ Source resolution first uses the nearest page `data-source` ancestor, retaining the picked library component's name. Without a marker it inspects React owner creation locations (`_debugSource` and React 19 `_debugStack`). Library and generated entry locations are rejected. Picks without a page location fail visibly through `error`.
10
+
11
+ The development compiler preserves the original `fileName`, `lineNumber` and `columnNumber` for composite JSX call sites, including member components and Sucrase's spread/key `createElement` path. A library pick without a marked page ancestor can therefore resolve through its owner creation location. Incomplete or non-page locations still fail visibly; the agent does not invent a column.
12
+
13
+ The bookmarklet explicitly supplies `sourceContext: { mode: "external-document", url: document.location.href }`. Its ordinary HTML selections use this canonical, credential-free HTTP(S) or `file:` URL for `element.source` and carry the same `element.sourceContext`; no markers or React owner are required. File documents use the bookmarklet loader's opaque-origin source-window/session contract; they are never runtime-frame sources. Runtime frames omit this option and retain strict page-source resolution. Both loaders use the same picker. The external host still owns screenshots. Design mode is unavailable for external documents.
14
+
15
+ Review commands and the host adapter are described in [Remote review](../../host/review/README.md). `startPageAgent` also accepts `pageSources` from the lock to validate the declared page-link context. The compiler projects editable linked page markers to page-relative paths before the agent sees them; ordinary library links retain their rejected library locations.
16
+
17
+ Design mode activates the same picker with `{ type: "mode", mode: "design" }`. Editable facet call sites (`BoxNode`, `ContainerNode`, `BrandBox`, `BrandContainer`, `Tile`, `Zone`, including named aliases and namespace imports from facet subpaths) and intrinsic SVG (`rect`, `circle`, `ellipse`, `line`, `polyline`, `polygon`, `path`, `text`, `tspan`, `g`) carry `data-source="<file>:<line>:<column>#<ordinal>@<hash>"`. They share the write server's source-order ordinal sequence. The hash is the first 12 SHA-256 hex digits of the original UTF-8 source. Other host tags retain positional markers. Import `EditableSourceMarker`, `EDITABLE_SOURCE_ATTRIBUTE`, `parseEditableSource(value: string): EditableSourceMarker` and `formatEditableSource(marker: EditableSourceMarker): string` from `@flanksource/page-runtime/markers`; this pure entry has no compiler, Node or React dependency.
18
+
19
+ The Design bridge types are exported from `@flanksource/page-runtime/schema`:
20
+
21
+ ```ts
22
+ type DesignHostMessage =
23
+ | { type: "design-override"; requestId: string; source: string; props: Record<string, JsonValue> }
24
+ | { type: "design-write"; requestId: string; page: string; source: string; edit: DesignEdit; choose?: string }
25
+ | { type: "design-write-result"; requestId: string; result: DesignWriteResult };
26
+ ```
27
+
28
+ The frame emits `design-selection` with `{ selection: AgentSelection, source: string, props: Record<string, JsonValue> }`. `props` projects scalar call-site props suitable for the host panel; React children, callbacks and renderer internals are excluded. Preview with `design-override`; null removes a prop. The override runs against the frame's development renderer and committed call-site fiber, and emits `design-override-result` with `{ requestId, source, ok: true }` or `{ requestId, source, ok: false, error }`. All live DOM instances carrying that selected marker update together.
29
+
30
+ Send `design-write` to ask the frame to emit `design-write-request` with `{ requestId, request: DesignWriteRequest }`. Supply the host API's page identifier explicitly (`report`, not the frame entry `report.tsx`, for playground's slug-based API). The host forwards `request` unchanged to `POST /__playground/visual-edits` and returns its validated response using `design-write-result`. The frame accepts only a pending request ID and acknowledges the result with the same frame event. The request carries `{ page, source, edit, choose? }`; its edit and result unions match the existing visual-edits API, including attributes, delete, text, style and applied/stale/refused/ambiguous/invalid results. The host owns refusal recovery and reload after a successful write. It can send another override to restore a failed preview. Requests must match a live selection and Design mode; package and runtime sources are rejected.
31
+
32
+ The overlay is a `[data-page-agent][data-react-grab-ignore]` sibling outside the page root. Pins, highlight and styles live in its shadow root. HTML export must remove that host and the fork's `[data-react-grab]` overlay hosts; Tailwind and readiness observers must observe the page root. Screenshot capture and clipboard writes belong to the host.
33
+
34
+ While focus is in the frame, Alt+C and Escape are forwarded as `keys`; Alt+C is ignored in editable controls and composition. Escape deactivates the picker. The host owns toggling its comment UI.
35
+
36
+ Run focused checks from the repository root:
37
+
38
+ ```bash
39
+ gavel test --work-dir ./packages/ui --framework vitest --recursive=false -- src/comments/anchoring
40
+ gavel test --work-dir ./packages/page-runtime --framework vitest --recursive=false -- agent
41
+ gavel test --work-dir ./packages/page-runtime --framework vitest --recursive=false -- --config src/frame/agent/vitest.browser.config.ts agent
42
+ gavel test --work-dir ./apps/playground --framework vitest --recursive=false -- src/comments src/bookmarklet
43
+ ```
44
+
45
+ The browser project uses agent-browser with Chromium because picking and pins require real hit testing and layout. The `agent-browser` executable must be on PATH. The package's shared browser config includes `src/**/*.browser.ts`.
46
+
47
+ `bootFrame` constructs the agent after styles are prepared and before mounting the page, routes all six command types, and wraps the page in `PageAgentProvider`. The bridge sends agent events and reports errors. Teardown and boot failures dispose the agent, page root and styles. HTML exports remove agent and picker hosts before inlining assets; Tailwind and readiness continue observing only the page root.