@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,96 @@
1
+ import { createLinkHost, connectLinkRuntime } from "../../host/link/index.ts";
2
+ import type { PageLock, RuntimeProfile } from "../../schema.ts";
3
+ import type { LinkBuild } from "../types.ts";
4
+ import { copyLinkToOpfs } from "./folder.ts";
5
+
6
+ type Configuration = { runtimeOrigin: string; sourceOrigin: string; profile: RuntimeProfile; lock: PageLock; build: LinkBuild };
7
+ const config = JSON.parse(document.getElementById("config")!.textContent!) as Configuration;
8
+ const setup = document.querySelector<HTMLIFrameElement>("#setup")!;
9
+ const linked = document.querySelector<HTMLIFrameElement>("#linked")!;
10
+ let controlLoads = 0;
11
+ let start = 0;
12
+ let restored = false;
13
+ let deniedWithoutOverrides = false;
14
+ let phase = 0;
15
+ let folderTransport = false;
16
+ let folderRequested = false;
17
+ let completeReload: (() => void) | undefined;
18
+ let opening!: () => void;
19
+ const activated = new Promise<void>((resolve) => { opening = resolve; });
20
+ const failure = (error: unknown) => { document.getElementById("status")!.textContent = String(error); void fetch("/record", { method: "POST", body: JSON.stringify({ error: String(error) }) }); };
21
+
22
+ async function runtimeRequest(value: unknown): Promise<{ compiled?: string[] }> {
23
+ return new Promise((resolve, reject) => {
24
+ const channel = new MessageChannel();
25
+ const timer = setTimeout(() => { channel.port1.close(); reject(new Error("test runtime request timeout")); }, 15000);
26
+ channel.port1.onmessage = (event) => { clearTimeout(timer); channel.port1.close(); if (event.data.error) reject(new Error(event.data.error)); else resolve(event.data); };
27
+ setup.contentWindow!.postMessage(value, config.runtimeOrigin, [channel.port2]);
28
+ });
29
+ }
30
+
31
+ window.addEventListener("message", (event) => {
32
+ if (event.source === setup.contentWindow && event.origin === config.runtimeOrigin && event.data === "runtime-ready") opening();
33
+ if (event.source === setup.contentWindow && event.origin === config.runtimeOrigin && event.data?.error) failure(event.data.error);
34
+ if (event.source === document.querySelector<HTMLIFrameElement>("#control")!.contentWindow && event.origin === config.runtimeOrigin && event.data === "control-ready") controlLoads++;
35
+ });
36
+
37
+ async function run() {
38
+ await activated;
39
+ const connection = await connectLinkRuntime({ runtimeOrigin: config.runtimeOrigin, profile: config.profile, developerOverrides: true });
40
+ const host = createLinkHost({ profile: config.profile, developerOverrides: true, transport: connection.request });
41
+ try { createLinkHost({ profile: config.profile, developerOverrides: false, transport: connection.request }); }
42
+ catch { deniedWithoutOverrides = true; }
43
+ if (!(await host.restore()).length) await host.server({ id: "checkout", url: config.sourceOrigin });
44
+ await host.close();
45
+ const restoredHost = createLinkHost({ profile: config.profile, developerOverrides: true, transport: connection.request });
46
+ restored = (await restoredHost.restore()).length === 1;
47
+ const lock = restoredHost.override({ lock: config.lock, ids: ["checkout"] });
48
+ await runtimeRequest({ message: { type: "open", page: "page.tsx", manifest: { dependencies: {} }, lock, files: { "page.tsx": `import React from "react"; import {createRoot} from "react-dom/client"; import {Version,DataTable,linkedVersionReact,linkedTableReact} from "@flanksource/clicky-ui/data"; globalThis.reactInstances = new Set([React, linkedVersionReact, linkedTableReact]).size; createRoot(document.getElementById("root")).render(React.createElement("main",null,React.createElement(Version),React.createElement("div",{style:{height:320}},React.createElement(DataTable,{data:[{name:"alpha",status:"ready"},{name:"beta",status:"ready"}],columns:[{key:"name",label:"Name"},{key:"status",label:"Status"}]}))));` } } });
49
+ let watcher = restoredHost.watch("checkout");
50
+ document.querySelector<HTMLButtonElement>("#folder")!.onclick = () => {
51
+ void (async () => {
52
+ await restoredHost.pickFolder({ id: "checkout" });
53
+ await watcher.stop(); watcher = restoredHost.watch("checkout");
54
+ start = performance.timeOrigin + performance.now(); linked.src = `${config.runtimeOrigin}/test-frame?page=page.tsx&manual-folder=${++phase}`;
55
+ await watcher.start({ onError: failure });
56
+ document.getElementById("status")!.textContent = "Folder linked. Edit src/data/Version.tsx in the selected checkout.";
57
+ })().catch((error: unknown) => { document.getElementById("status")!.textContent = String(error); });
58
+ };
59
+ restoredHost.registerFrame({ id: "linked", links: ["checkout"], reload() {
60
+ if (completeReload) throw new Error("Linked frame reload is already pending");
61
+ return new Promise<void>((resolve) => { completeReload = resolve; start = performance.timeOrigin + performance.now(); linked.src = `${config.runtimeOrigin}/test-frame?page=page.tsx&revision=${++phase}`; });
62
+ } });
63
+ restoredHost.registerFrame({ id: "control", links: [], reload() { throw new Error("Unlinked frame must never reload"); } });
64
+ window.addEventListener("message", (event) => {
65
+ if (event.source !== linked.contentWindow || event.origin !== config.runtimeOrigin) return;
66
+ void (async () => {
67
+ if (event.data.error) throw new Error(event.data.error);
68
+ if (!event.data.marker) return;
69
+ completeReload?.(); completeReload = undefined;
70
+ if (phase === 1) await watcher.start({ onError: failure });
71
+ const stats = await runtimeRequest({ stats: true });
72
+ await fetch("/record", { method: "POST", body: JSON.stringify({ ...event.data, elapsed: event.data.at - start, compiled: stats.compiled, controlLoads, restored, deniedWithoutOverrides, folderTransport }) });
73
+ if (phase === 0) { phase = 1; start = performance.timeOrigin + performance.now(); linked.src = `${config.runtimeOrigin}/test-frame?page=page.tsx&warm`; }
74
+ else if (phase === 1) phase = 2;
75
+ if (event.data.marker === "revision-12" && !folderRequested) {
76
+ folderRequested = true;
77
+ const files = await connection.request({ type: "files", id: "checkout" });
78
+ if (!files.files) throw new Error("Worker did not report source files");
79
+ const link = restoredHost.list()[0]; if (!link) throw new Error("Missing server link");
80
+ const directory = await copyLinkToOpfs({ link, files: Object.keys(files.files), build: config.build });
81
+ await watcher.stop();
82
+ await restoredHost.folder({ id: "checkout", directory });
83
+ await restoredHost.close();
84
+ const folderHost = createLinkHost({ profile: config.profile, developerOverrides: true, transport: connection.request });
85
+ const restoredLinks = await folderHost.restore();
86
+ if (restoredLinks[0]?.source.kind !== "folder" || !restoredLinks[0].directory) throw new Error("Directory handle did not survive IndexedDB storage");
87
+ folderTransport = true;
88
+ start = performance.timeOrigin + performance.now(); linked.src = `${config.runtimeOrigin}/test-frame?page=page.tsx&folder`;
89
+ }
90
+ })().catch(failure);
91
+ });
92
+ start = performance.timeOrigin + performance.now(); linked.src = `${config.runtimeOrigin}/test-frame?page=page.tsx`;
93
+ }
94
+ setup.src = `${config.runtimeOrigin}/setup`;
95
+ document.querySelector<HTMLIFrameElement>("#control")!.src = `${config.runtimeOrigin}/control`;
96
+ void run().catch(failure);
@@ -0,0 +1,19 @@
1
+ import type { LinkBuild, StoredLink } from "../types.ts";
2
+ import { readLinkFile } from "../source.ts";
3
+
4
+ export async function copyLinkToOpfs(options: { link: StoredLink; files: string[]; build: LinkBuild }): Promise<FileSystemDirectoryHandle> {
5
+ const root = await navigator.storage.getDirectory();
6
+ const folder = await root.getDirectoryHandle(`link-test-${crypto.randomUUID()}`, { create: true });
7
+ async function write(path: string, bytes: Uint8Array<ArrayBuffer>) {
8
+ let directory = folder;
9
+ const parts = path.split("/");
10
+ for (const part of parts.slice(0, -1)) directory = await directory.getDirectoryHandle(part, { create: true });
11
+ const writable = await (await directory.getFileHandle(parts.at(-1)!, { create: true })).createWritable();
12
+ try { await writable.write(bytes); } finally { await writable.close(); }
13
+ }
14
+ const prefix = `${options.build.library}@${options.build.version}/`;
15
+ const runtime = Object.keys(options.build.fragment.integrity).filter((path) => path.startsWith(prefix)).map((path) => path.slice(prefix.length));
16
+ for (const path of new Set([...options.files, ...runtime, ...Object.values(options.build.entries), ...Object.keys(options.build.generated)])) await write(path, new Uint8Array(await readLinkFile({ link: options.link, path })));
17
+ await write("dist/runtime/link.json", new TextEncoder().encode(JSON.stringify(options.build)));
18
+ return folder;
19
+ }
@@ -0,0 +1,30 @@
1
+ import { connectLinkRuntime } from "../../host/link/transport.ts";
2
+ import { exampleLink } from "../testing-fixtures.ts";
3
+
4
+ async function run() {
5
+ await new Promise<void>((resolve) => { window.addEventListener("message", (event) => { if (event.origin === location.origin && event.data === "worker-ready") resolve(); }); });
6
+ const connection = await connectLinkRuntime({ runtimeOrigin: location.origin, profile: { links: "allow" }, developerOverrides: true, relayPath: "/frame/_link-relay" });
7
+ const link = exampleLink(); link.source = { kind: "server", url: `${location.origin}/checkout/` }; link.build.modules["src/version.js"] = { resolutions: {} };
8
+ await connection.request({ type: "install", link });
9
+ const probe = document.createElement("iframe"); probe.src = "/frame/probe"; document.body.append(probe);
10
+ const reads: Array<{ code: string; compiled: string }> = [];
11
+ await new Promise<void>((resolve, reject) => {
12
+ window.addEventListener("message", (event) => {
13
+ if (event.origin !== location.origin || event.source !== probe.contentWindow) return;
14
+ void (async () => {
15
+ if (event.data.error) throw new Error(event.data.error);
16
+ reads.push(event.data);
17
+ if (reads.length === 1) probe.contentWindow!.postMessage("read", location.origin);
18
+ else if (reads.length === 2) {
19
+ await fetch("/edit", { method: "POST" });
20
+ await connection.request({ type: "invalidate", id: link.id, paths: ["src/version.js"] });
21
+ probe.contentWindow!.postMessage("read", location.origin);
22
+ } else resolve();
23
+ })().catch(reject);
24
+ });
25
+ });
26
+ const scopes = (await navigator.serviceWorker.getRegistrations()).map((registration) => new URL(registration.scope).pathname);
27
+ document.getElementById("result")!.textContent = JSON.stringify({ shellControlled: Boolean(navigator.serviceWorker.controller), scopes, reads });
28
+ connection.close(); document.title = "LINK-READY";
29
+ }
30
+ void run().catch((error: unknown) => { document.getElementById("error")!.textContent = String(error); document.title = "LINK-ERROR"; });
@@ -0,0 +1,26 @@
1
+ import { createServer } from "node:http";
2
+ import { fileURLToPath } from "node:url";
3
+ import { build } from "rolldown";
4
+
5
+ export async function startLocalLinkServer() {
6
+ async function bundle(entry: string) {
7
+ const output = await build({ input: fileURLToPath(new URL(entry, import.meta.url)), platform: "browser", resolve: { conditionNames: ["worker", "browser", "import", "default"] }, transform: { define: { "process.env.NODE_ENV": JSON.stringify("development"), "process.env": "{}" } }, output: { format: "iife" }, write: false });
8
+ const chunk = output.output.find((item) => item.type === "chunk"); if (!chunk || chunk.type !== "chunk") throw new Error("Missing local link fixture bundle"); return chunk.code;
9
+ }
10
+ const worker = await bundle("./local-worker.ts");
11
+ const client = await bundle("./local-client.ts");
12
+ let revision = 0;
13
+ const server = createServer((request, response) => {
14
+ const path = new URL(request.url!, "http://fixture.invalid").pathname;
15
+ if (path === "/frame/worker.js" || path === "/client.js") { response.setHeader("content-type", "text/javascript"); response.end(path === "/client.js" ? client : worker); return; }
16
+ if (path === "/checkout/src/version.js") { response.end(`export const value = "revision-${revision}";`); return; }
17
+ if (path === "/edit" && request.method === "POST") { revision++; response.end("ok"); return; }
18
+ response.setHeader("content-type", "text/html");
19
+ if (path === "/frame/setup") { response.end('<!doctype html><script>(async()=>{await navigator.serviceWorker.register("/frame/worker.js",{scope:"/frame/"});await navigator.serviceWorker.ready;if(!navigator.serviceWorker.controller)await new Promise(r=>navigator.serviceWorker.addEventListener("controllerchange",r,{once:true}));parent.postMessage("worker-ready",location.origin)})()</script>'); return; }
20
+ if (path === "/frame/probe") { response.end('<!doctype html><script>async function read(){try{const r=await fetch("/link/checkout/src/version.js?page=page.tsx");parent.postMessage({code:await r.text(),compiled:r.headers.get("x-link-compiled")},location.origin)}catch(e){parent.postMessage({error:String(e)},location.origin)}}window.addEventListener("message",e=>{if(e.source===parent&&e.origin===location.origin&&e.data==="read")read()});read()</script>'); return; }
21
+ response.end('<!doctype html><title>LOADING</title><h1>Local link</h1><pre id="result"></pre><pre id="error"></pre><iframe src="/frame/setup" hidden></iframe><script src="/client.js"></script>');
22
+ });
23
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
24
+ const address = server.address(); if (!address || typeof address === "string") throw new Error("No local link server port");
25
+ return { url: `http://127.0.0.1:${address.port}`, close: () => new Promise<void>((resolve, reject) => { server.closeAllConnections(); server.close((error) => error ? reject(error) : resolve()); }) };
26
+ }
@@ -0,0 +1,17 @@
1
+ import { createLinkRoutes } from "../../sw/link-route.ts";
2
+ import { exampleLock } from "../testing-fixtures.ts";
3
+ import type { RuntimeProfile } from "../../schema.ts";
4
+
5
+ const worker = self as unknown as {
6
+ location: Location; skipWaiting(): Promise<void>; clients: { claim(): Promise<void> };
7
+ addEventListener(type: string, receive: (event: { request: Request; waitUntil(pending: Promise<unknown>): void; respondWith(pending: Promise<Response>): void }) => void): void;
8
+ };
9
+ const profile: RuntimeProfile = { runtimeDomain: "127.0.0.1", embedders: [worker.location.origin], packageOrigin: worker.location.origin, registry: `${worker.location.origin}/registry`, managed: {}, policy: { dependencies: "strict" }, minReleaseAgeDays: 0, network: { allow: [] }, csp: { add: {} }, links: "allow", sources: ["host"], readinessTimeoutMs: 15000 };
10
+ const lock = exampleLock(); lock.map.imports.example = "/link/checkout/src/version.js";
11
+ const route = createLinkRoutes({ origin: worker.location.origin, version: "V-local", profile, caches, plugins: {} as never, load: async () => ({ lock, files: {} }) });
12
+ worker.addEventListener("install", (event) => event.waitUntil(worker.skipWaiting()));
13
+ worker.addEventListener("activate", (event) => event.waitUntil(worker.clients.claim()));
14
+ worker.addEventListener("fetch", (event) => {
15
+ if (new URL(event.request.url).pathname === "/frame/setup") return;
16
+ event.respondWith((async () => (await route(event.request)) ?? fetch(event.request))());
17
+ });
@@ -0,0 +1,131 @@
1
+ import { createServer, type Server, type IncomingMessage, type ServerResponse } from "node:http";
2
+ import { mkdir, mkdtemp, cp, symlink, readFile, writeFile, rename } from "node:fs/promises";
3
+ import { dirname, isAbsolute, join, resolve, sep } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { build } from "rolldown";
6
+ import { ResolverFactory } from "rolldown/experimental";
7
+ import type { PageLock, RuntimeProfile } from "../../schema.ts";
8
+ import { buildLinkRuntime } from "../build.ts";
9
+ import { composeLinkOverrides } from "../overrides.ts";
10
+ import { integrityOf, packageOf } from "../../build/trace.ts";
11
+ import { moduleUrl } from "../../sw/compiler.ts";
12
+
13
+ export type LinkRecord = { marker: string; at: number; elapsed: number; compiled: string[]; controlLoads: number; reactInstances: number; reactEvaluations: number; restored: boolean; deniedWithoutOverrides: boolean; folderTransport: boolean };
14
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), "../../../../..");
15
+ const here = dirname(fileURLToPath(import.meta.url));
16
+
17
+ async function listen(server: Server): Promise<string> {
18
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
19
+ const address = server.address(); if (!address || typeof address === "string") throw new Error("No server port");
20
+ return `http://127.0.0.1:${address.port}`;
21
+ }
22
+ async function bundle(entry: string, { format = "iife", external = [] }: { format?: "es" | "iife"; external?: string[] } = {}): Promise<string> {
23
+ const result = await build({ input: entry, external, platform: "browser", resolve: { conditionNames: ["worker", "browser", "import", "default"] }, transform: { define: { "process.env.NODE_ENV": JSON.stringify("development"), "process.env": "{}" } }, output: { format }, write: false });
24
+ const chunk = result.output.find((file) => file.type === "chunk"); if (!chunk || chunk.type !== "chunk") throw new Error("Missing test bundle"); return chunk.code;
25
+ }
26
+ function serve(handle: (request: IncomingMessage, response: ServerResponse) => Promise<void>): Server {
27
+ return createServer((request, response) => { void handle(request, response).catch((error: unknown) => { console.error("Link test request failed", error); response.statusCode = 500; response.end("Link test request failed"); }); });
28
+ }
29
+
30
+ export async function startLinkTestServer() {
31
+ await mkdir(join(root, ".tmp/H-link"), { recursive: true });
32
+ const checkout = await mkdtemp(join(root, ".tmp/H-link/checkout-"));
33
+ await cp(join(root, "packages/ui/src"), join(checkout, "src"), { recursive: true });
34
+ await symlink(join(root, "packages/ui/node_modules"), join(checkout, "node_modules"), "dir");
35
+ await writeFile(join(checkout, "package.json"), JSON.stringify({ name: "@flanksource/clicky-ui", version: "9.0.0", type: "module", sideEffects: ["**/*.css"], exports: { "./data": "./dist/Version.js" } }));
36
+ const original = 'import * as __linkProbeReact from "react";\n' + await readFile(join(checkout, "src/data/Version.tsx"), "utf8") + '\nexport const linkedVersionReact = __linkProbeReact.default;\n';
37
+ const tablePath = join(checkout, "src/data/DataTable.tsx");
38
+ await writeFile(tablePath, 'import * as __linkProbeReact from "react";\n' + await readFile(tablePath, "utf8") + '\nexport const linkedTableReact = __linkProbeReact.default;\n');
39
+ const edit = async (revision: number) => {
40
+ const path = join(checkout, "src/data/Version.tsx");
41
+ const marker = '<span data-link-edit>revision-' + revision + '</span>';
42
+ await writeFile(path + ".next", original.replace("{parts.length > 0 &&", marker + "{parts.length > 0 &&"));
43
+ await rename(path + ".next", path);
44
+ };
45
+ await edit(0);
46
+ await writeFile(join(checkout, "src/link-data.ts"), 'export { Version, linkedVersionReact } from "./data/Version"; export { DataTable, linkedTableReact } from "./data/DataTable";');
47
+ const dist = await build({ input: join(checkout, "src/link-data.ts"), platform: "browser", external: (source) => !source.startsWith(".") && !isAbsolute(source), output: { dir: join(checkout, "dist"), format: "es", preserveModules: true, preserveModulesRoot: join(checkout, "src"), entryFileNames: "[name].js" } });
48
+ const entry = dist.output.find((file) => file.type === "chunk" && file.isEntry);
49
+ if (!entry) throw new Error("Missing Version dist fixture");
50
+ await writeFile(join(checkout, "package.json"), JSON.stringify({ name: "@flanksource/clicky-ui", version: "9.0.0", type: "module", sideEffects: ["**/*.css"], exports: { "./data": `./dist/${entry.fileName}` } }));
51
+ const built = await buildLinkRuntime({ libraryDir: checkout, outDir: join(checkout, "dist/runtime"), entries: { "@flanksource/clicky-ui/data": "src/link-data.ts" }, defines: { __CLICKY_COMMIT__: "checkout-commit", __CLICKY_TAG__: "local", __CLICKY_DATE__: "2026-01-01", __CLICKY_DIRTY__: false } });
52
+ const target = built.fragment.imports.react!;
53
+ const path = join(checkout, target.slice(`${built.library}@${built.version}/`.length));
54
+ const code = "globalThis.__LINK_REACT_EVALUATIONS__ = (globalThis.__LINK_REACT_EVALUATIONS__ ?? 0) + 1;\n" + await readFile(path, "utf8");
55
+ await writeFile(path, code); built.fragment.integrity[target] = integrityOf(code);
56
+ await writeFile(join(checkout, "dist/runtime/link.json"), JSON.stringify(built));
57
+ const source = serve(async (request, response) => {
58
+ response.setHeader("access-control-allow-origin", "*"); response.setHeader("cache-control", "no-store");
59
+ const path = resolve(checkout, "." + decodeURIComponent(new URL(request.url!, "http://localhost").pathname));
60
+ if (!path.startsWith(checkout + sep)) { response.statusCode = 403; response.end("outside checkout"); return; }
61
+ try { response.end(await readFile(path)); } catch (error) { console.error("Link test file unavailable", error); response.statusCode = 404; response.end("Link test file unavailable"); }
62
+ });
63
+ const sourceOrigin = await listen(source);
64
+ let hostOrigin = ""; let runtimeOrigin = "";
65
+ const profile: RuntimeProfile = { runtimeDomain: "127.0.0.1", embedders: [], packageOrigin: "http://127.0.0.1", registry: "http://127.0.0.1/registry", managed: {}, policy: { dependencies: "strict" }, minReleaseAgeDays: 0, network: { allow: [] }, csp: { add: {} }, links: "allow", sources: ["host"], readinessTimeoutMs: 15000 };
66
+ const baseLock: PageLock = { lock: 2, packageOrigin: profile.packageOrigin, page: "page.tsx", versions: { "@flanksource/clicky-ui": "1.0.0" }, map: { imports: {}, scopes: {} }, integrity: {}, remaps: {}, barrels: { modules: [], barrels: {} } };
67
+ const lock = composeLinkOverrides({ lock: baseLock, links: [{ id: "checkout", build: built, source: { kind: "server", url: sourceOrigin } }], profile, developerOverrides: true });
68
+ const resolver = new ResolverFactory({ conditionNames: ["browser", "import", "module", "default"], extensions: [".js", ".mjs"], symlinks: true });
69
+ const runtimeFiles = new Map<string, string>();
70
+ // Transitive packages are only resolvable from the packages that depend on them, so each one is looked up
71
+ // from the checkout and every package directory found so far, and must match the traced version.
72
+ const packageDirs = [checkout];
73
+ const pending = Object.keys(built.fragment.integrity).filter((path) => !path.startsWith(`${built.library}@${built.version}/`));
74
+ while (pending.length) {
75
+ const found = pending.filter((path) => {
76
+ const match = /^(@[^/]+\/[^@]+|[^@]+)@([^/]+)\/(.*)$/.exec(path); if (!match) throw new Error(`Invalid package path ${path}`);
77
+ for (const base of packageDirs) {
78
+ const result = resolver.sync(base, match[1]!);
79
+ if (!result.path) continue;
80
+ const pkg = packageOf(result.path);
81
+ if (pkg.version !== match[2]) continue;
82
+ runtimeFiles.set(path, join(pkg.dir, match[3]!));
83
+ if (!packageDirs.includes(pkg.dir)) packageDirs.push(pkg.dir);
84
+ return true;
85
+ }
86
+ return false;
87
+ });
88
+ if (!found.length) throw new Error(`Missing dependency manifests: ${pending.join(", ")}`);
89
+ for (const path of found) pending.splice(pending.indexOf(path), 1);
90
+ }
91
+ const workerCode = await bundle(join(here, "worker.ts"));
92
+ const clientCode = await bundle(join(here, "client.ts"));
93
+ const editingCode = await bundle(join(here, "../../editing.ts"), { format: "es", external: ["react"] });
94
+ const runtime = serve(async (request, response) => {
95
+ const url = new URL(request.url!, runtimeOrigin); response.setHeader("cache-control", "no-store");
96
+ if (url.pathname === "/worker.js") { response.setHeader("content-type", "text/javascript"); response.end(workerCode); return; }
97
+ if (url.pathname === "/editing.js") { response.setHeader("content-type", "text/javascript"); response.end(editingCode); return; }
98
+ if (url.pathname === "/profile.json") { response.setHeader("content-type", "application/json"); response.end(JSON.stringify(profile)); return; }
99
+ if (url.pathname.startsWith("/packages/")) { const file = runtimeFiles.get(decodeURIComponent(url.pathname.slice(10))); if (!file) throw new Error(`Missing package ${url.pathname}`); response.end(await readFile(file)); return; }
100
+ response.setHeader("content-type", "text/html");
101
+ const hostConfig = `<script type="application/json" id="host-origin">${JSON.stringify(hostOrigin).replaceAll("<", "\\u003c")}</script>`;
102
+ if (url.pathname === "/setup") { response.end(`<!doctype html>${hostConfig}<script>const hostOrigin=JSON.parse(document.getElementById("host-origin").textContent);navigator.serviceWorker.addEventListener("message",e=>parent.postMessage(e.data,hostOrigin));window.addEventListener("message",e=>{if(e.source!==parent||e.origin!==hostOrigin)return;navigator.serviceWorker.controller.postMessage(e.data,e.ports)});(async()=>{await navigator.serviceWorker.register("/worker.js");await navigator.serviceWorker.ready;if(!navigator.serviceWorker.controller)await new Promise(r=>navigator.serviceWorker.addEventListener("controllerchange",r,{once:true}));parent.postMessage("runtime-ready",hostOrigin)})()</script>`); return; }
103
+ if (url.pathname === "/control") { response.end(`<!doctype html><p>Unlinked control</p>${hostConfig}<script>const hostOrigin=JSON.parse(document.getElementById("host-origin").textContent);parent.postMessage("control-ready",hostOrigin)</script>`); return; }
104
+ if (url.pathname === "/test-frame") {
105
+ const map = { imports: Object.fromEntries(Object.entries(lock.map.imports).map(([name, target]) => [name, moduleUrl(target)])), scopes: Object.fromEntries(Object.entries(lock.map.scopes).map(([scope, table]) => [scope, Object.fromEntries(Object.entries(table).map(([name, target]) => [name, moduleUrl(target)]))])) };
106
+ response.end(`<!doctype html><html><head><script type="importmap">${JSON.stringify(map).replaceAll("<", "\\u003c")}</script></head><body><div id="root"></div>${hostConfig}<script type="module">const hostOrigin=JSON.parse(document.getElementById("host-origin").textContent);try{await import("/src/page.tsx?page=page.tsx");const ready=()=>{const marker=document.querySelector("[data-link-edit]");if(marker&&document.querySelectorAll("tbody tr").length===2)requestAnimationFrame(()=>requestAnimationFrame(()=>parent.postMessage({marker:marker.textContent,at:performance.timeOrigin+performance.now(),reactInstances:globalThis.reactInstances,reactEvaluations:globalThis.__LINK_REACT_EVALUATIONS__},hostOrigin)));else requestAnimationFrame(ready)};ready()}catch(e){parent.postMessage({error:String(e)},hostOrigin)}</script></body></html>`); return;
107
+ }
108
+ response.statusCode = 404; response.end("missing runtime test page");
109
+ });
110
+ runtimeOrigin = await listen(runtime); profile.packageOrigin = `${runtimeOrigin}/packages`;
111
+ baseLock.packageOrigin = profile.packageOrigin; lock.packageOrigin = profile.packageOrigin;
112
+ const records: LinkRecord[] = []; const errors: string[] = [];
113
+ const host = serve(async (request, response) => {
114
+ if (request.url === "/client.js") { response.setHeader("content-type", "text/javascript"); response.end(clientCode); return; }
115
+ if (request.url === "/record") { const chunks = []; for await (const chunk of request) chunks.push(chunk); const record = JSON.parse(Buffer.concat(chunks).toString()); if (record.error) errors.push(record.error); else records.push(record); response.end("ok"); return; }
116
+ response.setHeader("content-type", "text/html"); response.end(`<!doctype html><h1>Linked checkout</h1><button id="folder">Link folder</button><p id="status">File-server link</p><iframe id="setup" hidden></iframe><iframe id="linked" style="width:900px;height:400px"></iframe><iframe id="control"></iframe><script type="application/json" id="config">${JSON.stringify({ runtimeOrigin, sourceOrigin, profile, lock: baseLock, build: built }).replaceAll("<", "\\u003c")}</script><script src="/client.js"></script>`);
117
+ });
118
+ hostOrigin = await listen(host); profile.embedders = [hostOrigin];
119
+ return { hostOrigin, checkout, edit, async next(): Promise<LinkRecord> {
120
+ const deadline = Date.now() + 30000;
121
+ while (!records.length) { if (errors.length) throw new Error(errors.join("\n")); if (Date.now() > deadline) throw new Error("Timed out waiting for linked frame"); await new Promise((resolve) => setTimeout(resolve, 25)); }
122
+ return records.shift()!;
123
+ }, async close() { await Promise.all([host, runtime, source].map((server) => new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve())))); } };
124
+ }
125
+
126
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
127
+ const server = await startLinkTestServer();
128
+ process.stdout.write(`Link verification host: ${server.hostOrigin}\nFolder to select: ${server.checkout}\n`);
129
+ process.once("SIGINT", () => { void server.close(); });
130
+ process.once("SIGTERM", () => { void server.close(); });
131
+ }
@@ -0,0 +1,32 @@
1
+ import { createRouter } from "../../sw/router.ts";
2
+ import { BASE_PLUGINS } from "../../sw/compiler.ts";
3
+ import { createPageClients } from "../../sw/page-clients.ts";
4
+ import type { RuntimeProfile } from "../../schema.ts";
5
+
6
+ const worker = self as unknown as {
7
+ location: Location; skipWaiting(): Promise<void>;
8
+ clients: { claim(): Promise<void>; get(id: string): Promise<{ id: string; url: string } | undefined>; matchAll(options?: { type: "all"; includeUncontrolled: boolean }): Promise<Array<{ id: string; postMessage(value: unknown): void }>> };
9
+ addEventListener(type: string, listener: (event: { request: Request; clientId: string; resultingClientId: string; data: { stats?: boolean; message?: unknown }; ports: MessagePort[]; waitUntil(promise: Promise<unknown>): void; respondWith(promise: Promise<Response>): void }) => void): void;
10
+ };
11
+ const router = fetch("/profile.json").then(async (response) => createRouter({ origin: worker.location.origin, version: "link-browser", profile: await response.json() as RuntimeProfile, caches, plugins: BASE_PLUGINS }));
12
+ const pageClients = createPageClients({ origin: worker.location.origin, clients: worker.clients });
13
+ let compiled: string[] = [];
14
+ worker.addEventListener("install", (event) => event.waitUntil(worker.skipWaiting()));
15
+ worker.addEventListener("activate", (event) => event.waitUntil(worker.clients.claim()));
16
+ worker.addEventListener("message", (event) => event.waitUntil((async () => {
17
+ try {
18
+ if (event.data.stats) { event.ports[0]!.postMessage({ compiled }); compiled = []; }
19
+ else { await (await router).message(event.data.message); event.ports[0]!.postMessage({ ok: true }); }
20
+ } catch (error) { event.ports[0]!.postMessage({ error: String(error) }); }
21
+ })()));
22
+ worker.addEventListener("fetch", (event) => {
23
+ const url = new URL(event.request.url);
24
+ if (url.origin !== worker.location.origin || !/^\/(src|link|npm|frame|__runtime)\//.test(url.pathname)) return;
25
+ event.respondWith((async () => {
26
+ const { request, owner } = await pageClients.request(event);
27
+ const response = await (await router).route(request, { onError: (error) => { void worker.clients.matchAll().then((clients) => { for (const client of clients) client.postMessage({ error: `${error.phase}: ${error.file}: ${error.message}` }); }); } });
28
+ if (response.headers.get("x-link-compiled") === "1") compiled.push(url.pathname);
29
+ event.waitUntil(pageClients.served({ event, owner, response }));
30
+ return response;
31
+ })());
32
+ });
@@ -0,0 +1,20 @@
1
+ import type { StoredLink } from "./types.ts";
2
+ import type { createLinkStore } from "./storage.ts";
3
+
4
+ export function memoryLinkStorage(): ReturnType<typeof createLinkStore> {
5
+ const links = new Map<string, StoredLink>();
6
+ return { async get(id) { const link = links.get(id); if (!link) throw new Error(`Unknown library link ${id}`); return structuredClone(link); }, async put(link) { links.set(link.id, structuredClone(link)); }, async list() { return [...links.values()].map((link) => structuredClone(link)); }, async remove(id) { links.delete(id); }, async close() {} };
7
+ }
8
+
9
+ export function memoryCaches(): CacheStorage {
10
+ const stores = new Map<string, Map<string, Response>>();
11
+ const address = (key: RequestInfo | URL) => typeof key === "string" ? key : key instanceof URL ? key.href : key.url;
12
+ return {
13
+ async open(name: string) {
14
+ const entries = stores.get(name) ?? new Map<string, Response>(); stores.set(name, entries);
15
+ return { async put(key: RequestInfo | URL, response: Response) { entries.set(address(key), response.clone()); }, async match(key: RequestInfo | URL) { return entries.get(address(key))?.clone(); }, async keys() { return [...entries.keys()].map((key) => new Request(key)); }, async delete(key: RequestInfo | URL) { return entries.delete(address(key)); } };
16
+ },
17
+ async keys() { return [...stores.keys()]; },
18
+ async delete(name: string) { return stores.delete(name); },
19
+ } as unknown as CacheStorage;
20
+ }
@@ -0,0 +1,16 @@
1
+ import type { LibraryLink } from "./types.ts";
2
+ import type { PageLock } from "../schema.ts";
3
+
4
+ export function exampleLink(): LibraryLink {
5
+ return { id: "checkout", source: { kind: "server", url: "http://127.0.0.1:9000/" }, build: {
6
+ link: 1, library: "@flanksource/clicky-ui", version: "2.0.0",
7
+ fragment: { fragment: 1, name: "@flanksource/clicky-ui", imports: { react: "@flanksource/clicky-ui@2.0.0/dist/runtime/react.js", "@flanksource/clicky-ui": "@flanksource/clicky-ui@2.0.0/dist/index.js" }, scopes: {}, inherits: [], aliases: {}, remaps: {}, integrity: { "@flanksource/clicky-ui@2.0.0/dist/runtime/react.js": "sha384-react" } },
8
+ entries: { "@flanksource/clicky-ui": "src/index.ts" },
9
+ modules: { "src/index.ts": { resolutions: { "./Counter": "src/Counter.tsx" } }, "src/Counter.tsx": { resolutions: {} }, "src/untouched.ts": { resolutions: {} } },
10
+ barrels: { modules: ["src/Counter.tsx"], barrels: { "src/index.ts": { Counter: 0 } } }, defines: { __CHECKOUT__: "local-commit" }, generated: {},
11
+ } };
12
+ }
13
+
14
+ export function exampleLock(): PageLock {
15
+ return { lock: 2, packageOrigin: "https://packages.example", page: "page.tsx", versions: { "@flanksource/clicky-ui": "1.0.0" }, map: { imports: { react: "/npm/react@18/index.js", "@flanksource/clicky-ui": "/npm/@flanksource/clicky-ui@1.0.0/index.js" }, scopes: { "/npm/@acme/facet@1/": { react: "/npm/react@18/index.js" } } }, integrity: {}, remaps: {}, barrels: { modules: [], barrels: {} } };
16
+ }
@@ -0,0 +1,27 @@
1
+ import type { BarrelIndex, Fragment } from "../schema.ts";
2
+ export type CommonJsSource = { hash: string; target: string };
3
+
4
+ export type LinkBuild = {
5
+ link: 1;
6
+ library: string;
7
+ version: string;
8
+ fragment: Fragment;
9
+ entries: Record<string, string>;
10
+ modules: Record<string, { resolutions: Record<string, string> }>;
11
+ barrels: BarrelIndex;
12
+ defines: Record<string, string | boolean | number>;
13
+ generated: Record<string, string>;
14
+ pageSources?: Array<Omit<import("./page-sources.ts").PageSourceRoot, "link">>;
15
+ commonjs?: Record<string, CommonJsSource>;
16
+ package?: { dependencies?: Record<string, string>; peerDependencies?: Record<string, string> };
17
+ };
18
+ export type LinkSource = { kind: "server"; url: string } | { kind: "folder"; session?: string };
19
+ export type LibraryLink = { id: string; build: LinkBuild; source: LinkSource };
20
+ export type StoredLink = LibraryLink & { directory?: FileSystemDirectoryHandle };
21
+ export type LinkCommand =
22
+ | { type: "install"; link: StoredLink }
23
+ | { type: "remove"; id: string }
24
+ | { type: "files"; id: string }
25
+ | { type: "invalidate"; id: string; paths: string[] };
26
+ export type LinkReply = { ok: true; files?: Record<string, string> };
27
+ export type LinkFrame = { id: string; links: readonly string[]; reload(): void | Promise<void> };
@@ -0,0 +1,44 @@
1
+ import type { RuntimeProfile } from "../schema.ts";
2
+ import { validateSourcePath } from "../host/validation.ts";
3
+ import type { LibraryLink } from "./types.ts";
4
+ import { validatePageSources } from "./page-sources.ts";
5
+ import { BASE_PACKAGES } from "../sw/composition.ts";
6
+
7
+ export function assertLinksAllowed(options: { profile: Pick<RuntimeProfile, "links">; developerOverrides: boolean }): void {
8
+ if (options.profile.links !== "allow" || options.developerOverrides !== true) throw new Error("Library links require links: allow and host developer overrides");
9
+ }
10
+
11
+ export function linkUrl(id: string, path: string): string {
12
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) throw new Error(`Invalid link id ${id}`);
13
+ validateSourcePath(path);
14
+ return `/link/${id}/${path.split("/").map(encodeURIComponent).join("/")}`;
15
+ }
16
+
17
+ export function validateLink(link: LibraryLink): void {
18
+ linkUrl(link.id, "package.json");
19
+ const build = link.build;
20
+ if (BASE_PACKAGES.includes(build.library)) throw new Error(`${build.library}: singleton checkouts must be supplied by the clicky-ui runtime set`);
21
+ if (build.pageSources !== undefined) validatePageSources(build.pageSources.map((root) => ({ ...root, link: link.id })));
22
+ if (build.link !== 1 || !build.library || !build.version || build.fragment.fragment !== 1 || build.fragment.name !== build.library) throw new Error("Invalid checkout link manifest; rebuild with buildLinkRuntime (buildLibraryRuntime)");
23
+ if (link.source.kind === "server") {
24
+ const url = new URL(link.source.url);
25
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error(`Invalid link server URL ${url}`);
26
+ } else if (link.source.kind !== "folder") throw new Error("Unknown link source kind");
27
+ if (!Object.keys(build.entries).length) throw new Error(`${build.library}: link must declare source entry points`);
28
+ for (const [specifier, path] of Object.entries(build.entries)) {
29
+ if (specifier !== build.library && !specifier.startsWith(`${build.library}/`)) throw new Error(`Link entry ${specifier} is outside ${build.library}`);
30
+ validateSourcePath(path);
31
+ if (!Object.hasOwn(build.modules, path)) throw new Error(`Link entry ${specifier}: missing source module ${path}`);
32
+ }
33
+ for (const path of [...Object.keys(build.modules), ...Object.keys(build.generated)]) validateSourcePath(path);
34
+ for (const [path, conversion] of Object.entries(build.commonjs ?? {})) {
35
+ validateSourcePath(path); validateSourcePath(conversion.target);
36
+ if (!build.modules[path] || !/^[a-f0-9]{12}$/.test(conversion.hash) || !build.fragment.integrity[`${build.library}@${build.version}/${conversion.target}`]) throw new Error(`Invalid CommonJS conversion metadata for ${path}`);
37
+ }
38
+ for (const name of Object.keys(build.defines)) if (!/^[A-Za-z_$][\w$]*$/.test(name)) throw new Error(`Invalid checkout constant ${name}`);
39
+ }
40
+
41
+ export function missingLinkFile(link: LibraryLink, path: string): Error {
42
+ const command = link.build.generated[path] ?? (link.build.library === "@flanksource/clicky-ui" && path.startsWith("src/icons") ? "pnpm --filter @flanksource/clicky-ui build:icons" : undefined);
43
+ return new Error(`${link.build.library}: missing checkout file ${path}; ${command ? `run \`${command}\`` : "rebuild the checkout with buildLinkRuntime (buildLibraryRuntime)"}`);
44
+ }
@@ -0,0 +1,3 @@
1
+ import { defineConfig } from "vitest/config";
2
+
3
+ export default defineConfig({ test: { name: "link-chromium", environment: "node", include: ["src/link/link.browser.ts"], testTimeout: 120000, hookTimeout: 120000, fileParallelism: false } });
package/src/markers.ts ADDED
@@ -0,0 +1,18 @@
1
+ export type EditableSourceMarker = { file: string; line: number; column: number; ordinal: number; hash: string };
2
+ export const EDITABLE_SOURCE_ATTRIBUTE = "data-source";
3
+ const MARKER = /^(.+):(\d+):(\d+)#(\d+)@([0-9a-f]{12})$/;
4
+
5
+ export function formatEditableSource({ file, line, column, ordinal, hash }: EditableSourceMarker): string {
6
+ if (!file || /["\\\r\n]/.test(file)) throw new Error(`cannot mark editable source in ${JSON.stringify(file)}: unsupported file name`);
7
+ if (![line, column].every((value) => Number.isSafeInteger(value) && value > 0) || !Number.isSafeInteger(ordinal) || ordinal < 0) throw new Error("invalid editable source position or ordinal");
8
+ if (!/^[0-9a-f]{12}$/.test(hash)) throw new Error(`invalid source hash ${JSON.stringify(hash)}`);
9
+ return `${file}:${line}:${column}#${ordinal}@${hash}`;
10
+ }
11
+
12
+ export function parseEditableSource(value: string): EditableSourceMarker {
13
+ const match = MARKER.exec(value);
14
+ if (!match) throw new Error(`malformed ${EDITABLE_SOURCE_ATTRIBUTE} ${JSON.stringify(value)}; expected <file>:<line>:<column>#<ordinal>@<hash>`);
15
+ const marker = { file: match[1]!, line: Number(match[2]), column: Number(match[3]), ordinal: Number(match[4]), hash: match[5]! };
16
+ formatEditableSource(marker);
17
+ return marker;
18
+ }
@@ -0,0 +1,27 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createPublication, type Publication } from "./publish.ts";
3
+ import { withPackageLock } from "./lock.ts";
4
+
5
+ export async function runPackageBuild(options: { libraryDir: string; command: string; args: string[] }): Promise<Publication> {
6
+ return withPackageLock({ libraryDir: options.libraryDir, run: async () => {
7
+ await new Promise<void>((done, fail) => {
8
+ const child = spawn(options.command, options.args, { cwd: options.libraryDir, stdio: "inherit", detached: process.platform !== "win32" });
9
+ const signal = (value: NodeJS.Signals) => {
10
+ if (process.platform === "win32") { child.kill(value); return; }
11
+ if (child.pid) {
12
+ try { process.kill(-child.pid, value); }
13
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; }
14
+ }
15
+ };
16
+ const term = () => signal("SIGTERM");
17
+ const int = () => signal("SIGINT");
18
+ process.once("SIGTERM", term); process.once("SIGINT", int);
19
+ child.once("error", fail);
20
+ child.once("close", (code, signal) => {
21
+ process.off("SIGTERM", term); process.off("SIGINT", int);
22
+ if (code === 0) done(); else fail(new Error(`Package build failed: ${signal ?? code}`));
23
+ });
24
+ });
25
+ return createPublication({ libraryDir: options.libraryDir });
26
+ } });
27
+ }
@@ -0,0 +1,2 @@
1
+ if (process.argv[2] === "interrupt") process.kill(process.pid, "SIGTERM");
2
+ else process.exitCode = 17;
@@ -0,0 +1,3 @@
1
+ export { publishPackage, readPublication, publicationRoot, atomicJson, type Publication } from "./publish.ts";
2
+ export { runPackageBuild } from "./build.ts";
3
+ export type { PackageCatalog, PackageBuild } from "./schema.ts";
@@ -0,0 +1,32 @@
1
+ import { mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ import { setTimeout } from "node:timers/promises";
4
+
5
+ export async function withPackageLock<T>(options: { libraryDir: string; run: () => Promise<T> }): Promise<T> {
6
+ const root = resolve(await realpath(options.libraryDir), ".tmp/package-publications");
7
+ const lock = resolve(root, "build.lock");
8
+ await mkdir(root, { recursive: true });
9
+ let missingOwner = 0;
10
+ for (;;) {
11
+ try { await mkdir(lock); break; }
12
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
13
+ try {
14
+ const owner = JSON.parse(await readFile(resolve(lock, "owner.json"), "utf8")) as { pid: number };
15
+ missingOwner = 0;
16
+ if (!Number.isInteger(owner.pid) || owner.pid <= 0) throw new Error(`Invalid package build lock: ${lock}`);
17
+ try { process.kill(owner.pid, 0); }
18
+ catch (error) {
19
+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
20
+ throw new Error(`Interrupted build left a lock at ${lock}; its owner ${owner.pid} has stopped. Remove that lock before rebuilding.`);
21
+ }
22
+ } catch (error) {
23
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
24
+ if (++missingOwner > 20) throw new Error(`Package build lock has no owner: ${lock}. Confirm no build is running before removing it.`);
25
+ }
26
+ await setTimeout(250);
27
+ }
28
+ try {
29
+ await writeFile(resolve(lock, "owner.json"), JSON.stringify({ pid: process.pid, started: new Date().toISOString() }));
30
+ return await options.run();
31
+ } finally { await rm(lock, { recursive: true, force: true }); }
32
+ }
@@ -0,0 +1,14 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+
4
+ export type PackageManifest = Record<string, unknown> & { name: string; version: string };
5
+ export function validateManifest(value: unknown): PackageManifest {
6
+ if (!value || typeof value !== "object") throw new Error("Package manifest must be an object");
7
+ const manifest = value as PackageManifest;
8
+ if (typeof manifest.name !== "string" || !/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(manifest.name)) throw new Error("Invalid package name");
9
+ if (typeof manifest.version !== "string" || !/^\d+\.\d+\.\d+(?:-[\da-zA-Z.-]+)?(?:\+[\da-zA-Z.-]+)?$/.test(manifest.version)) throw new Error("Invalid package version");
10
+ return manifest;
11
+ }
12
+ export async function readManifest(directory: string): Promise<PackageManifest> {
13
+ return validateManifest(JSON.parse(await readFile(resolve(directory, "package.json"), "utf8")));
14
+ }