@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,269 @@
1
+ import { randomUUID } from "@flanksource/clicky-ui/utils";
2
+ import type { BridgeEnvelope, FrameConfig, FrameMessage, JsonValue, RuntimeError, RuntimePhase, RuntimeProfile } from "../schema.ts";
3
+ import { createFrameBridge, workerRequest } from "./bridge.ts";
4
+ import { waitForReadiness } from "./readiness.ts";
5
+ import { exportHtml } from "./export.ts";
6
+ import { withExportRender } from "./export-page.ts";
7
+ import { runtimeError } from "../sw/errors.ts";
8
+ import { validateProfile } from "../sw/profile.ts";
9
+ import { validateFrameMessage } from "../host/validation.ts";
10
+ import { loadPageStyles, pageTailwind, preparePageStyles } from "./boot-styles.ts";
11
+ import type { PageAgent } from "./agent/index.ts";
12
+ import { PAGE_AGENT_URL } from "../sw/runtime-module.ts";
13
+ import { createFrameActivity } from "./activity.ts";
14
+ import { mountPage, type PageModule, type PageLayout, type ReactRuntime } from "./mount-page.ts";
15
+ import { frameRenderJobs } from "./render-job.ts";
16
+
17
+ export type PageStyles = Awaited<ReturnType<typeof preparePageStyles>>;
18
+
19
+ function detail(error: unknown, phase: RuntimePhase, file: string): RuntimeError {
20
+ if (error && typeof error === "object" && "pageRuntime" in error) return error.pageRuntime as RuntimeError;
21
+ return runtimeError({ error, phase, file });
22
+ }
23
+
24
+ export async function ensureController(options: { timeoutMs?: number } = {}): Promise<boolean> {
25
+ if (!("serviceWorker" in navigator)) throw new Error("navigator.serviceWorker is unavailable");
26
+ const controlled = navigator.serviceWorker.controller;
27
+ await navigator.serviceWorker.register("/sw.js", { scope: "/frame/" });
28
+ const registration = await withTimeout(navigator.serviceWorker.ready, options.timeoutMs ?? 15000, "service worker activation timeout");
29
+ const active = registration.installing ?? registration.waiting ?? registration.active;
30
+ if (!active) throw new Error("service worker registration has no active worker");
31
+ if (active.state !== "activated") await withTimeout(new Promise<void>((resolve, reject) => active.addEventListener("statechange", () => {
32
+ if (active.state === "activated") resolve();
33
+ if (active.state === "redundant") reject(new Error("service worker installation failed"));
34
+ })), options.timeoutMs ?? 15000, "service worker activation timeout");
35
+ if (controlled && navigator.serviceWorker.controller === active) return true;
36
+ const url = new URL(location.href);
37
+ if (url.searchParams.has("runtime-reloaded")) throw new Error("service worker does not control frame after one reload");
38
+ url.searchParams.set("runtime-reloaded", "1"); location.replace(url); return false;
39
+ }
40
+
41
+ export async function bootFrame(): Promise<void> {
42
+ performance.mark("page-runtime:boot");
43
+ let phase: RuntimePhase = "resolve";
44
+ let config: FrameConfig | undefined;
45
+ let lockAnnounced = false;
46
+ const announceLock = () => { if (config && !lockAnnounced) { bridge.send({ type: "lock", lock: config.lock }); lockAnnounced = true; } };
47
+ let ready = false;
48
+ let agent: PageAgent | undefined;
49
+ let styles: PageStyles | undefined;
50
+ let unmount: (() => void) | undefined;
51
+ let updateData: ((value: JsonValue) => Promise<void>) | undefined;
52
+ let updateSources: ((files: Record<string, string | null>) => Promise<void>) | undefined;
53
+ let latestData: JsonValue = null;
54
+ let exportMount: ((module: PageModule, root: HTMLElement) => { mounted: Promise<void>; unmount: () => void }) | undefined;
55
+ let receiveData!: (data: JsonValue) => void;
56
+ const data = new Promise<JsonValue>((resolve) => { receiveData = resolve; });
57
+ const bridge = createFrameBridge({ receive: (envelope) => { void receive(envelope).catch((error: unknown) => report(error, envelope.id)); }, error: (error) => report(error) });
58
+ const report = (error: unknown, re?: string) => { bridge.send({ type: "error", error: detail(error, phase, config?.page ?? location.pathname) }, re ? { re } : undefined); };
59
+ const activity = createFrameActivity({ send: (message) => bridge.send(message), error: report });
60
+ let controlled = false; let activitySubscribed = false;
61
+ let renderJobs: ReturnType<typeof frameRenderJobs> | undefined;
62
+ const subscribeActivity = () => {
63
+ if (activitySubscribed) return;
64
+ activitySubscribed = true;
65
+ void workerRequest({ message: "subscribe-activity", load: activity.load, navigationStart: activity.navigationStart }, 15000).catch(report);
66
+ };
67
+ let sizeObserver: ResizeObserver | undefined;
68
+ const dispose = () => { ready = false; sizeObserver?.disconnect(); sizeObserver = undefined; unmount?.(); unmount = undefined; exportMount = undefined; agent?.dispose(); agent = undefined; styles?.stop(); styles = undefined; };
69
+ window.addEventListener("pagehide", () => { activity.stop(); dispose(); bridge.dispose(); }, { once: true });
70
+ async function receive(envelope: BridgeEnvelope) {
71
+ const m = envelope.message;
72
+ if (m.type === "prepare-render" || m.type === "render") {
73
+ if (!renderJobs) throw new Error("render jobs are unavailable in this frame");
74
+ bridge.send(await renderJobs(envelope), envelope.id ? { re: envelope.id } : undefined);
75
+ return;
76
+ }
77
+ if (renderJobs) throw new Error("interactive messages are unavailable in a render frame");
78
+ if (m.type === "open") {
79
+ phase = "resolve"; await workerRequest({ message: m }, 15000);
80
+ const url = new URL(location.href);
81
+ if (url.searchParams.has("runtime-opened")) location.reload();
82
+ else { url.searchParams.set("runtime-opened", "1"); location.replace(url); }
83
+ }
84
+ else if (m.type === "sources") {
85
+ if (!config || !updateSources) throw new Error("page is not mounted for source updates");
86
+ ready = false; phase = "compile";
87
+ performance.mark("page-runtime:sources");
88
+ await workerRequest({ page: config.page, message: m }, 15000);
89
+ if ("data" in m) latestData = m.data!;
90
+ await updateSources(m.files);
91
+ ready = true;
92
+ bridge.send({ type: "status", state: "ready" }, envelope.id ? { re: envelope.id } : undefined);
93
+ }
94
+ else if (m.type === "reload") location.reload();
95
+ else if (m.type === "theme") { document.documentElement.dataset.theme = m.theme; document.documentElement.dataset.density = m.density; }
96
+ else if (m.type === "data") {
97
+ latestData = m.data; receiveData(m.data);
98
+ if (updateData) {
99
+ ready = false; phase = "render";
100
+ await updateData(m.data);
101
+ ready = true;
102
+ bridge.send({ type: "status", state: "ready" }, envelope.id ? { re: envelope.id } : undefined);
103
+ }
104
+ }
105
+ else if (m.type === "mode" || m.type === "pick" || m.type === "page" || m.type === "pins" || m.type === "highlight" || m.type === "scroll" || m.type === "design-override" || m.type === "design-write" || m.type === "design-write-result" || m.type === "review-remove" || m.type === "review-list" || m.type === "review-select" || m.type === "review-visibility" || m.type === "review-action") {
106
+ if (!agent) throw new Error("page agent is not ready");
107
+ agent.receive(m);
108
+ }
109
+ else if (m.type === "capture-vocabulary") {
110
+ const reference = envelope.id ? { re: envelope.id } : undefined;
111
+ if (!ready || !agent) {
112
+ bridge.send({ type: "error", error: { phase: "render", message: "page is not ready for vocabulary capture", file: config?.page ?? location.pathname } }, reference);
113
+ return;
114
+ }
115
+ bridge.send(await agent.captureVocabulary({ ready }), reference);
116
+ }
117
+ else if (m.type === "export") {
118
+ if (!ready || !config || !exportMount) throw new Error("page is not ready for export");
119
+ const reference = envelope.id ? { re: envelope.id } : undefined;
120
+ const root = document.getElementById("root");
121
+ if (!(root instanceof HTMLElement)) throw new Error("frame root is missing");
122
+ await withExportRender({ config, root, mount: exportMount, request: (message) => workerRequest(message, 15000), run: async () => {
123
+ if (m.format === "print") { window.print(); bridge.send({ type: "status", state: "ready" }, reference); }
124
+ else bridge.send({ type: "snapshot", html: await exportHtml() }, reference);
125
+ } });
126
+ }
127
+ }
128
+ try {
129
+ const element = document.getElementById("page-runtime-config");
130
+ if (element) config = JSON.parse(element.textContent!) as FrameConfig;
131
+ let profile: RuntimeProfile;
132
+ if (config) profile = validateProfile(config.profile);
133
+ else {
134
+ const profileResponse = await withTimeout(fetch("/profile.json", { cache: "no-store" }), 15000, "profile fetch timeout");
135
+ if (!profileResponse.ok) throw new Error(`profile.json: HTTP ${profileResponse.status}`);
136
+ profile = validateProfile(await profileResponse.json());
137
+ }
138
+ const host = new URLSearchParams(location.hash.slice(1)).get("host");
139
+ if (!host || !profile.embedders.includes(host)) throw new Error(`host ${host} is not in profile.embedders`);
140
+ const navigationError = document.getElementById("page-runtime-error");
141
+ if (navigationError) {
142
+ const error = JSON.parse(navigationError.textContent!) as RuntimeError;
143
+ throw Object.assign(new Error(error.message), { pageRuntime: error });
144
+ }
145
+ if (!await ensureController({ timeoutMs: profile.readinessTimeoutMs })) { bridge.dispose(); return; }
146
+ controlled = true;
147
+ if (new URL(location.href).searchParams.has("render-job")) {
148
+ if (!profile.renderJobs) throw new Error("render jobs are disabled in this runtime");
149
+ renderJobs = frameRenderJobs(config);
150
+ bridge.send({ type: "status", state: "connecting" });
151
+ return;
152
+ }
153
+ if (!config || !new URL(location.href).searchParams.has("runtime-opened")) { bridge.send({ type: "status", state: "connecting" }); return; }
154
+ bridge.send({ type: "status", state: "booting" });
155
+ performance.mark("page-runtime:controlled");
156
+ phase = "link";
157
+ let rejectModule!: (error: Error) => void;
158
+ const moduleFailure = new Promise<never>((_, reject) => { rejectModule = reject; });
159
+ const workerError = (event: MessageEvent<unknown>) => {
160
+ if (event.source !== navigator.serviceWorker.controller) return;
161
+ if (!event.data || typeof event.data !== "object" || !("type" in event.data) || event.data.type !== "error") return;
162
+ const message = validateFrameMessage(event.data);
163
+ if (message.type === "error") rejectModule(Object.assign(new Error(message.error.message), { pageRuntime: message.error }));
164
+ };
165
+ navigator.serviceWorker.addEventListener("message", workerError);
166
+ let pageModule: PageModule;
167
+ let libraryStyles: Awaited<ReturnType<typeof loadPageStyles>>;
168
+ let pageData: JsonValue;
169
+ let agentModule: typeof import("./page-agent.js");
170
+ let reactRuntime: ReactRuntime;
171
+ try { [pageModule, libraryStyles, pageData, agentModule, reactRuntime] = await Promise.race([Promise.all([
172
+ import(config.entry) as Promise<PageModule>, loadPageStyles(config),
173
+ withTimeout(data, config.profile.readinessTimeoutMs, "data bridge timeout"),
174
+ import(`${PAGE_AGENT_URL}${new URL(config.entry, location.href).search}`) as Promise<typeof import("./page-agent.js")>,
175
+ Promise.all([import("react"), import("react-dom/client"), import("react-dom")]),
176
+ ]), moduleFailure]); }
177
+ finally { navigator.serviceWorker.removeEventListener("message", workerError); }
178
+ let layout = config.layout ? await import(config.layout) as PageLayout : undefined;
179
+ for (const module of [pageModule, layout]) if (module?.meta !== undefined && (module.meta === null || typeof module.meta !== "object" || Array.isArray(module.meta))) throw new Error(`${config.page}: meta must be an object`);
180
+ performance.mark("page-runtime:module");
181
+ performance.mark("page-runtime:libraries");
182
+ activity.resolve(config, { react: reactRuntime[0].version, "react-dom": reactRuntime[2].version });
183
+ if (typeof pageModule.default !== "function" && typeof pageModule.default !== "object") throw new Error(`${config.page}: missing default React component`);
184
+ const styledModule = layout?.meta === undefined ? pageModule : { ...pageModule, meta: { ...layout.meta as object, ...pageModule.meta as object } };
185
+ let pageStyles = await preparePageStyles({ config, styles: libraryStyles, module: styledModule, onError: (error) => { ready = false; report(error); }, onActivity: activity.tailwind });
186
+ let dynamicStyles = pageTailwind({ module: styledModule, page: config.page });
187
+ styles = pageStyles;
188
+ performance.mark("page-runtime:styles");
189
+ const pageRoot = document.getElementById("root");
190
+ if (!(pageRoot instanceof HTMLElement)) throw new Error("frame root is missing");
191
+ performance.mark("page-runtime:agent");
192
+ const { startPageAgent, PageAgentProvider } = agentModule;
193
+ agent = startPageAgent({ root: pageRoot, page: config.page, ...(config.lock.pageSources ? { pageSources: config.lock.pageSources } : {}), send: (message) => bridge.send(message), error: report });
194
+ phase = "render";
195
+ const pageAgent = agent; const runtime = reactRuntime;
196
+ const wrap = (children: import("react").ReactNode) => runtime[0].createElement(PageAgentProvider, { agent: pageAgent, children });
197
+ let reportedHeight: number | undefined;
198
+ sizeObserver = new ResizeObserver(() => {
199
+ const height = Math.ceil(pageRoot.getBoundingClientRect().height);
200
+ if (height !== reportedHeight) { reportedHeight = height; bridge.send({ type: "size", height }); }
201
+ });
202
+ sizeObserver.observe(pageRoot);
203
+ const send = (message: FrameMessage) => bridge.send(message);
204
+ const mountedPage = mountPage({ module: pageModule, ...(layout ? { layout } : {}), runtime, data: pageData, file: config.page, root: pageRoot, wrap, send });
205
+ updateSources = async (files) => {
206
+ const revision = randomUUID();
207
+ const revised = (path: string) => { const url = new URL(path, location.href); url.searchParams.set("revision", revision); return url.href; };
208
+ const paths = Object.keys(files);
209
+ if (paths.length && paths.every(path => path.endsWith(".css"))) {
210
+ for (const path of paths) {
211
+ const url = new URL(`/src/${path.split("/").map(encodeURIComponent).join("/")}`, location.href);
212
+ const links = [...document.querySelectorAll<HTMLLinkElement>("link[data-page-runtime-stylesheet]")].filter(link => link.dataset.pageRuntimeStylesheet === url.pathname);
213
+ if (files[path] === null) { for (const link of links) link.remove(); }
214
+ else if (links.length) { url.searchParams.set("module", ""); const module = await import(revised(url.href)) as { default: Promise<CSSStyleSheet> }; await module.default; }
215
+ }
216
+ if (!updateData) throw new Error("page is not mounted for CSS updates");
217
+ await updateData(latestData); return;
218
+ }
219
+ const entry = revised(config!.entry);
220
+ const nextModule = await import(entry) as PageModule;
221
+ const nextLayout = config!.layout && Object.keys(files).some(path => path !== config!.page) ? await import(revised(config!.layout)) as PageLayout : layout;
222
+ for (const module of [nextModule, nextLayout]) if (module?.meta !== undefined && (module.meta === null || typeof module.meta !== "object" || Array.isArray(module.meta))) throw new Error(`${config!.page}: meta must be an object`);
223
+ if (typeof nextModule.default !== "function" && typeof nextModule.default !== "object") throw new Error(`${config!.page}: missing default React component`);
224
+ const nextStyled = { meta: { ...nextLayout?.meta as object, ...nextModule.meta as object } };
225
+ const nextDynamic = pageTailwind({ module: nextStyled, page: config!.page });
226
+ if (nextDynamic !== dynamicStyles) {
227
+ const nextStyles = await preparePageStyles({ config: config!, styles: await loadPageStyles(config!), module: nextStyled, onError: report, onActivity: activity.tailwind });
228
+ pageStyles.stop(); pageStyles = nextStyles; styles = nextStyles; dynamicStyles = nextDynamic;
229
+ }
230
+ phase = "render";
231
+ await mountedPage.replace({ module: nextModule, ...(nextLayout ? { layout: nextLayout } : {}), data: latestData });
232
+ pageModule = nextModule; layout = nextLayout; config!.entry = entry;
233
+ if (config!.layout && nextLayout) config!.layout = revised(config!.layout);
234
+ phase = "readiness";
235
+ await waitForReadiness({ root: pageRoot, mounted: pageStyles.ready(), ...(pageModule.ready ? { hook: pageModule.ready } : {}), timeoutMs: config!.profile.readinessTimeoutMs, status: () => undefined });
236
+ await pageStyles.ready(); activity.schedule();
237
+ };
238
+ updateData = async (value) => {
239
+ await mountedPage.update(value);
240
+ phase = "readiness";
241
+ await waitForReadiness({ root: pageRoot, mounted: pageStyles.ready(), ...(pageModule.ready ? { hook: pageModule.ready } : {}), timeoutMs: config!.profile.readinessTimeoutMs, status: () => undefined });
242
+ await pageStyles.ready();
243
+ activity.schedule();
244
+ };
245
+ unmount = mountedPage.unmount;
246
+ latestData = pageData;
247
+ const page = config.page;
248
+ exportMount = (module, root) => {
249
+ if (typeof module.default !== "function" && typeof module.default !== "object") throw new Error(`${page}: export compile has no default React component`);
250
+ return mountPage({ module, ...(layout ? { layout } : {}), runtime, data: latestData, file: page, root, wrap, send });
251
+ };
252
+ performance.mark("page-runtime:render");
253
+ requestAnimationFrame(() => requestAnimationFrame(() => { performance.mark("page-runtime:visible"); subscribeActivity(); activity.schedule(); }));
254
+ phase = "readiness";
255
+ await waitForReadiness({ root: pageRoot, mounted: mountedPage.mounted.then(() => pageStyles.ready()), ...(pageModule.ready ? { hook: pageModule.ready } : {}), timeoutMs: config.profile.readinessTimeoutMs, status: (state) => { if (state !== "ready") bridge.send({ type: "status", state }); } });
256
+ await pageStyles.ready();
257
+ announceLock();
258
+ ready = true;
259
+ performance.mark("page-runtime:ready");
260
+ bridge.send({ type: "status", state: "ready" });
261
+ activity.schedule();
262
+ } catch (error) { if (controlled) subscribeActivity(); dispose(); announceLock(); report(error); }
263
+ }
264
+
265
+ async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, message: string): Promise<T> {
266
+ let timer: ReturnType<typeof setTimeout> | undefined;
267
+ try { return await Promise.race([promise, new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(message)), timeoutMs); })]); }
268
+ finally { clearTimeout(timer); }
269
+ }
@@ -0,0 +1,27 @@
1
+ import { createBridge } from "../host/bridge.ts";
2
+ import type { BridgeEnvelope } from "../schema.ts";
3
+ import { validateFrameOrigin } from "../host/origin.ts";
4
+
5
+ export function createFrameBridge(options: { receive: (value: BridgeEnvelope) => void; error: (error: Error) => void }) {
6
+ const params = new URLSearchParams(location.hash.slice(1));
7
+ const origin = params.get("host"); const session = params.get("session");
8
+ if (!origin || !session || parent === window) throw new Error("frame requires a host origin and session");
9
+ const mode = params.get("origin") ?? "cross-origin";
10
+ if (mode !== "cross-origin" && mode !== "same-origin-local") throw new Error("invalid frame origin mode");
11
+ validateFrameOrigin({ runtimeOrigin: location.origin, hostOrigin: origin, origin: mode });
12
+ return createBridge({ target: parent, origin, session, direction: "frame", onMessage: options.receive, onError: options.error });
13
+ }
14
+
15
+ export async function workerRequest<T = void>(message: unknown, timeoutMs: number): Promise<T> {
16
+ const controller = navigator.serviceWorker.controller;
17
+ if (!controller) throw new Error("service worker does not control frame");
18
+ return new Promise<T>((resolve, reject) => {
19
+ const channel = new MessageChannel();
20
+ const timer = setTimeout(() => { channel.port1.close(); reject(new Error("worker request timed out")); }, timeoutMs);
21
+ channel.port1.onmessage = (event: MessageEvent<{ ok: boolean; error?: unknown; result: T }>) => {
22
+ clearTimeout(timer); channel.port1.close();
23
+ if (event.data.ok) resolve(event.data.result); else reject(Object.assign(new Error("worker rejected request"), { pageRuntime: event.data.error }));
24
+ };
25
+ controller.postMessage(message, [channel.port2]);
26
+ });
27
+ }
@@ -0,0 +1 @@
1
+ import "bippy/install-hook-only";
@@ -0,0 +1,76 @@
1
+ import type { DocumentSource, PageLock } from "../schema.ts";
2
+ import { CONTENT_TYPES, extensionOf } from "../sw/content-types.ts";
3
+ import { verifyIntegrity } from "../sw/integrity.ts";
4
+
5
+ export const DOCUMENT_ORIGIN = "https://facet-document.invalid";
6
+ export const documentSourceURL = (path: string) => `/src/${path.split("/").map(encodeURIComponent).join("/")}`;
7
+ export const textAsset = (text: string, type: string) => URL.createObjectURL(new Blob([text], { type }));
8
+
9
+ export function documentAssets(options: { files: DocumentSource["files"]; lock: PageLock }) {
10
+ const { lock, files } = options;
11
+ const requests = new Map<string, Promise<Uint8Array<ArrayBuffer>>>();
12
+ const urls = new Map<string, string>();
13
+
14
+ async function read(path: string): Promise<Uint8Array<ArrayBuffer>> {
15
+ if (path.startsWith("/src/")) {
16
+ const key = decodeURIComponent(path.slice("/src/".length));
17
+ const file = Object.hasOwn(files, key) ? files[key] : undefined;
18
+ if (!file) throw new Error(`Missing document source ${key}`);
19
+ return "text" in file ? new TextEncoder().encode(file.text) : Uint8Array.from(atob(file.base64), char => char.charCodeAt(0));
20
+ }
21
+ if (!path.startsWith("/npm/")) throw new Error(`Unsupported document package URL ${path}`);
22
+ const key = decodeURIComponent(path.slice("/npm/".length));
23
+ const expected = Object.hasOwn(lock.integrity, key) ? lock.integrity[key] : undefined;
24
+ if (!expected) throw new Error(`${key} is outside the document's package lock`);
25
+ let pending = requests.get(key);
26
+ if (!pending) {
27
+ pending = (async () => {
28
+ const response = await fetch(`${lock.packageOrigin.replace(/\/$/, "")}/${key}`, { mode: "cors", credentials: "omit", redirect: "error" });
29
+ if (!response.ok) throw new Error(`${key}: package origin returned HTTP ${response.status}`);
30
+ const bytes = new Uint8Array(await response.arrayBuffer());
31
+ await verifyIntegrity(bytes, expected, key);
32
+ return bytes;
33
+ })();
34
+ requests.set(key, pending);
35
+ }
36
+ return pending;
37
+ }
38
+
39
+ const readText = async (path: string) => new TextDecoder().decode(await read(path));
40
+
41
+ async function css(path: string, parents: readonly string[] = []): Promise<string> {
42
+ const text = await readText(path);
43
+ return replaceMatches(text, /url\(\s*(?:"([^"]+)"|'([^']+)'|([^\s)]+))\s*\)|(@import\s+)(?:"([^"]+)"|'([^']+)')/g, async match => {
44
+ const reference = match[1] ?? match[2] ?? match[3] ?? match[5] ?? match[6]!;
45
+ if (/^(?:[a-z][a-z+.-]*:|\/\/|#)/i.test(reference)) return match[0];
46
+ const target = new URL(reference, DOCUMENT_ORIGIN + path);
47
+ const href = await url(target.pathname, [...parents, path]) + target.hash;
48
+ return match[4] ? `${match[4]}${JSON.stringify(href)}` : `url(${JSON.stringify(href)})`;
49
+ });
50
+ }
51
+
52
+ async function url(path: string, parents: readonly string[] = []): Promise<string> {
53
+ const hit = urls.get(path);
54
+ if (hit) return hit;
55
+ if (parents.includes(path)) throw new Error(`Circular stylesheet imports: ${[...parents, path].join(" → ")}`);
56
+ const ext = extensionOf(path);
57
+ const type = CONTENT_TYPES[ext] ?? "application/octet-stream";
58
+ const blob = ext === ".css" ? textAsset(await css(path, parents), type) : URL.createObjectURL(new Blob([await read(path)], { type }));
59
+ const winner = urls.get(path);
60
+ if (winner) { URL.revokeObjectURL(blob); return winner; }
61
+ urls.set(path, blob);
62
+ return blob;
63
+ }
64
+
65
+ return { readText, css, url };
66
+ }
67
+
68
+ export async function replaceMatches(code: string, pattern: RegExp, replace: (match: RegExpMatchArray) => Promise<string>): Promise<string> {
69
+ const matches = [...code.matchAll(pattern)];
70
+ const values = await Promise.all(matches.map(replace));
71
+ for (let i = matches.length - 1; i >= 0; i--) {
72
+ const match = matches[i]!;
73
+ code = code.slice(0, match.index!) + values[i] + code.slice(match.index! + match[0].length);
74
+ }
75
+ return code;
76
+ }
@@ -0,0 +1,68 @@
1
+ import type { DocumentSource, FrameConfig, RuntimeProfile } from "../schema.ts";
2
+ import { fetchJson, resolvePage } from "../sw/resolver.ts";
3
+ import { validateSourcePath } from "../host/validation.ts";
4
+ import { DOCUMENT_ORIGIN, documentSourceURL } from "./document-assets.ts";
5
+ import { documentModules } from "./document-modules.ts";
6
+ import { documentError, mount } from "./document-mount.ts";
7
+ import { baseStylesheets, loadLibraries } from "./tailwind/load.ts";
8
+ import { prepareTailwind } from "./tailwind/runtime.ts";
9
+ import { insertBaseStyles } from "./tailwind/stylesheets.ts";
10
+ import type { PageLayout, PageModule, ReactRuntime } from "./mount-page.ts";
11
+
12
+ async function documentProfile(source: DocumentSource): Promise<RuntimeProfile> {
13
+ if (source.profileUrl) {
14
+ const profile = await fetchJson<RuntimeProfile>(fetch, source.profileUrl);
15
+ const rebase = (url: string) => new URL(`.${new URL(url).pathname}`, source.profileUrl).href;
16
+ return { ...profile, packageOrigin: rebase(profile.packageOrigin), registry: rebase(profile.registry) };
17
+ }
18
+ return {
19
+ runtimeDomain: new URL(DOCUMENT_ORIGIN).hostname, embedders: [], packageOrigin: "https://unpkg.com",
20
+ registry: "https://registry.npmjs.org", managed: source.managed, policy: { dependencies: "any" },
21
+ minReleaseAgeDays: 0, network: { allow: [] }, csp: { add: {} }, links: "deny", sources: ["host"], readinessTimeoutMs: 30000,
22
+ };
23
+ }
24
+
25
+ async function launch(source: DocumentSource): Promise<void> {
26
+ for (const path of Object.keys(source.files)) validateSourcePath(path);
27
+ const entry = documentSourceURL(source.page);
28
+ const layout = documentSourceURL(source.layout);
29
+ const profile = await documentProfile(source);
30
+ const lock = await resolvePage({ page: source.page, profile, manifest: { dependencies: source.dependencies },
31
+ ...(source.profileUrl ? { runtimeExportsUrl: new URL("runtime-exports.json", source.profileUrl).href } : {}),
32
+ });
33
+ const modules = documentModules({ source, lock });
34
+ await modules.enableCompilerPlugins();
35
+ const react = ["react", "react-dom/client", "react-dom"].map(id => modules.resolve(id, entry));
36
+ const [page, wrapper, ...runtime] = await modules.importModules([entry, layout, ...react]);
37
+ const config: FrameConfig = { page: source.page, entry, layout, lock, profile, runtimeVersion: "document" };
38
+ const styles = await documentStyles({ config, modules });
39
+ await mount(page as PageModule, runtime as unknown as ReactRuntime, {
40
+ layout: wrapper as PageLayout,
41
+ prepareStyles: async root => {
42
+ if (source.dynamicStyles === false) return;
43
+ const dynamic = await prepareTailwind({ ...styles, root, runtimeVersion: config.runtimeVersion,
44
+ candidates: [...modules.candidates], timeoutMs: profile.readinessTimeoutMs, onError: documentError,
45
+ });
46
+ await dynamic.ready();
47
+ },
48
+ });
49
+ }
50
+
51
+ async function documentStyles(options: { config: FrameConfig; modules: ReturnType<typeof documentModules> }) {
52
+ const { config, modules } = options;
53
+ const resolve = ({ id, base }: { id: string; base: string }) => /^(?:[./]|https?:)/.test(id)
54
+ ? new URL(id, base).href : new URL(modules.resolve(id, base), DOCUMENT_ORIGIN).href;
55
+ const styles = await loadLibraries({ config, resolve,
56
+ importModule: async url => (await modules.importModules([new URL(url).pathname]))[0]!,
57
+ fetch: async url => new Response(await modules.assets.css(new URL(String(url)).pathname), { headers: { "content-type": "text/css" } }),
58
+ });
59
+ const stylesheets = await Promise.all(baseStylesheets({ ...styles, config, resolve }).map(async sheet => ({
60
+ ...sheet, url: await modules.assets.url(new URL(sheet.url).pathname),
61
+ })));
62
+ await insertBaseStyles({ document, stylesheets, timeoutMs: config.profile.readinessTimeoutMs }).ready;
63
+ return styles;
64
+ }
65
+
66
+ const source = document.getElementById("facet-document-source");
67
+ if (!source) documentError(new Error("Document sources are missing"));
68
+ else void Promise.resolve().then(() => launch(JSON.parse(source.textContent ?? "") as DocumentSource)).catch(documentError);
@@ -0,0 +1,113 @@
1
+ import { init, parse } from "es-module-lexer";
2
+ import type { DocumentSource, PageLock } from "../schema.ts";
3
+ import { DEV_SHIM_URL } from "../sw/compile.ts";
4
+ import { BASE_PLUGINS, compilePage, rewriteImports } from "../sw/compiler.ts";
5
+ import { extensionOf } from "../sw/content-types.ts";
6
+ import { resolveSpecifier } from "../sw/composition.ts";
7
+ import { stylesheetModule } from "../sw/module-transform.ts";
8
+ import { DOCUMENT_ORIGIN, documentAssets, documentSourceURL, replaceMatches, textAsset } from "./document-assets.ts";
9
+
10
+ export function documentModules(options: { source: DocumentSource; lock: PageLock }) {
11
+ const { source, lock } = options;
12
+ const assets = documentAssets({ files: source.files, lock });
13
+ const sources = Object.keys(source.files).map(path => documentSourceURL(path).slice("/src/".length));
14
+ const modules = new Set<string>();
15
+ const candidates = new Set<string>();
16
+ let active = Promise.resolve();
17
+ let remark: unknown[] = [];
18
+
19
+ function resolve(id: string, referrer: string): string {
20
+ const path = new URL(referrer, DOCUMENT_ORIGIN).pathname;
21
+ const linked = resolveSpecifier(lock.map, id, path);
22
+ if (!linked) throw new Error(`${path}: cannot resolve ${id} in the document runtime`);
23
+ return linked;
24
+ }
25
+
26
+ async function compile(path: string): Promise<string> {
27
+ const url = new URL(path, DOCUMENT_ORIGIN);
28
+ const extension = extensionOf(url.pathname);
29
+ const rewrite = (code: string) => rewriteImports({ code, path, lock, sources });
30
+ if (url.pathname === DEV_SHIM_URL) return rewrite('export { Fragment, jsxDEV } from "react/jsx-dev-runtime";');
31
+ if (url.searchParams.has("raw")) return `export default ${JSON.stringify(await assets.readText(url.pathname))};`;
32
+ if (url.searchParams.has("url") || !/\.(?:tsx?|jsx?|mjs|mdx?|css|json)$/.test(extension)) {
33
+ return `export default ${JSON.stringify(await assets.url(url.pathname))};`;
34
+ }
35
+ if (extension === ".css") return stylesheetModule(await assets.css(url.pathname), await assets.url(url.pathname));
36
+ const code = await assets.readText(url.pathname);
37
+ if (extension === ".json") return `export default ${JSON.stringify(JSON.parse(code))};`;
38
+ if (url.pathname.startsWith("/npm/")) return rewrite(code);
39
+ const result = await compilePage({ path, code, lock, sources, plugins: BASE_PLUGINS, remark: [...remark, markdownAssets(url.pathname)] });
40
+ for (const candidate of result.candidates) candidates.add(candidate);
41
+ return result.code;
42
+ }
43
+
44
+ function markdownAssets(path: string) {
45
+ type Node = { type: string; identifier?: string; url?: string; children?: Node[] };
46
+ return () => async (root: Node) => {
47
+ const nodes: Node[] = [root];
48
+ for (const node of nodes) nodes.push(...(node.children ?? []));
49
+ const definitions = new Set(nodes.filter(node => node.type === "imageReference").map(node => node.identifier));
50
+ for (const node of nodes) {
51
+ const image = node.type === "image" || (node.type === "definition" && definitions.has(node.identifier));
52
+ if (!image || !node.url || /^(?:[a-z][a-z+.-]*:|\/|#)/i.test(node.url)) continue;
53
+ const target = new URL(node.url, DOCUMENT_ORIGIN + path);
54
+ node.url = await assets.url(target.pathname) + target.hash;
55
+ }
56
+ };
57
+ }
58
+
59
+ async function load(path: string): Promise<{ code: string; imports: string[] }> {
60
+ const code = await replaceMatches(await compile(path), /(new URL\(\s*)(['"])([^'":?#]+)\2\s*,\s*import\.meta\.url\s*\)/g, async match => {
61
+ const target = new URL(match[3]!, DOCUMENT_ORIGIN + path);
62
+ return `${match[1]}${JSON.stringify(await assets.url(target.pathname))})`;
63
+ });
64
+ const imports: string[] = [];
65
+ let output = code;
66
+ for (const item of [...parse(code)[0]].reverse()) {
67
+ if (item.type === "import-meta") continue;
68
+ if (!item.specifier || !item.specifier.startsWith("/")) throw new Error(`${path}: document module was not linked`);
69
+ imports.push(item.specifier);
70
+ const target = DOCUMENT_ORIGIN + item.specifier;
71
+ const quoted = /^['"`]/.test(code.slice(item.start, item.end));
72
+ output = output.slice(0, item.start) + (quoted ? JSON.stringify(target) : target) + output.slice(item.end);
73
+ }
74
+ return { code: output, imports };
75
+ }
76
+
77
+ async function prepare(paths: string[]): Promise<void> {
78
+ await init();
79
+ const imports: Record<string, string> = {};
80
+ let pending = paths;
81
+ while (pending.length) {
82
+ const fresh = [...new Set(pending)].filter(path => !modules.has(path));
83
+ for (const path of fresh) modules.add(path);
84
+ pending = (await Promise.all(fresh.map(async path => {
85
+ const output = await load(path);
86
+ imports[DOCUMENT_ORIGIN + path] = textAsset(output.code, "text/javascript");
87
+ return output.imports;
88
+ }))).flat();
89
+ }
90
+ if (!Object.keys(imports).length) return;
91
+ const map = document.createElement("script");
92
+ map.type = "importmap";
93
+ map.textContent = JSON.stringify({ imports });
94
+ document.head.append(map);
95
+ }
96
+
97
+ function importModules(paths: string[]): Promise<Array<Record<string, unknown>>> {
98
+ active = active.then(() => prepare(paths));
99
+ return active.then(() => Promise.all(paths.map(path => import(/* @vite-ignore */ DOCUMENT_ORIGIN + path) as Promise<Record<string, unknown>>)));
100
+ }
101
+
102
+ async function enableCompilerPlugins(): Promise<void> {
103
+ const plugins = Object.values(lock.compiler ?? {}).flatMap(group => group.remark);
104
+ const loaded = await importModules(plugins.map(plugin => resolve(plugin.module, documentSourceURL(source.page))));
105
+ remark = plugins.map((plugin, index) => {
106
+ const entry = loaded[index]?.default;
107
+ if (typeof entry !== "function") throw new Error(`${plugin.module}: remark plugin must export a default function`);
108
+ return [entry, plugin.options];
109
+ });
110
+ }
111
+
112
+ return { importModules, enableCompilerPlugins, resolve, assets, candidates };
113
+ }
@@ -0,0 +1,32 @@
1
+ import { mountPage, type PageLayout, type PageModule, type ReactRuntime } from "./mount-page.ts";
2
+ import { waitForReadiness } from "./readiness.ts";
3
+ import type { JsonValue } from "../schema.ts";
4
+
5
+ export function documentError(error: unknown): void {
6
+ const status = document.getElementById("facet-document-status");
7
+ if (!status) throw error;
8
+ status.textContent = error instanceof Error ? error.message : String(error);
9
+ status.setAttribute("role", "alert");
10
+ }
11
+
12
+ export async function mount(module: PageModule, runtime: ReactRuntime, options?: { layout: PageLayout; prepareStyles: (root: HTMLElement) => Promise<void> }): Promise<void> {
13
+ const root = document.getElementById("facet-root");
14
+ const data = document.getElementById("facet-document-data");
15
+ const status = document.getElementById("facet-document-status");
16
+ if (!root || !data || !status) throw new Error("Incomplete Facet document");
17
+ try {
18
+ const mounted = mountPage({
19
+ module, runtime, root, file: document.title, data: JSON.parse(data.textContent ?? "") as JsonValue,
20
+ ...(options ? { layout: options.layout } : {}), wrap: children => children, send: () => undefined,
21
+ });
22
+ await mounted.mounted;
23
+ await options?.prepareStyles(root);
24
+ await waitForReadiness({
25
+ root, mounted: mounted.mounted, ...(module.ready ? { hook: module.ready } : {}),
26
+ timeoutMs: 30000, status: () => undefined,
27
+ });
28
+ status.remove();
29
+ } catch (error) {
30
+ documentError(error);
31
+ }
32
+ }
@@ -0,0 +1,4 @@
1
+ import { bootFrame } from "./boot.ts";
2
+ void bootFrame().catch((error: unknown) => {
3
+ document.getElementById("root")!.textContent = `page-runtime boot failed: ${error instanceof Error ? error.message : String(error)}`;
4
+ });
@@ -0,0 +1,18 @@
1
+ import { compile } from "@mdx-js/mdx";
2
+ import { init, parse } from "es-module-lexer";
3
+ import { compileMdx } from "../sw/compile.ts";
4
+ import { BASE_PLUGINS } from "../sw/compiler.ts";
5
+
6
+ /**
7
+ * Compiles a Markdown page for an HTML or PDF export: the base plugins, then the library-declared `remark` plugins.
8
+ * Imported Markdown is compiled by the worker without those plugins, so an export that would include it fails.
9
+ */
10
+ export async function compileExportMdx(options: { path: string; code: string; remark: unknown[] }): Promise<string> {
11
+ const extension = options.path.slice(options.path.lastIndexOf("."));
12
+ const code = await compileMdx({ path: options.path, extension, code: options.code }, compile, BASE_PLUGINS, options.remark);
13
+ await init();
14
+ const [imports] = parse(code);
15
+ const markdown = imports.map((item) => item.specifier).filter((specifier): specifier is string => typeof specifier === "string" && /^\.{0,2}\//.test(specifier) && /\.mdx?(?:\?|$)/.test(specifier));
16
+ if (markdown.length) throw new Error(`${options.path}: export compiler plugins do not apply to imported Markdown (${markdown.join(", ")}); move that content into the exported page`);
17
+ return code;
18
+ }