@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.
- package/LICENSE +17 -0
- package/README.md +494 -2
- package/dist/build/README.md +96 -0
- package/dist/build/cjs-export-names.mjs +24 -0
- package/dist/build/dependencies.mjs +279 -0
- package/dist/build/dependencies.mjs.map +1 -0
- package/dist/build/dependency-cache-Zg-FGasE.mjs +2130 -0
- package/dist/build/dependency-cache-Zg-FGasE.mjs.map +1 -0
- package/dist/build/index.mjs +42 -0
- package/dist/build/index.mjs.map +1 -0
- package/dist/build/package.json +19 -0
- package/dist/build/types/activity-schema.d.ts +62 -0
- package/dist/build/types/build/barrels.d.ts +70 -0
- package/dist/build/types/build/base.d.ts +2 -0
- package/dist/build/types/build/browser-runtime-exports.d.ts +19 -0
- package/dist/build/types/build/check-fragment.d.ts +5 -0
- package/dist/build/types/build/commonjs-exports.d.ts +5 -0
- package/dist/build/types/build/convert-commonjs.d.ts +12 -0
- package/dist/build/types/build/dependencies.d.ts +6 -0
- package/dist/build/types/build/dependency-barrel-index.d.ts +5 -0
- package/dist/build/types/build/dependency-barrels.d.ts +7 -0
- package/dist/build/types/build/dependency-cache.d.ts +7 -0
- package/dist/build/types/build/dependency-optional.d.ts +4 -0
- package/dist/build/types/build/dependency-plugin.d.ts +8 -0
- package/dist/build/types/build/dependency-runtime.d.ts +20 -0
- package/dist/build/types/build/dependency-workers.d.ts +8 -0
- package/dist/build/types/build/errors.d.ts +9 -0
- package/dist/build/types/build/fragment.d.ts +13 -0
- package/dist/build/types/build/index.d.ts +7 -0
- package/dist/build/types/build/library-runtime.d.ts +21 -0
- package/dist/build/types/build/module-utils.d.ts +3 -0
- package/dist/build/types/build/recipe-dependencies.d.ts +2 -0
- package/dist/build/types/build/runtime-entries.d.ts +4 -0
- package/dist/build/types/build/runtime-layer.d.ts +17 -0
- package/dist/build/types/build/trace.d.ts +140 -0
- package/dist/build/types/design-schema.d.ts +98 -0
- package/dist/build/types/host/agent-source.d.ts +2 -0
- package/dist/build/types/host/agent-validation.d.ts +3 -0
- package/dist/build/types/host/design-validation.d.ts +2 -0
- package/dist/build/types/host/message-values.d.ts +8 -0
- package/dist/build/types/host/review/validation.d.ts +5 -0
- package/dist/build/types/host/validation.d.ts +6 -0
- package/dist/build/types/link/page-sources.d.ts +31 -0
- package/dist/build/types/link/types.d.ts +62 -0
- package/dist/build/types/link/validation.d.ts +9 -0
- package/dist/build/types/markers.d.ts +10 -0
- package/dist/build/types/review-schema.d.ts +60 -0
- package/dist/build/types/schema.d.ts +319 -0
- package/dist/build/types/sw/barrels.d.ts +9 -0
- package/dist/build/types/sw/compiler-plugins.d.ts +6 -0
- package/dist/build/types/sw/composition.d.ts +8 -0
- package/dist/build/types/sw/module-transform.d.ts +68 -0
- package/dist/build/types/sw/profile.d.ts +7 -0
- package/dist/build/types/sw/source-provider.d.ts +7 -0
- package/dist/build/types/sw/versions.d.ts +10 -0
- package/dist/node/catalog.mjs +1 -0
- package/dist/node/chunks/publication-RchcQvxD.mjs +229 -0
- package/dist/node/chunks/publication-RchcQvxD.mjs.map +1 -0
- package/dist/node/chunks/schema-CaRTfg2x.mjs +12 -0
- package/dist/node/chunks/schema-CaRTfg2x.mjs.map +1 -0
- package/dist/node/dev.mjs +410 -0
- package/dist/node/dev.mjs.map +1 -0
- package/dist/node/publication/cli.mjs +13 -0
- package/dist/node/publication/cli.mjs.map +1 -0
- package/dist/node/publication.mjs +1 -0
- package/dist/node/schema.mjs +1 -0
- package/dist/node/styles.mjs +49 -0
- package/dist/node/styles.mjs.map +1 -0
- package/dist/static/boot.js +40938 -0
- package/dist/static/boot.js.map +1 -0
- package/dist/static/bootstrap.html +1 -0
- package/dist/static/devtools-hook.js +118 -0
- package/dist/static/document-bundle.js +1 -0
- package/dist/static/document.js +2621 -0
- package/dist/static/editing.js +37 -0
- package/dist/static/export-compiler.js +81521 -0
- package/dist/static/export-compiler.js.map +1 -0
- package/dist/static/page-agent.js +17193 -0
- package/dist/static/page-agent.js.map +1 -0
- package/dist/static/sw.js +86112 -0
- package/dist/static/sw.js.map +1 -0
- package/package.json +110 -3
- package/scripts/build-builder.ts +27 -0
- package/scripts/build-library-runtime.ts +9 -0
- package/scripts/build-node.ts +26 -0
- package/scripts/build-static.ts +86 -0
- package/scripts/build.ts +7 -0
- package/scripts/check-fragment.ts +12 -0
- package/scripts/local-workspaces.ts +55 -0
- package/scripts/react-externals.ts +18 -0
- package/scripts/release-version.ts +47 -0
- package/scripts/run-package-build.ts +8 -0
- package/scripts/serve-packages.ts +8 -0
- package/src/activity-schema.ts +92 -0
- package/src/build/README.md +96 -0
- package/src/build/barrels.ts +306 -0
- package/src/build/base.ts +2 -0
- package/src/build/browser-runtime-exports.ts +52 -0
- package/src/build/check-fragment.ts +45 -0
- package/src/build/cjs-export-names.mjs +24 -0
- package/src/build/commonjs-exports.ts +24 -0
- package/src/build/convert-commonjs.ts +183 -0
- package/src/build/dependencies.ts +6 -0
- package/src/build/dependency-barrel-index.ts +48 -0
- package/src/build/dependency-barrels.ts +80 -0
- package/src/build/dependency-cache.ts +40 -0
- package/src/build/dependency-optional.ts +15 -0
- package/src/build/dependency-plugin.ts +58 -0
- package/src/build/dependency-runtime.ts +182 -0
- package/src/build/dependency-workers.ts +41 -0
- package/src/build/errors.ts +9 -0
- package/src/build/fragment.ts +89 -0
- package/src/build/index.ts +7 -0
- package/src/build/library-runtime.ts +101 -0
- package/src/build/module-utils.ts +11 -0
- package/src/build/recipe-dependencies.ts +14 -0
- package/src/build/runtime-entries.ts +10 -0
- package/src/build/runtime-layer.ts +99 -0
- package/src/build/trace.ts +431 -0
- package/src/design-schema.ts +25 -0
- package/src/dev/README.md +78 -0
- package/src/dev/catalog.ts +79 -0
- package/src/dev/cli.ts +25 -0
- package/src/dev/index.ts +118 -0
- package/src/dev/runtime-origin.ts +63 -0
- package/src/editing.ts +25 -0
- package/src/form/entry-source.ts +68 -0
- package/src/form/form-page.ts +63 -0
- package/src/form/index.ts +2 -0
- package/src/form/source-update.ts +17 -0
- package/src/frame/activity.browser.ts +34 -0
- package/src/frame/activity.ts +52 -0
- package/src/frame/agent/README.md +47 -0
- package/src/frame/agent/agent.browser.ts +127 -0
- package/src/frame/agent/design.ts +62 -0
- package/src/frame/agent/frame-layout.ts +54 -0
- package/src/frame/agent/index.ts +151 -0
- package/src/frame/agent/overlay.ts +104 -0
- package/src/frame/agent/owner.ts +61 -0
- package/src/frame/agent/provider.tsx +14 -0
- package/src/frame/agent/react-override.ts +55 -0
- package/src/frame/agent/review.browser.ts +65 -0
- package/src/frame/agent/review.ts +108 -0
- package/src/frame/agent/testing/callsite.tsx +5 -0
- package/src/frame/agent/testing/client.ts +99 -0
- package/src/frame/agent/testing/library.ts +3 -0
- package/src/frame/agent/testing/modal.tsx +5 -0
- package/src/frame/agent/testing/review-client.ts +43 -0
- package/src/frame/agent/testing/review-server.ts +31 -0
- package/src/frame/agent/testing/server.ts +72 -0
- package/src/frame/agent/testing/vocabulary-host.ts +20 -0
- package/src/frame/agent/testing/vocabulary.tsx +10 -0
- package/src/frame/agent/vitest.browser.config.ts +6 -0
- package/src/frame/agent/vocabulary.browser.ts +30 -0
- package/src/frame/agent/vocabulary.ts +13 -0
- package/src/frame/agent.ts +3 -0
- package/src/frame/boot-styles.ts +50 -0
- package/src/frame/boot.ts +269 -0
- package/src/frame/bridge.ts +27 -0
- package/src/frame/devtools-hook.ts +1 -0
- package/src/frame/document-assets.ts +76 -0
- package/src/frame/document-entry.ts +68 -0
- package/src/frame/document-modules.ts +113 -0
- package/src/frame/document-mount.ts +32 -0
- package/src/frame/entry.ts +4 -0
- package/src/frame/export-compiler.ts +18 -0
- package/src/frame/export-page.ts +61 -0
- package/src/frame/export.ts +89 -0
- package/src/frame/index.ts +8 -0
- package/src/frame/local-runtime.browser.ts +36 -0
- package/src/frame/mount-page.ts +36 -0
- package/src/frame/page-agent.ts +2 -0
- package/src/frame/readiness.ts +51 -0
- package/src/frame/render-job.ts +101 -0
- package/src/frame/review-integration.browser.ts +48 -0
- package/src/frame/runtime.browser.ts +90 -0
- package/src/frame/tailwind/README.md +49 -0
- package/src/frame/tailwind/boot-styles.browser.ts +18 -0
- package/src/frame/tailwind/cache.ts +20 -0
- package/src/frame/tailwind/load.ts +75 -0
- package/src/frame/tailwind/recipe.ts +76 -0
- package/src/frame/tailwind/runtime.ts +113 -0
- package/src/frame/tailwind/store.ts +55 -0
- package/src/frame/tailwind/stylesheets.ts +42 -0
- package/src/frame/tailwind/tailwind.browser.ts +71 -0
- package/src/frame/tailwind/testing/client.ts +133 -0
- package/src/frame/tailwind/testing/compare.ts +91 -0
- package/src/frame/tailwind/testing/pages.ts +14 -0
- package/src/frame/tailwind/testing/server.ts +89 -0
- package/src/frame/tailwind/vitest.browser.config.ts +7 -0
- package/src/frame/testing/boot-layout.ts +3 -0
- package/src/frame/testing/boot-page.ts +3 -0
- package/src/frame/testing/host.ts +78 -0
- package/src/frame/testing/local-host.tsx +33 -0
- package/src/frame/testing/server.ts +135 -0
- package/src/host/BuildLog.tsx +28 -0
- package/src/host/DEBUG_CONSOLE.md +13 -0
- package/src/host/PageForm.tsx +63 -0
- package/src/host/PageFrame.tsx +49 -0
- package/src/host/RuntimeActivity.tsx +77 -0
- package/src/host/RuntimeDebugPanel.tsx +18 -0
- package/src/host/activity-state.ts +69 -0
- package/src/host/agent-source.ts +14 -0
- package/src/host/agent-validation.ts +73 -0
- package/src/host/bridge.ts +56 -0
- package/src/host/build-log.ts +29 -0
- package/src/host/clear-cache.ts +66 -0
- package/src/host/debug-runtime.tsx +17 -0
- package/src/host/design-validation.ts +96 -0
- package/src/host/index.ts +12 -0
- package/src/host/link/index.ts +66 -0
- package/src/host/link/transport.ts +68 -0
- package/src/host/link/watch.ts +62 -0
- package/src/host/message-values.ts +55 -0
- package/src/host/origin.ts +7 -0
- package/src/host/review/README.md +32 -0
- package/src/host/review/index.ts +43 -0
- package/src/host/review/validation.ts +55 -0
- package/src/host/runtime-diagnostics.ts +41 -0
- package/src/host/validation.ts +148 -0
- package/src/link/README.md +115 -0
- package/src/link/barrels.ts +5 -0
- package/src/link/build-cli.ts +12 -0
- package/src/link/build.ts +99 -0
- package/src/link/commonjs.ts +39 -0
- package/src/link/examples/server.ts +18 -0
- package/src/link/index.ts +6 -0
- package/src/link/link.browser.ts +66 -0
- package/src/link/local-relay.browser.ts +22 -0
- package/src/link/overrides.ts +69 -0
- package/src/link/page-sources.ts +69 -0
- package/src/link/source.ts +25 -0
- package/src/link/storage.ts +32 -0
- package/src/link/testing/client.ts +96 -0
- package/src/link/testing/folder.ts +19 -0
- package/src/link/testing/local-client.ts +30 -0
- package/src/link/testing/local-server.ts +26 -0
- package/src/link/testing/local-worker.ts +17 -0
- package/src/link/testing/server.ts +131 -0
- package/src/link/testing/worker.ts +32 -0
- package/src/link/testing-cache.ts +20 -0
- package/src/link/testing-fixtures.ts +16 -0
- package/src/link/types.ts +27 -0
- package/src/link/validation.ts +44 -0
- package/src/link/vitest.browser.config.ts +3 -0
- package/src/markers.ts +18 -0
- package/src/publication/build.ts +27 -0
- package/src/publication/fixtures/build.mjs +2 -0
- package/src/publication/index.ts +3 -0
- package/src/publication/lock.ts +32 -0
- package/src/publication/manifest.ts +14 -0
- package/src/publication/publish.ts +80 -0
- package/src/publication/runtime.ts +28 -0
- package/src/publication/schema.ts +13 -0
- package/src/review-schema.ts +17 -0
- package/src/schema.ts +175 -0
- package/src/storage/db.ts +64 -0
- package/src/styles.ts +40 -0
- package/src/sw/activity.ts +66 -0
- package/src/sw/barrels.ts +44 -0
- package/src/sw/candidates.ts +14 -0
- package/src/sw/compile.ts +92 -0
- package/src/sw/compiler-columns.ts +44 -0
- package/src/sw/compiler-internals.d.ts +8 -0
- package/src/sw/compiler-plugins.ts +18 -0
- package/src/sw/compiler.ts +93 -0
- package/src/sw/composition.ts +86 -0
- package/src/sw/content-types.ts +28 -0
- package/src/sw/converted.browser.ts +31 -0
- package/src/sw/converted.ts +64 -0
- package/src/sw/editable-sites.ts +42 -0
- package/src/sw/errors.ts +30 -0
- package/src/sw/esm-sh-fixtures/browser-client.ts +18 -0
- package/src/sw/esm-sh-fixtures/browser-server.ts +104 -0
- package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-entry.headers +15 -0
- package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-entry.mjs.txt +3 -0
- package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-module.headers +13 -0
- package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-module.mjs.txt +142 -0
- package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-entry.headers +15 -0
- package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-entry.mjs.txt +3 -0
- package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-module.headers +11 -0
- package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-module.mjs.txt +222 -0
- package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-entry.headers +14 -0
- package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-entry.mjs.txt +3 -0
- package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-module.headers +11 -0
- package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-module.mjs.txt +76 -0
- package/src/sw/esm-sh-fixtures/fixtures.ts +54 -0
- package/src/sw/esm-sh-fixtures/redact.ts +1 -0
- package/src/sw/index.ts +7 -0
- package/src/sw/integrity.ts +10 -0
- package/src/sw/legacy-storage.ts +18 -0
- package/src/sw/link-activity.ts +21 -0
- package/src/sw/link-cache.ts +19 -0
- package/src/sw/link-compiler.ts +120 -0
- package/src/sw/link-folder.ts +29 -0
- package/src/sw/link-relay.ts +40 -0
- package/src/sw/link-route.ts +239 -0
- package/src/sw/link-source.ts +41 -0
- package/src/sw/markers.ts +128 -0
- package/src/sw/module-transform.ts +364 -0
- package/src/sw/page-clients.ts +45 -0
- package/src/sw/profile.ts +90 -0
- package/src/sw/resolver.ts +224 -0
- package/src/sw/router.ts +360 -0
- package/src/sw/runtime-exports.ts +39 -0
- package/src/sw/runtime-module.ts +13 -0
- package/src/sw/source-hash.ts +37 -0
- package/src/sw/source-provider.ts +20 -0
- package/src/sw/versions.ts +96 -0
- package/src/sw/worker.ts +91 -0
- package/static/README.md +15 -0
- package/static/profile.example.json +15 -0
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join, relative } from "node:path";
|
|
3
|
+
import { buildBarrelIndex, shapeOf } from "./barrels.ts";
|
|
4
|
+
import { sideEffectsRule } from "../sw/barrels.ts";
|
|
5
|
+
import { moduleFormat, packageOf } from "./trace.ts";
|
|
6
|
+
|
|
7
|
+
export function dependencyBarrelIndex(options: {
|
|
8
|
+
path: string;
|
|
9
|
+
canonical: (path: string) => string;
|
|
10
|
+
resolve: (from: string, source: string) => string | undefined;
|
|
11
|
+
}) {
|
|
12
|
+
const paths = new Map<string, string>();
|
|
13
|
+
const rules = new Map<string, (path: string) => boolean>();
|
|
14
|
+
const canonical = (path: string) => {
|
|
15
|
+
const url = options.canonical(path).slice("/npm/".length);
|
|
16
|
+
paths.set(url, path);
|
|
17
|
+
return url;
|
|
18
|
+
};
|
|
19
|
+
const pathOf = (url: string) => {
|
|
20
|
+
const path = paths.get(url);
|
|
21
|
+
if (!path) throw new Error(`Unknown dependency barrel module ${url}`);
|
|
22
|
+
return path;
|
|
23
|
+
};
|
|
24
|
+
return buildBarrelIndex({
|
|
25
|
+
urls: [canonical(options.path)],
|
|
26
|
+
shape(url) {
|
|
27
|
+
const path = pathOf(url);
|
|
28
|
+
if (!/\.m?js$/.test(path)) return null;
|
|
29
|
+
const module = moduleFormat(path);
|
|
30
|
+
return module.format === "esm" ? shapeOf(module.module) : null;
|
|
31
|
+
},
|
|
32
|
+
resolve(url, source) {
|
|
33
|
+
const path = options.resolve(dirname(pathOf(url)), source);
|
|
34
|
+
return path ? canonical(path) : null;
|
|
35
|
+
},
|
|
36
|
+
sideEffectFree(url) {
|
|
37
|
+
const path = pathOf(url);
|
|
38
|
+
const pkg = packageOf(path);
|
|
39
|
+
let rule = rules.get(pkg.dir);
|
|
40
|
+
if (!rule) {
|
|
41
|
+
const manifest = JSON.parse(readFileSync(join(pkg.dir, "package.json"), "utf8")) as { sideEffects?: unknown };
|
|
42
|
+
rule = sideEffectsRule(manifest.sideEffects, pkg.name);
|
|
43
|
+
rules.set(pkg.dir, rule);
|
|
44
|
+
}
|
|
45
|
+
return rule(relative(pkg.dir, path).replaceAll("\\", "/"));
|
|
46
|
+
},
|
|
47
|
+
}).index;
|
|
48
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join, relative, sep } from "node:path";
|
|
3
|
+
import { init } from "es-module-lexer";
|
|
4
|
+
import { ResolverFactory } from "rolldown/experimental";
|
|
5
|
+
import { parseSync } from "rolldown/utils";
|
|
6
|
+
import type { Plugin } from "rolldown";
|
|
7
|
+
import type { BarrelIndex } from "../schema.ts";
|
|
8
|
+
import { guardedBarrels } from "../sw/barrels.ts";
|
|
9
|
+
import { mergeBarrels } from "../sw/composition.ts";
|
|
10
|
+
import { transformModule } from "../sw/module-transform.ts";
|
|
11
|
+
import { packageOf } from "./trace.ts";
|
|
12
|
+
import { dependencyBarrelIndex } from "./dependency-barrel-index.ts";
|
|
13
|
+
|
|
14
|
+
export function dependencyBarrels({ target, root, barrelSource, external }: { target: "node" | "browser"; root: string; barrelSource: "published" | "installed"; external: ReadonlySet<string> }): Plugin {
|
|
15
|
+
const resolver = new ResolverFactory({ conditionNames: [target, "import", "default"], mainFields: target === "browser" ? ["browser", "module", "main"] : ["module", "main"], extensions: [".mjs", ".js", ".cjs", ".json"], symlinks: true });
|
|
16
|
+
const loaded = new Set<string>();
|
|
17
|
+
const indexed = new Set<string>();
|
|
18
|
+
const directories = new Map<string, string>();
|
|
19
|
+
const installedIdentities = new Map<string, number>();
|
|
20
|
+
let index: BarrelIndex = { modules: [], barrels: {} };
|
|
21
|
+
const canonical = (path: string) => {
|
|
22
|
+
const pkg = packageOf(path);
|
|
23
|
+
if (barrelSource === "installed" && !installedIdentities.has(pkg.dir)) installedIdentities.set(pkg.dir, installedIdentities.size);
|
|
24
|
+
const instance = installedIdentities.get(pkg.dir);
|
|
25
|
+
const key = `${pkg.name}@${pkg.version}${instance === undefined ? "" : `+installed.${instance}`}`;
|
|
26
|
+
directories.set(key, pkg.dir);
|
|
27
|
+
if (!loaded.has(pkg.dir)) {
|
|
28
|
+
loaded.add(pkg.dir);
|
|
29
|
+
const file = join(pkg.dir, "dist/runtime/barrels.json");
|
|
30
|
+
if (barrelSource === "published" && existsSync(file)) {
|
|
31
|
+
const manifest = JSON.parse(readFileSync(join(pkg.dir, "package.json"), "utf8")) as { sideEffects?: boolean | string[] };
|
|
32
|
+
const published = guardedBarrels({ index: JSON.parse(readFileSync(file, "utf8")) as BarrelIndex, name: pkg.name, version: pkg.version, ...(manifest.sideEffects === undefined ? {} : { sideEffects: manifest.sideEffects }) });
|
|
33
|
+
// A published index records its dependencies at the publisher's installed versions; trust only barrels that stay
|
|
34
|
+
// inside the library and index everything else from this install.
|
|
35
|
+
const own = `${pkg.name}@${pkg.version}/`;
|
|
36
|
+
const inside = (at: number | [number, string]) => published.modules[typeof at === "number" ? at : at[0]]?.startsWith(own) === true;
|
|
37
|
+
index = mergeBarrels([index, { modules: published.modules, barrels: Object.fromEntries(Object.entries(published.barrels).filter(([url, entries]) => url.startsWith(own) && Object.values(entries).every(inside))) }]);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return `/npm/${key}/${relative(pkg.dir, path).split(sep).join("/")}`;
|
|
41
|
+
};
|
|
42
|
+
const localPath = (url: string) => {
|
|
43
|
+
const match = /^\/npm\/((?:@[^/]+\/)?[^/]+)\/(.+)$/.exec(url);
|
|
44
|
+
const root = match && directories.get(match[1]!);
|
|
45
|
+
if (!match || !root) throw new Error(`Unknown compiled runtime module ${url}`);
|
|
46
|
+
return join(root, match[2]!);
|
|
47
|
+
};
|
|
48
|
+
return {
|
|
49
|
+
name: "dependency-runtime-barrels",
|
|
50
|
+
async buildStart() { await init; },
|
|
51
|
+
resolveId(source) { return source.startsWith("/npm/") ? localPath(source) : null; },
|
|
52
|
+
transform(code, id) {
|
|
53
|
+
const entry = id.startsWith("\0entry:");
|
|
54
|
+
if (!entry && (id.startsWith("\0") || !/\.m?js$/.test(id))) return null;
|
|
55
|
+
const parsed = parseSync(id, code, { lang: "js", sourceType: "unambiguous" });
|
|
56
|
+
if (!parsed.module.hasModuleSyntax) return null;
|
|
57
|
+
const from = entry ? root : dirname(id);
|
|
58
|
+
const url = entry ? "/runtime-entry.js" : canonical(id);
|
|
59
|
+
for (const item of parsed.module.staticImports) {
|
|
60
|
+
if (external.has(item.moduleRequest.value)) continue;
|
|
61
|
+
const path = resolver.sync(from, item.moduleRequest.value).path;
|
|
62
|
+
if (path) {
|
|
63
|
+
canonical(path);
|
|
64
|
+
if (!indexed.has(path)) {
|
|
65
|
+
indexed.add(path);
|
|
66
|
+
const pkg = packageOf(path);
|
|
67
|
+
if (barrelSource === "installed" || !existsSync(join(pkg.dir, "dist/runtime/barrels.json"))) {
|
|
68
|
+
index = mergeBarrels([index, dependencyBarrelIndex({ path, canonical, resolve: (from, source) => resolver.sync(from, source).path })]);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return transformModule(code, { url, barrels: index, known: () => false, resolveBare(source) {
|
|
74
|
+
if (external.has(source)) return null;
|
|
75
|
+
const path = resolver.sync(from, source).path;
|
|
76
|
+
return path ? canonical(path) : null;
|
|
77
|
+
} }).code;
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
3
|
+
import { mkdir, open, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import { buildDependencyRuntime, type DependencyRuntime, type DependencyRuntimeOptions } from "./dependency-runtime.ts";
|
|
6
|
+
|
|
7
|
+
export type CachedDependencyRuntime = DependencyRuntime & { root: string };
|
|
8
|
+
|
|
9
|
+
export async function ensureDependencyRuntime(options: Omit<DependencyRuntimeOptions, "outDir"> & { cacheDir: string }): Promise<CachedDependencyRuntime> {
|
|
10
|
+
const identity = createHash("sha256").update(JSON.stringify({ root: resolve(options.root), target: options.target, entries: [...new Set(options.entries)].sort(), exports: options.exports, external: options.external, externalVersions: options.externalVersions, resolvedEntries: options.resolvedEntries, lock: readFileSync(join(options.root, "pnpm-lock.yaml"), "utf8"), compiler: readFileSync(new URL(import.meta.url)), abi: process.versions.modules })).digest("hex");
|
|
11
|
+
await mkdir(options.cacheDir, { recursive: true });
|
|
12
|
+
const pointer = join(options.cacheDir, `${identity}.json`);
|
|
13
|
+
const lock = `${pointer}.lock`;
|
|
14
|
+
const deadline = Date.now() + 300_000;
|
|
15
|
+
let handle;
|
|
16
|
+
while (!handle) {
|
|
17
|
+
try { handle = await open(lock, "wx"); }
|
|
18
|
+
catch (error) {
|
|
19
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
20
|
+
if (Date.now() > deadline) throw new Error(`Timed out waiting for compiled runtime ${lock}`);
|
|
21
|
+
await new Promise(done => setTimeout(done, 25));
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
if (existsSync(pointer)) {
|
|
26
|
+
const cached = JSON.parse(await readFile(pointer, "utf8")) as CachedDependencyRuntime;
|
|
27
|
+
if (Object.entries(cached.inputs).every(([path, hash]) => existsSync(path) && createHash("sha256").update(readFileSync(path)).digest("hex") === hash)) return cached;
|
|
28
|
+
}
|
|
29
|
+
const root = join(options.cacheDir, `${identity}-${randomUUID()}`);
|
|
30
|
+
const staging = `${root}.pending`;
|
|
31
|
+
try {
|
|
32
|
+
const runtime = await buildDependencyRuntime({ ...options, outDir: staging });
|
|
33
|
+
await rename(staging, root);
|
|
34
|
+
const result = { ...runtime, root };
|
|
35
|
+
await writeFile(`${pointer}.pending`, JSON.stringify(result));
|
|
36
|
+
await rename(`${pointer}.pending`, pointer);
|
|
37
|
+
return result;
|
|
38
|
+
} finally { await rm(staging, { recursive: true, force: true }); }
|
|
39
|
+
} finally { await handle.close(); await rm(lock); }
|
|
40
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { packageName, packageOf } from "./trace.ts";
|
|
4
|
+
import { specifierKind } from "./module-utils.ts";
|
|
5
|
+
|
|
6
|
+
export function optionalDependency(options: { source: string; importer: string }): boolean {
|
|
7
|
+
if (specifierKind(options.source) !== "bare" || options.importer.startsWith("\0")) return false;
|
|
8
|
+
const pkg = packageOf(options.importer);
|
|
9
|
+
const manifest = JSON.parse(readFileSync(join(pkg.dir, "package.json"), "utf8")) as {
|
|
10
|
+
optionalDependencies?: Record<string, string>;
|
|
11
|
+
peerDependenciesMeta?: Record<string, { optional?: boolean }>;
|
|
12
|
+
};
|
|
13
|
+
const name = packageName(options.source);
|
|
14
|
+
return Object.hasOwn(manifest.optionalDependencies ?? {}, name) || manifest.peerDependenciesMeta?.[name]?.optional === true;
|
|
15
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { isBuiltin } from "node:module";
|
|
2
|
+
import { isAbsolute, join } from "node:path";
|
|
3
|
+
import type { Plugin } from "rolldown";
|
|
4
|
+
import { parseSync } from "rolldown/utils";
|
|
5
|
+
import { ensureDependencyRuntime, type CachedDependencyRuntime } from "./dependency-cache.ts";
|
|
6
|
+
import { moduleFormat } from "./trace.ts";
|
|
7
|
+
|
|
8
|
+
export function dependencyRuntimePlugin(options: { root: string; cacheDir: string; base: CachedDependencyRuntime; versions?: Record<string, string> }): Plugin {
|
|
9
|
+
const modules = new Map<string, { path: string; styles: string[] }>();
|
|
10
|
+
const external = Object.fromEntries(Object.entries(options.base.imports).map(([source, path]) => [source, join(options.base.root, path)]));
|
|
11
|
+
const pinned = new Set(Object.values(external));
|
|
12
|
+
const prefix = "\0page-runtime:";
|
|
13
|
+
const bindings = new Map<string, Map<string, Set<string> | null>>();
|
|
14
|
+
return {
|
|
15
|
+
name: "page-runtime-dependencies",
|
|
16
|
+
transform(code, id) {
|
|
17
|
+
if (id.startsWith("\0") || !/\.[cm]?[jt]sx?$/.test(id)) return null;
|
|
18
|
+
const lang = id.endsWith(".tsx") ? "tsx" : id.endsWith(".ts") ? "ts" : id.endsWith(".jsx") ? "jsx" : "js";
|
|
19
|
+
const parsed = parseSync(id, code, { lang, sourceType: "unambiguous" });
|
|
20
|
+
if (parsed.errors.length) throw new Error(`${id}: ${parsed.errors.map(error => error.message).join("\n")}`);
|
|
21
|
+
const imported = new Map<string, Set<string> | null>();
|
|
22
|
+
for (const item of parsed.module.staticImports) {
|
|
23
|
+
const source = item.moduleRequest.value;
|
|
24
|
+
if (imported.get(source) === null) continue;
|
|
25
|
+
const names = imported.get(source) ?? new Set<string>();
|
|
26
|
+
for (const entry of item.entries) {
|
|
27
|
+
if (entry.isType) continue;
|
|
28
|
+
if (entry.importName.kind === "NamespaceObject") { imported.set(source, null); break; }
|
|
29
|
+
names.add(entry.importName.kind === "Default" ? "default" : entry.importName.name!);
|
|
30
|
+
}
|
|
31
|
+
if (!imported.has(source) || imported.get(source) !== null) imported.set(source, names);
|
|
32
|
+
}
|
|
33
|
+
bindings.set(id, imported);
|
|
34
|
+
return null;
|
|
35
|
+
},
|
|
36
|
+
async resolveId(source, importer) {
|
|
37
|
+
if (source.startsWith(prefix)) return source;
|
|
38
|
+
if (pinned.has(source)) return { id: source, external: options.base.target === "node" };
|
|
39
|
+
if (!importer || source.startsWith(".") || source.startsWith("\0") || isAbsolute(source) || isBuiltin(source) || /^[a-z][a-z0-9+.-]*:/i.test(source) || /[?#]|\.(css|json)$/.test(source)) return null;
|
|
40
|
+
const names = bindings.get(importer)?.get(source);
|
|
41
|
+
const key = JSON.stringify([source, names ? [...names].sort() : null]);
|
|
42
|
+
if (!modules.has(key)) {
|
|
43
|
+
const runtime = external[source] ? options.base : await ensureDependencyRuntime({ root: options.root, cacheDir: options.cacheDir, entries: [source], target: options.base.target, external, ...(options.versions ? { externalVersions: options.versions } : {}), ...(names?.size ? { exports: { [source]: [...names].sort() } } : {}) });
|
|
44
|
+
const path = join(runtime.root, runtime.imports[source]!);
|
|
45
|
+
pinned.add(path);
|
|
46
|
+
modules.set(key, { path, styles: runtime.styles.map(style => join(runtime.root, style)) });
|
|
47
|
+
}
|
|
48
|
+
return `${prefix}${key}`;
|
|
49
|
+
},
|
|
50
|
+
load(id) {
|
|
51
|
+
if (!id.startsWith(prefix)) return null;
|
|
52
|
+
const module = modules.get(id.slice(prefix.length));
|
|
53
|
+
if (!module) throw new Error(`Missing dependency runtime module ${id}`);
|
|
54
|
+
const hasDefault = moduleFormat(module.path).module.staticExports.some(item => item.entries.some(entry => entry.exportName.kind === "Default" || entry.exportName.name === "default"));
|
|
55
|
+
return [...module.styles.map(style => `import ${JSON.stringify(style)};`), `export * from ${JSON.stringify(module.path)};`, ...(hasDefault ? [`export { default } from ${JSON.stringify(module.path)};`] : [])].join("\n");
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { isBuiltin } from "node:module";
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { mkdir, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
6
|
+
import { rolldown, type Plugin } from "rolldown";
|
|
7
|
+
import { ClosureTracer, createResolver, IMPORT_CONDITIONS, moduleFormat, packageName, packageOf, resolveBrowser } from "./trace.ts";
|
|
8
|
+
import { dependencyBarrels } from "./dependency-barrels.ts";
|
|
9
|
+
import { commonJsExportNames, type CommonJsExports } from "./commonjs-exports.ts";
|
|
10
|
+
import { optionalDependency } from "./dependency-optional.ts";
|
|
11
|
+
import { bundleWorkerURLs } from "./dependency-workers.ts";
|
|
12
|
+
import { satisfiesVersion } from "../sw/versions.ts";
|
|
13
|
+
|
|
14
|
+
export interface DependencyRuntimeOptions {
|
|
15
|
+
root: string;
|
|
16
|
+
outDir: string;
|
|
17
|
+
entries: string[];
|
|
18
|
+
target: "node" | "browser";
|
|
19
|
+
external?: Record<string, string>;
|
|
20
|
+
externalVersions?: Record<string, string>;
|
|
21
|
+
resolvedEntries?: Record<string, string>;
|
|
22
|
+
exports?: Record<string, string[]>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface DependencyRuntime {
|
|
26
|
+
schema: 1;
|
|
27
|
+
target: "node" | "browser";
|
|
28
|
+
imports: Record<string, string>;
|
|
29
|
+
integrity: Record<string, string>;
|
|
30
|
+
inputs: Record<string, string>;
|
|
31
|
+
styles: string[];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function buildInstalledDependencyRuntime(options: DependencyRuntimeOptions): Promise<DependencyRuntime> {
|
|
35
|
+
return buildDependencyRuntime(options, "installed");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function buildDependencyRuntime(options: DependencyRuntimeOptions, barrelSource: "published" | "installed" = "published"): Promise<DependencyRuntime> {
|
|
39
|
+
if (!options.entries.length) throw new Error("A dependency runtime requires at least one entry");
|
|
40
|
+
const root = resolve(options.root);
|
|
41
|
+
const entries = [...new Set(options.entries)].sort();
|
|
42
|
+
const inputs: Record<string, string> = {};
|
|
43
|
+
const trackInput = (path: string, code: string) => { inputs[path] = createHash("sha256").update(code).digest("hex"); };
|
|
44
|
+
const styles = new Set<string>();
|
|
45
|
+
const assets = new Set<string>();
|
|
46
|
+
const workers = new Map<string, Promise<string>>();
|
|
47
|
+
const resolved = new Map<string, string>();
|
|
48
|
+
const peersByPackage = new Map<string, Record<string, string>>();
|
|
49
|
+
let commonJs: CommonJsExports = {};
|
|
50
|
+
const browserResolver = createResolver(IMPORT_CONDITIONS);
|
|
51
|
+
const plugin: Plugin = {
|
|
52
|
+
name: "dependency-runtime",
|
|
53
|
+
async buildStart() {
|
|
54
|
+
for (const entry of entries) {
|
|
55
|
+
if (options.resolvedEntries?.[entry]) {
|
|
56
|
+
resolved.set(entry, options.resolvedEntries[entry]);
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
const result = await this.resolve(entry, join(root, "package.json"), { skipSelf: true });
|
|
60
|
+
if (!result || result.external) throw new Error(`Cannot resolve runtime entry ${entry} from ${root}`);
|
|
61
|
+
resolved.set(entry, result.id);
|
|
62
|
+
}
|
|
63
|
+
const paths = [...new Set(resolved.values())].filter(path => moduleFormat(path).format === "commonjs");
|
|
64
|
+
commonJs = await commonJsExportNames(paths);
|
|
65
|
+
},
|
|
66
|
+
async resolveId(source, importer, extra) {
|
|
67
|
+
if (source.startsWith("\0external-require:")) return source;
|
|
68
|
+
if (options.external?.[source]) {
|
|
69
|
+
const version = options.externalVersions?.[packageName(source)];
|
|
70
|
+
const from = version && importer && !importer.startsWith("\0") ? importer : undefined;
|
|
71
|
+
const original = version || extra.kind === "require-call" ? await this.resolve(source, from ?? join(root, "package.json"), { ...extra, skipSelf: true }) : undefined;
|
|
72
|
+
let sharedPeer = false;
|
|
73
|
+
if (version && from) {
|
|
74
|
+
const pkg = packageOf(from);
|
|
75
|
+
if (!peersByPackage.has(pkg.dir)) peersByPackage.set(pkg.dir, JSON.parse(readFileSync(join(pkg.dir, "package.json"), "utf8")).peerDependencies ?? {});
|
|
76
|
+
const range = peersByPackage.get(pkg.dir)?.[packageName(source)];
|
|
77
|
+
if (range) {
|
|
78
|
+
if (!satisfiesVersion(version, range)) throw new Error(`${pkg.name} requires ${packageName(source)}@${range}; the runtime provides ${version}`);
|
|
79
|
+
sharedPeer = true;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (!version || sharedPeer || !original || original.external || packageOf(original.id).version === version) {
|
|
83
|
+
if (extra.kind !== "require-call") return { id: source, external: true };
|
|
84
|
+
const commonJs = !original || original.external ? moduleFormat(options.external[source]).module.staticExports.some(item => item.entries.some(entry => entry.exportName.kind === "Default")) : moduleFormat(original.id).format === "commonjs";
|
|
85
|
+
return `\0external-require:${JSON.stringify({ source, commonJs })}`;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
if (isBuiltin(source)) {
|
|
89
|
+
if (options.target === "browser") {
|
|
90
|
+
const mapped = importer && resolveBrowser({ resolver: browserResolver, fromDir: dirname(importer), specifier: source });
|
|
91
|
+
if (mapped && mapped.empty) return "\0browser-empty";
|
|
92
|
+
if (mapped && mapped.path) return mapped.path;
|
|
93
|
+
throw new Error(`Browser runtime cannot import ${source} from ${importer}`);
|
|
94
|
+
}
|
|
95
|
+
return { id: source, external: true };
|
|
96
|
+
}
|
|
97
|
+
if (source.startsWith("\0entry:")) return source;
|
|
98
|
+
if (extra.kind === "dynamic-import" && importer && optionalDependency({ source, importer })) {
|
|
99
|
+
return await this.resolve(source, importer, { ...extra, skipSelf: true }) ?? { id: source, external: true };
|
|
100
|
+
}
|
|
101
|
+
if (importer?.startsWith("\0entry:")) return this.resolve(source, join(root, "package.json"), { ...extra, skipSelf: true });
|
|
102
|
+
if (/^(react|react-dom|scheduler)(\/|$)/.test(source)) return this.resolve(source, join(root, "package.json"), { ...extra, skipSelf: true });
|
|
103
|
+
return null;
|
|
104
|
+
},
|
|
105
|
+
load(id) {
|
|
106
|
+
if (id === "\0browser-empty") return "export default {};";
|
|
107
|
+
if (id.startsWith("\0external-require:")) {
|
|
108
|
+
const { source, commonJs } = JSON.parse(id.slice("\0external-require:".length)) as { source: string; commonJs: boolean };
|
|
109
|
+
return `import * as ns from ${JSON.stringify(source)}; module.exports = ${commonJs ? "ns.default" : "ns"};`;
|
|
110
|
+
}
|
|
111
|
+
if (id.endsWith(".css")) {
|
|
112
|
+
const tracer = new ClosureTracer({ name: "dependency-styles", resolveFrom: root, entries: [], topLevel: [], inherits: [] });
|
|
113
|
+
tracer.target(id, id, "relative");
|
|
114
|
+
if (tracer.failures.length) throw new Error(tracer.failures.map(item => item.detail).join("\n"));
|
|
115
|
+
for (const file of tracer.files.values()) {
|
|
116
|
+
const fileName = `assets/${file.url}`;
|
|
117
|
+
const source = readFileSync(file.path);
|
|
118
|
+
inputs[file.path] = createHash("sha256").update(source).digest("hex");
|
|
119
|
+
if (file.path === id) styles.add(fileName);
|
|
120
|
+
if (!assets.has(fileName)) this.emitFile({ type: "asset", fileName, source });
|
|
121
|
+
assets.add(fileName);
|
|
122
|
+
}
|
|
123
|
+
return { code: "export {};", moduleType: "js" };
|
|
124
|
+
}
|
|
125
|
+
if (!id.startsWith("\0entry:")) return null;
|
|
126
|
+
const specifier = id.slice(7, -4);
|
|
127
|
+
const path = resolved.get(specifier);
|
|
128
|
+
if (!path) throw new Error(`Missing resolved runtime entry ${id}`);
|
|
129
|
+
const names = commonJs[path]?.names;
|
|
130
|
+
const requested = options.exports?.[specifier];
|
|
131
|
+
if (!names) {
|
|
132
|
+
const source = JSON.stringify(options.resolvedEntries?.[specifier] ?? specifier);
|
|
133
|
+
if (requested) return `import { ${requested.map((name, index) => `${JSON.stringify(name)} as e${index}`).join(", ")} } from ${source}; export { ${requested.map((name, index) => `e${index} as ${JSON.stringify(name)}`).join(", ")} };`;
|
|
134
|
+
return `export * from ${source}; ${moduleFormat(path).module.staticExports.some(item => item.entries.some(entry => entry.exportName.kind === "Default" || entry.exportName.name === "default")) ? `export { default } from ${source};` : ""}`;
|
|
135
|
+
}
|
|
136
|
+
const exported = names.filter(name => name !== "default" && name !== "__esModule");
|
|
137
|
+
return [`import value from ${JSON.stringify(path)};`, "export default value;", ...exported.map((name, index) => `const e${index} = value[${JSON.stringify(name)}]; export { e${index} as ${JSON.stringify(name)} };`)].join("\n");
|
|
138
|
+
},
|
|
139
|
+
async transform(code, id) {
|
|
140
|
+
if (!id.startsWith("\0") && !id.endsWith(".css")) trackInput(id, code);
|
|
141
|
+
if (id.startsWith("\0")) return null;
|
|
142
|
+
if (options.target === "browser" && code.includes("import.meta.url")) code = await bundleWorkerURLs({ code, id, context: this, workers, trackInput });
|
|
143
|
+
return code.replace(/new URL\(\s*(['"])(\.{1,2}\/[^'"]+)\1\s*,\s*import\.meta\.url\s*\)/g, (_match, _quote: string, reference: string) => {
|
|
144
|
+
const path = resolve(dirname(id), reference);
|
|
145
|
+
const source = readFileSync(path);
|
|
146
|
+
inputs[path] = createHash("sha256").update(source).digest("hex");
|
|
147
|
+
const asset = this.emitFile({ type: "asset", name: basename(path), source });
|
|
148
|
+
return `new URL(import.meta.ROLLUP_FILE_URL_${asset})`;
|
|
149
|
+
});
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
await rm(options.outDir, { recursive: true, force: true });
|
|
153
|
+
await mkdir(options.outDir, { recursive: true });
|
|
154
|
+
const bundle = await rolldown({
|
|
155
|
+
input: Object.fromEntries(entries.map((specifier, index) => [`entry-${index}`, `\0entry:${specifier}.mjs`])),
|
|
156
|
+
plugins: [plugin, dependencyBarrels({ target: options.target, root, barrelSource, external: new Set(Object.keys(options.external ?? {})) })],
|
|
157
|
+
platform: options.target,
|
|
158
|
+
resolve: { conditionNames: [options.target, "import", "default"], mainFields: options.target === "browser" ? ["browser", "module", "main"] : ["module", "main"], aliasFields: options.target === "browser" ? [["browser"]] : [] },
|
|
159
|
+
transform: { define: { "process.env.NODE_ENV": JSON.stringify("development") } },
|
|
160
|
+
onLog(level, log, handler) {
|
|
161
|
+
if (log.code === "UNRESOLVED_IMPORT") throw new Error(log.message);
|
|
162
|
+
// Page runtimes execute whole React trees; React Server Component boundaries do not apply.
|
|
163
|
+
if (log.code === "MODULE_LEVEL_DIRECTIVE") return;
|
|
164
|
+
handler(level, log);
|
|
165
|
+
},
|
|
166
|
+
});
|
|
167
|
+
try {
|
|
168
|
+
const paths = Object.fromEntries(Object.entries(options.external ?? {}).map(([specifier, path]) => {
|
|
169
|
+
const value = relative(options.outDir, path).split(sep).join("/");
|
|
170
|
+
return [specifier, value.startsWith(".") ? value : `./${value}`];
|
|
171
|
+
}));
|
|
172
|
+
const { output } = await bundle.write({ dir: options.outDir, format: "esm", entryFileNames: "[name].mjs", chunkFileNames: "[name]-[hash].mjs", paths, ...(options.target === "node" ? { banner: 'import { createRequire as __runtimeRequire } from "node:module"; const require = __runtimeRequire(import.meta.url);' } : {}) });
|
|
173
|
+
if (options.target === "browser") {
|
|
174
|
+
for (const item of output) if (item.type === "chunk" && /(?<![\w$.])__require\s*\(/.test(item.code)) throw new Error(`Browser dependency runtime ${item.fileName} still contains a dynamic require`);
|
|
175
|
+
}
|
|
176
|
+
const imports = Object.fromEntries(entries.map((specifier, index) => [specifier, `entry-${index}.mjs`]));
|
|
177
|
+
const integrity = Object.fromEntries(output.map(item => [item.fileName, createHash("sha256").update(readFileSync(join(options.outDir, item.fileName))).digest("hex")]));
|
|
178
|
+
const runtime: DependencyRuntime = { schema: 1, target: options.target, imports, integrity, inputs, styles: [...styles] };
|
|
179
|
+
await writeFile(join(options.outDir, "runtime.json"), JSON.stringify(runtime, null, 2));
|
|
180
|
+
return runtime;
|
|
181
|
+
} finally { await bundle.close(); }
|
|
182
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { basename, dirname, resolve } from "node:path";
|
|
2
|
+
import { rolldown, type PluginContext } from "rolldown";
|
|
3
|
+
|
|
4
|
+
const workerURL = /(new\s+(?:Worker|SharedWorker)\s*\(\s*)new URL\(\s*(['"])([^'":?#]+)\2\s*,\s*import\.meta\.url\s*\)/g;
|
|
5
|
+
|
|
6
|
+
export async function bundleWorkerURLs(options: { code: string; id: string; context: PluginContext; workers: Map<string, Promise<string>>; trackInput: (path: string, code: string) => void }): Promise<string> {
|
|
7
|
+
const matches = [...options.code.matchAll(workerURL)].filter(match => !match[3]!.startsWith("/"));
|
|
8
|
+
const replacements = await Promise.all(matches.map(async match => {
|
|
9
|
+
const path = resolve(dirname(options.id), match[3]!);
|
|
10
|
+
let pending = options.workers.get(path);
|
|
11
|
+
if (!pending) {
|
|
12
|
+
pending = compileWorker(path, options.trackInput).then(source => options.context.emitFile({ type: "asset", name: basename(path), source }));
|
|
13
|
+
options.workers.set(path, pending);
|
|
14
|
+
}
|
|
15
|
+
return match[1] + `new URL(import.meta.ROLLUP_FILE_URL_${await pending})`;
|
|
16
|
+
}));
|
|
17
|
+
let code = options.code;
|
|
18
|
+
for (let index = matches.length - 1; index >= 0; index--) {
|
|
19
|
+
const match = matches[index]!;
|
|
20
|
+
code = code.slice(0, match.index) + replacements[index] + code.slice(match.index + match[0].length);
|
|
21
|
+
}
|
|
22
|
+
return code;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function compileWorker(path: string, trackInput: (path: string, code: string) => void): Promise<string> {
|
|
26
|
+
const worker = await rolldown({
|
|
27
|
+
input: path,
|
|
28
|
+
platform: "browser",
|
|
29
|
+
plugins: [{ name: "worker-inputs", transform(code, id) { if (!id.startsWith("\0")) trackInput(id, code); } }],
|
|
30
|
+
onLog(level, log, handler) {
|
|
31
|
+
if (log.code === "UNRESOLVED_IMPORT") throw new Error(log.message);
|
|
32
|
+
handler(level, log);
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
try {
|
|
36
|
+
const { output } = await worker.generate({ format: "esm", codeSplitting: false, minify: true });
|
|
37
|
+
const chunk = output[0];
|
|
38
|
+
if (output.length !== 1 || chunk?.type !== "chunk" || chunk.imports.length || chunk.dynamicImports.length) throw new Error(`Worker ${path} must compile to one browser script`);
|
|
39
|
+
return chunk.code;
|
|
40
|
+
} finally { await worker.close(); }
|
|
41
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export class NodeBuiltinError extends Error {
|
|
2
|
+
override name = "NodeBuiltinError";
|
|
3
|
+
}
|
|
4
|
+
export class CommonJsConversionError extends Error {
|
|
5
|
+
override name = "CommonJsConversionError";
|
|
6
|
+
}
|
|
7
|
+
export class BaseSetRemapError extends Error {
|
|
8
|
+
override name = "BaseSetRemapError";
|
|
9
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { Fragment, ImportMap } from "../schema.ts";
|
|
2
|
+
import type { ClosureTracer, Failure } from "./trace.ts";
|
|
3
|
+
|
|
4
|
+
function sorted<T>(record: Record<string, T>): Record<string, T> {
|
|
5
|
+
return Object.fromEntries(Object.entries(record).sort(([a], [b]) => a.localeCompare(b)));
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function fragmentOf(tracer: ClosureTracer, aliases: Record<string, string> = {}): Fragment {
|
|
9
|
+
return {
|
|
10
|
+
fragment: 1,
|
|
11
|
+
name: tracer.spec.name,
|
|
12
|
+
imports: sorted(tracer.imports),
|
|
13
|
+
scopes: sorted(Object.fromEntries(Object.entries(tracer.scopes).map(([key, table]) => [key, sorted(table)]))),
|
|
14
|
+
remaps: sorted(tracer.remaps),
|
|
15
|
+
aliases,
|
|
16
|
+
inherits: [...tracer.inherited.keys()].sort(),
|
|
17
|
+
integrity: sorted(Object.fromEntries([...tracer.files.values()].map((file) => [file.url, file.integrity]))),
|
|
18
|
+
...(tracer.spec.compiler ? { compiler: tracer.spec.compiler } : {}),
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function lookup(table: Record<string, string>, specifier: string): string | null {
|
|
23
|
+
const exact = table[specifier];
|
|
24
|
+
if (exact) return exact;
|
|
25
|
+
let best: string | null = null;
|
|
26
|
+
for (const key of Object.keys(table)) {
|
|
27
|
+
if (key.endsWith("/") && specifier.startsWith(key) && (!best || key.length > best.length)) best = key;
|
|
28
|
+
}
|
|
29
|
+
return best ? `${table[best]}${specifier.slice(best.length)}` : null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Resolves a bare specifier the way a browser applies an import map: most specific scope first, then the top level. */
|
|
33
|
+
export function resolveSpecifier(map: ImportMap, specifier: string, referrer: string): string | null {
|
|
34
|
+
const scopes = Object.keys(map.scopes)
|
|
35
|
+
.filter((scope) => referrer.startsWith(scope))
|
|
36
|
+
.sort((a, b) => b.length - a.length);
|
|
37
|
+
for (const scope of scopes) {
|
|
38
|
+
const table = map.scopes[scope];
|
|
39
|
+
const resolved = table ? lookup(table, specifier) : null;
|
|
40
|
+
if (resolved) return resolved;
|
|
41
|
+
}
|
|
42
|
+
return lookup(map.imports, specifier);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Composes fragments into one page import map. Fragments are applied in order; a later fragment
|
|
47
|
+
* remapping a specifier or a scope entry is an error, and so is an inherited specifier nobody maps.
|
|
48
|
+
*/
|
|
49
|
+
export function composeImportMap(fragments: Fragment[], base: string): { map: ImportMap; failures: Failure[] } {
|
|
50
|
+
const failures: Failure[] = [];
|
|
51
|
+
const url = (value: string) => `${base}${value}`;
|
|
52
|
+
const map: ImportMap = { imports: {}, scopes: {} };
|
|
53
|
+
for (const fragment of fragments) {
|
|
54
|
+
const owned: string[] = [];
|
|
55
|
+
for (const [specifier, target] of Object.entries(fragment.imports)) {
|
|
56
|
+
const existing = map.imports[specifier];
|
|
57
|
+
if (existing && existing !== url(target)) failures.push({ name: fragment.name, detail: `remaps ${specifier}: ${existing} → ${url(target)}` });
|
|
58
|
+
else map.imports[specifier] = url(target);
|
|
59
|
+
owned.push(specifier);
|
|
60
|
+
}
|
|
61
|
+
for (const [from, to] of Object.entries(fragment.remaps)) {
|
|
62
|
+
const existing = map.imports[url(from)];
|
|
63
|
+
if (existing && existing !== url(to)) failures.push({ name: fragment.name, detail: `remaps ${from} twice: ${existing} and ${url(to)}` });
|
|
64
|
+
else map.imports[url(from)] = url(to);
|
|
65
|
+
}
|
|
66
|
+
for (const [alias, prefix] of Object.entries(fragment.aliases)) {
|
|
67
|
+
for (const specifier of owned) {
|
|
68
|
+
if (specifier !== prefix && !specifier.startsWith(`${prefix}/`)) continue;
|
|
69
|
+
const target = map.imports[specifier];
|
|
70
|
+
if (target) map.imports[`${alias}${specifier.slice(prefix.length)}`] = target;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
for (const [scope, table] of Object.entries(fragment.scopes)) {
|
|
74
|
+
const merged = (map.scopes[url(scope)] ??= {});
|
|
75
|
+
for (const [specifier, target] of Object.entries(table)) {
|
|
76
|
+
const existing = merged[specifier];
|
|
77
|
+
if (existing && existing !== url(target)) {
|
|
78
|
+
failures.push({ name: fragment.name, detail: `scope ${scope} maps ${specifier} to both ${existing} and ${url(target)}` });
|
|
79
|
+
} else merged[specifier] = url(target);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
for (const fragment of fragments) {
|
|
84
|
+
for (const specifier of fragment.inherits) {
|
|
85
|
+
if (!lookup(map.imports, specifier)) failures.push({ name: fragment.name, detail: `imports ${specifier}, which no fragment maps at the top level` });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return { map, failures };
|
|
89
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { buildLibraryRuntime, BASE_PACKAGES, BASE_ENTRIES, type LibraryRuntimeOptions, type BuiltLibraryRuntime } from "./library-runtime.ts";
|
|
2
|
+
export { buildDependencyRuntime, type DependencyRuntime, type DependencyRuntimeOptions } from "./dependency-runtime.ts";
|
|
3
|
+
export { ensureDependencyRuntime, type CachedDependencyRuntime } from "./dependency-cache.ts";
|
|
4
|
+
export { checkFragment } from "./check-fragment.ts";
|
|
5
|
+
export { BaseSetRemapError, CommonJsConversionError, NodeBuiltinError } from "./errors.ts";
|
|
6
|
+
export { composeImportMap, resolveSpecifier } from "./fragment.ts";
|
|
7
|
+
export type { Fragment, BarrelIndex } from "../schema.ts";
|