@jxsuite/compiler 9.0.1 → 9.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/dist/cli.js +204 -205
- package/dist/compiler.js +134 -138
- package/package.json +18 -18
- package/src/cli.ts +13 -3
- package/src/compiler.ts +25 -12
- package/src/shared.ts +560 -118
- package/src/site/bundler-backend.bun.ts +36 -2
- package/src/site/bundler-backend.node.ts +42 -2
- package/src/site/bundler-backend.ts +12 -0
- package/src/site/bundler.ts +40 -4
- package/src/site/external-class.ts +290 -0
- package/src/site/format-host.ts +49 -10
- package/src/site/headers-emitter.ts +6 -5
- package/src/site/image-cache.ts +34 -3
- package/src/site/image-optimizer.ts +51 -11
- package/src/site/image-transform.ts +100 -62
- package/src/site/pages-discovery.ts +8 -1
- package/src/site/prototype-resolver.ts +91 -195
- package/src/site/service-worker.ts +4 -3
- package/src/site/site-build.ts +179 -14
- package/src/site/site-loader.ts +9 -0
- package/src/targets/compile-class.ts +42 -3
- package/src/targets/compile-client.ts +177 -55
- package/src/targets/compile-element.ts +308 -46
- package/src/targets/compile-static.ts +21 -83
|
@@ -6,9 +6,9 @@
|
|
|
6
6
|
* both under one Bun.
|
|
7
7
|
*/
|
|
8
8
|
import { rmSync, writeFileSync } from "node:fs";
|
|
9
|
-
import { join } from "node:path";
|
|
9
|
+
import { join, resolve } from "node:path";
|
|
10
10
|
import type { BuildConfig } from "bun";
|
|
11
|
-
import type { BackendBuild, BundleTargetName } from "./bundler-backend.ts";
|
|
11
|
+
import type { BackendBuild, BackendSplitBuild, BundleTargetName } from "./bundler-backend.ts";
|
|
12
12
|
import { TRANSIENT_ENTRY_PREFIX } from "./bundler-backend.ts";
|
|
13
13
|
import * as esbuildBackend from "./bundler-backend.node.ts";
|
|
14
14
|
|
|
@@ -94,3 +94,37 @@ export async function build(request: BackendBuild): Promise<string> {
|
|
|
94
94
|
rmSync(entryPath, { force: true });
|
|
95
95
|
}
|
|
96
96
|
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Bundle several entries with code splitting into `outdir`, and return the files written. Throws
|
|
100
|
+
* with the backend's diagnostics on failure.
|
|
101
|
+
*/
|
|
102
|
+
export async function buildSplit(request: BackendSplitBuild): Promise<string[]> {
|
|
103
|
+
if (forcedToEsbuild()) {
|
|
104
|
+
return esbuildBackend.buildSplit(request);
|
|
105
|
+
}
|
|
106
|
+
const config: BuildConfig = {
|
|
107
|
+
entrypoints: request.entries,
|
|
108
|
+
external: request.external,
|
|
109
|
+
format: "esm",
|
|
110
|
+
minify: request.minify,
|
|
111
|
+
naming: { chunk: "chunk-[hash].[ext]", entry: "[name].[ext]" },
|
|
112
|
+
outdir: request.outdir,
|
|
113
|
+
plugins: request.plugins,
|
|
114
|
+
splitting: true,
|
|
115
|
+
target: bunTarget(request.target),
|
|
116
|
+
throw: false,
|
|
117
|
+
};
|
|
118
|
+
if (request.conditions) {
|
|
119
|
+
config.conditions = request.conditions;
|
|
120
|
+
}
|
|
121
|
+
if (request.define) {
|
|
122
|
+
config.define = request.define;
|
|
123
|
+
}
|
|
124
|
+
const result = await Bun.build(config);
|
|
125
|
+
if (!result.success) {
|
|
126
|
+
const logs = result.logs.map(String).join("\n");
|
|
127
|
+
throw new Error(`Bun.build failed for ${request.entries.join(", ")}:\n${logs}`);
|
|
128
|
+
}
|
|
129
|
+
return result.outputs.map((output) => resolve(request.outdir, output.path));
|
|
130
|
+
}
|
|
@@ -3,9 +3,15 @@
|
|
|
3
3
|
* runtime that is not Bun bundles with it, and Bun does too under `JX_BUNDLER=esbuild`.
|
|
4
4
|
*/
|
|
5
5
|
import { createRequire } from "node:module";
|
|
6
|
-
import {
|
|
6
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { dirname, join } from "node:path";
|
|
7
8
|
import type { BuildOptions } from "esbuild";
|
|
8
|
-
import type {
|
|
9
|
+
import type {
|
|
10
|
+
BackendBuild,
|
|
11
|
+
BackendSplitBuild,
|
|
12
|
+
BundlePlugin,
|
|
13
|
+
BundleTargetName,
|
|
14
|
+
} from "./bundler-backend.ts";
|
|
9
15
|
|
|
10
16
|
/** Which bundler this backend runs. */
|
|
11
17
|
export function backendName(): "bun" | "esbuild" {
|
|
@@ -79,3 +85,37 @@ export async function build(request: BackendBuild): Promise<string> {
|
|
|
79
85
|
const result = await esbuild.build({ ...options, write: false });
|
|
80
86
|
return result.outputFiles[0]!.text;
|
|
81
87
|
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Bundle several entries with code splitting into `outdir`, and return the files written. Throws
|
|
91
|
+
* with esbuild's diagnostics on failure.
|
|
92
|
+
*/
|
|
93
|
+
export async function buildSplit(request: BackendSplitBuild): Promise<string[]> {
|
|
94
|
+
const esbuild = await import("esbuild");
|
|
95
|
+
const options: BuildOptions = {
|
|
96
|
+
bundle: true,
|
|
97
|
+
chunkNames: "chunk-[hash]",
|
|
98
|
+
entryNames: "[name]",
|
|
99
|
+
entryPoints: request.entries,
|
|
100
|
+
external: request.external,
|
|
101
|
+
format: "esm",
|
|
102
|
+
logLevel: "silent",
|
|
103
|
+
minify: request.minify,
|
|
104
|
+
outdir: request.outdir,
|
|
105
|
+
platform: esbuildPlatform(request.target),
|
|
106
|
+
plugins: request.plugins,
|
|
107
|
+
splitting: true,
|
|
108
|
+
};
|
|
109
|
+
if (request.conditions) {
|
|
110
|
+
options.conditions = request.conditions;
|
|
111
|
+
}
|
|
112
|
+
if (request.define) {
|
|
113
|
+
options.define = request.define;
|
|
114
|
+
}
|
|
115
|
+
const result = await esbuild.build({ ...options, write: false });
|
|
116
|
+
return result.outputFiles.map((file) => {
|
|
117
|
+
mkdirSync(dirname(file.path), { recursive: true });
|
|
118
|
+
writeFileSync(file.path, file.contents);
|
|
119
|
+
return file.path;
|
|
120
|
+
});
|
|
121
|
+
}
|
|
@@ -66,5 +66,17 @@ export interface BackendBuild {
|
|
|
66
66
|
plugins: BundlePlugin[];
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
+
/**
|
|
70
|
+
* Several entry files bundled in one call with code splitting: each entry becomes `<outdir>/<its
|
|
71
|
+
* base name>.js`, and a module two entries import becomes one shared `<outdir>/chunk-<hash>.js`
|
|
72
|
+
* that both import, so it is one instance on a page that loads both.
|
|
73
|
+
*/
|
|
74
|
+
export interface BackendSplitBuild extends Omit<BackendBuild, "entry"> {
|
|
75
|
+
/** Absolute paths of the entry modules. Their base names must differ. */
|
|
76
|
+
entries: string[];
|
|
77
|
+
/** Absolute path of the directory the output is written to. */
|
|
78
|
+
outdir: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
69
81
|
/** Basename prefix of the throwaway entry the Bun backend writes for a source entry. */
|
|
70
82
|
export const TRANSIENT_ENTRY_PREFIX = ".jx-entry-";
|
package/src/site/bundler.ts
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { rmSync, writeFileSync } from "node:fs";
|
|
16
|
+
import { builtinModules } from "node:module";
|
|
16
17
|
import { tmpdir } from "node:os";
|
|
17
18
|
import { basename, join, resolve } from "node:path";
|
|
18
19
|
import { isNpmSpecifier, NPM_SPECIFIER_PREFIX } from "@jxsuite/schema/asset-paths";
|
|
@@ -150,17 +151,37 @@ function hookPlugins(opts: BundleOptions): BundlePlugin[] {
|
|
|
150
151
|
return [{ name: "jx-bundle-hooks", setup }, ...plugins];
|
|
151
152
|
}
|
|
152
153
|
|
|
154
|
+
/**
|
|
155
|
+
* Node builtins written without the `node:` prefix (`tls`, `diagnostics_channel`, ...). A package
|
|
156
|
+
* may import either spelling — postgres 4's workerd entry reaches `tls` and `diagnostics_channel`
|
|
157
|
+
* through its shared `index.js` — and `nodejs_compat` serves both at runtime.
|
|
158
|
+
*
|
|
159
|
+
* A plugin rather than `external` entries: Bun's browser target substitutes its own polyfill for a
|
|
160
|
+
* bare `os` or `fs` even when listed external, so the import has to be rewritten to `node:<name>`.
|
|
161
|
+
*/
|
|
162
|
+
const bareNodeBuiltins: BundlePlugin = {
|
|
163
|
+
name: "jx-bare-node-builtins",
|
|
164
|
+
setup(build) {
|
|
165
|
+
const names = builtinModules.filter((name) => !name.startsWith("_") && !name.includes(":"));
|
|
166
|
+
const filter = new RegExp(
|
|
167
|
+
`^(${names.map((name) => name.replaceAll("/", String.raw`\/`)).join("|")})$`,
|
|
168
|
+
);
|
|
169
|
+
build.onResolve({ filter }, (args) => ({ external: true, path: `node:${args.path}` }));
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
|
|
153
173
|
/**
|
|
154
174
|
* Per-adapter bundle options for the generated site worker (WinterTC runtimes). Cloudflare resolves
|
|
155
|
-
* with workerd conditions and keeps `cloudflare:*`/`node:*` imports
|
|
156
|
-
* provides node builtins at runtime); node/bun bundle
|
|
157
|
-
* construction.
|
|
175
|
+
* with workerd conditions and keeps `cloudflare:*`/`node:*` imports (and bare node builtins,
|
|
176
|
+
* rewritten to `node:`) external (nodejs_compat provides node builtins at runtime); node/bun bundle
|
|
177
|
+
* platform-native with builtins external by construction.
|
|
158
178
|
*/
|
|
159
179
|
export function workerBundleOptions(adapter: string): BundleOptions {
|
|
160
180
|
if (adapter === "cloudflare-workers" || adapter === "cloudflare-pages") {
|
|
161
181
|
return {
|
|
162
182
|
conditions: ["workerd", "worker"],
|
|
163
183
|
external: ["cloudflare:*", "node:*"],
|
|
184
|
+
plugins: [bareNodeBuiltins],
|
|
164
185
|
target: "workerd",
|
|
165
186
|
};
|
|
166
187
|
}
|
|
@@ -237,6 +258,21 @@ export async function bundleEntry(request: BundleRequest, opts: BundleOptions):
|
|
|
237
258
|
writeFileSync(request.outfile, code, "utf8");
|
|
238
259
|
}
|
|
239
260
|
|
|
261
|
+
/**
|
|
262
|
+
* Bundle several entry modules in one call with code splitting, into `outdir`: each entry is
|
|
263
|
+
* written as `<its base name>.js`, and a module two or more entries import is written once, as a
|
|
264
|
+
* `chunk-<hash>.js` they all import. That is what makes such a module ONE instance on a page that
|
|
265
|
+
* loads two of the entries, where {@link bundleEntry} would give each entry its own copy and its
|
|
266
|
+
* own module state. Returns the files written. Throws with the backend's diagnostics on failure.
|
|
267
|
+
*/
|
|
268
|
+
export async function bundleEntries(
|
|
269
|
+
entryPaths: string[],
|
|
270
|
+
outdir: string,
|
|
271
|
+
opts: BundleOptions,
|
|
272
|
+
): Promise<string[]> {
|
|
273
|
+
return backend.buildSplit({ entries: entryPaths, outdir, ...backendOptions(opts) });
|
|
274
|
+
}
|
|
275
|
+
|
|
240
276
|
/**
|
|
241
277
|
* Bundle one entry module and return the code rather than writing it.
|
|
242
278
|
*
|
|
@@ -323,7 +359,7 @@ export async function bundleWorkerSource(
|
|
|
323
359
|
): Promise<void> {
|
|
324
360
|
const opts = workerBundleOptions(adapter);
|
|
325
361
|
if (plugins !== undefined) {
|
|
326
|
-
opts.plugins = plugins;
|
|
362
|
+
opts.plugins = [...(opts.plugins ?? []), ...plugins];
|
|
327
363
|
}
|
|
328
364
|
await bundleSource(source, { outfile, resolveDir: projectRoot }, opts);
|
|
329
365
|
}
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* External-class.ts — the classes state entries name, as a site build finds, loads and runs them
|
|
3
|
+
*
|
|
4
|
+
* A state entry whose `$prototype` is not a built-in names an external class (spec.md §12.3,
|
|
5
|
+
* compiler.md §3). This module is everything the build does with one, for both timings: where its
|
|
6
|
+
* `.class.json` is, which class that document means (its `$implementation`'s export, or the class
|
|
7
|
+
* generated from its schema, compiler.md §5.4), how an instance becomes a value, and the module a
|
|
8
|
+
* `timing: "client"` class ships as.
|
|
9
|
+
*
|
|
10
|
+
* @module external-class
|
|
11
|
+
* @docs extending/extensions/classes
|
|
12
|
+
* @docs framework/build
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { createHash } from "node:crypto";
|
|
16
|
+
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
17
|
+
import { createRequire } from "node:module";
|
|
18
|
+
import { tmpdir } from "node:os";
|
|
19
|
+
import { dirname, join, resolve } from "node:path";
|
|
20
|
+
import { pathToFileURL } from "node:url";
|
|
21
|
+
import { isFunction, isString } from "@jxsuite/schema/guards";
|
|
22
|
+
import { parseClassDef } from "@jxsuite/schema/parse";
|
|
23
|
+
import type { ExtensionRegistry } from "@jxsuite/schema/extension-registry";
|
|
24
|
+
import type {
|
|
25
|
+
JsonObject,
|
|
26
|
+
JsonValue,
|
|
27
|
+
JxClassDef,
|
|
28
|
+
JxDocumentValue,
|
|
29
|
+
JxPrototypeDef,
|
|
30
|
+
JxStateDefinition,
|
|
31
|
+
ProjectConfig,
|
|
32
|
+
} from "@jxsuite/schema/types";
|
|
33
|
+
import { compileClassJson } from "../targets/compile-class.ts";
|
|
34
|
+
import { implementationFile, importImplementation } from "./format-host.ts";
|
|
35
|
+
import type { ProjectSectionData } from "./project-sections.ts";
|
|
36
|
+
|
|
37
|
+
/** The route a document is being resolved for, as far as a class reads it. */
|
|
38
|
+
export interface ClassRoute {
|
|
39
|
+
sourcePath?: string;
|
|
40
|
+
_pathParams?: Record<string, string>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** `config._project`: the project config and root, plus every loaded section under its key. */
|
|
44
|
+
export interface ClassProjectContext {
|
|
45
|
+
config: ProjectConfig | null;
|
|
46
|
+
root: string;
|
|
47
|
+
[sectionKey: string]: ProjectSectionData | ProjectConfig | string | null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** `config._document`: the route being built and the document's whole state. */
|
|
51
|
+
export interface ClassDocumentContext {
|
|
52
|
+
route: ClassRoute;
|
|
53
|
+
state: Record<string, JxStateDefinition>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The config an external class is constructed with during a build: the entry's own non-reserved
|
|
58
|
+
* keys, plus the build host's `_project` and `_document` context.
|
|
59
|
+
*/
|
|
60
|
+
export type ExternalClassConfig = Record<
|
|
61
|
+
string,
|
|
62
|
+
JxDocumentValue | ClassProjectContext | ClassDocumentContext | undefined
|
|
63
|
+
>;
|
|
64
|
+
|
|
65
|
+
/** A class instance that computes its value: `resolve()` answers with the JSON to bake in. */
|
|
66
|
+
interface ResolvingInstance {
|
|
67
|
+
resolve: () => JsonValue | Promise<JsonValue>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** A class instance that holds its value: a `value` field, or an accessor of that name. */
|
|
71
|
+
interface ValueInstance {
|
|
72
|
+
value: JsonValue;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* What an external class constructs (spec.md §12.3): an instance that resolves its value, one that
|
|
77
|
+
* holds it as `value`, or one whose own fields ARE the value.
|
|
78
|
+
*/
|
|
79
|
+
export type ExternalClassInstance = ResolvingInstance | ValueInstance | JsonObject;
|
|
80
|
+
|
|
81
|
+
/** An external class, as its implementation module exports it or as its schema generates it. */
|
|
82
|
+
export type ExternalClassCtor = new (config: ExternalClassConfig) => ExternalClassInstance;
|
|
83
|
+
|
|
84
|
+
/** A state entry's class, found: its descriptor, where that is, and the export that is the class. */
|
|
85
|
+
export interface LocatedClass {
|
|
86
|
+
/** Absolute path of the `.class.json` descriptor. */
|
|
87
|
+
classJsonPath: string;
|
|
88
|
+
classDef: JxClassDef;
|
|
89
|
+
/** The export the class is read by: `$export`, else the descriptor's `title`, else the name. */
|
|
90
|
+
exportName: string;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Where a state entry's class is looked for. */
|
|
94
|
+
export interface ClassLookup {
|
|
95
|
+
/** The directory of the document that declares the entry; a relative `$src` resolves from it. */
|
|
96
|
+
docDir?: string | null | undefined;
|
|
97
|
+
projectRoot: string;
|
|
98
|
+
/** The document's `imports` map. */
|
|
99
|
+
imports?: Record<string, string> | undefined;
|
|
100
|
+
/** The project's extension registry, whose enabled manifest classes are found by name. */
|
|
101
|
+
registry?: ExtensionRegistry | undefined;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Find the class a state entry names. The descriptor is the entry's `$src`, else the document's
|
|
106
|
+
* `imports` entry for the name, else an enabled extension's manifest class of that name, in that
|
|
107
|
+
* order; `undefined` when none of the three names one.
|
|
108
|
+
*
|
|
109
|
+
* A relative descriptor path resolves against the declaring document's directory, and anything else
|
|
110
|
+
* as a package specifier from the project's own `node_modules`. A descriptor that is named but
|
|
111
|
+
* cannot be read throws, naming the path.
|
|
112
|
+
*
|
|
113
|
+
* @param {JxPrototypeDef} def
|
|
114
|
+
* @param {ClassLookup} where
|
|
115
|
+
* @returns {LocatedClass | undefined}
|
|
116
|
+
*/
|
|
117
|
+
export function locateClass(def: JxPrototypeDef, where: ClassLookup): LocatedClass | undefined {
|
|
118
|
+
const src =
|
|
119
|
+
def.$src ??
|
|
120
|
+
where.imports?.[def.$prototype] ??
|
|
121
|
+
where.registry?.byName(def.$prototype)?.classPath;
|
|
122
|
+
if (!src) {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
let classJsonPath: string;
|
|
127
|
+
if (src.startsWith("./") || src.startsWith("../")) {
|
|
128
|
+
classJsonPath = resolve(where.docDir ?? where.projectRoot, src);
|
|
129
|
+
} else {
|
|
130
|
+
// A bare specifier or an absolute path: resolved from the project root, walking node_modules.
|
|
131
|
+
const require = createRequire(resolve(where.projectRoot, "package.json"));
|
|
132
|
+
classJsonPath = require.resolve(src);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const classDef = parseClassDef(readFileSync(classJsonPath, "utf8"), classJsonPath);
|
|
136
|
+
return {
|
|
137
|
+
classDef,
|
|
138
|
+
classJsonPath,
|
|
139
|
+
exportName: def.$export ?? classDef.title ?? def.$prototype,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Refuse a self-contained class whose `extends` is a `$ref`. The class generated for it imports its
|
|
145
|
+
* base from the sibling module a direct compile of that document writes (compiler.md §5.2, §5.6),
|
|
146
|
+
* which a site build does not write.
|
|
147
|
+
*
|
|
148
|
+
* @param {LocatedClass} located
|
|
149
|
+
*/
|
|
150
|
+
function refuseDocumentBase(located: LocatedClass): void {
|
|
151
|
+
const base = located.classDef.extends;
|
|
152
|
+
if (base !== undefined && !isString(base)) {
|
|
153
|
+
throw new Error(
|
|
154
|
+
`${located.classJsonPath} has no $implementation and extends another class document ` +
|
|
155
|
+
`("${base.$ref}"), which a site build does not compile: give it an $implementation`,
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Generated classes already loaded by this process, by the hash of their module text. */
|
|
161
|
+
const generatedClasses = new Map<string, Promise<ExternalClassCtor>>();
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Load the class a self-contained descriptor generates: compile it to its ES class module
|
|
165
|
+
* (compiler.md §5.5), write that to a temporary file, import it, and remove the file.
|
|
166
|
+
*
|
|
167
|
+
* The module is named by a hash of its text and kept by that hash, so the same class is loaded once
|
|
168
|
+
* however many documents name it, and a descriptor edited between two builds in one process is a
|
|
169
|
+
* different module.
|
|
170
|
+
*
|
|
171
|
+
* @param {LocatedClass} located
|
|
172
|
+
* @returns {Promise<ExternalClassCtor>}
|
|
173
|
+
*/
|
|
174
|
+
function loadGeneratedClass(located: LocatedClass): Promise<ExternalClassCtor> {
|
|
175
|
+
refuseDocumentBase(located);
|
|
176
|
+
const source = compileClassJson(located.classDef);
|
|
177
|
+
const hash = createHash("sha256").update(source).digest("hex").slice(0, 16);
|
|
178
|
+
let loading = generatedClasses.get(hash);
|
|
179
|
+
if (loading === undefined) {
|
|
180
|
+
const dir = join(tmpdir(), `jx-class-${process.pid}`);
|
|
181
|
+
mkdirSync(dir, { recursive: true });
|
|
182
|
+
const file = join(dir, `${located.classDef.title}-${hash}.mjs`);
|
|
183
|
+
writeFileSync(file, source, "utf8");
|
|
184
|
+
/* SAFETY: the module is `compileClassJson`'s output, which ends `export default <Title>`: a
|
|
185
|
+
class whose constructor takes one config object and reads members off it. */
|
|
186
|
+
loading = (import(pathToFileURL(file).href) as Promise<{ default: ExternalClassCtor }>)
|
|
187
|
+
.then((mod) => mod.default)
|
|
188
|
+
.finally(() => {
|
|
189
|
+
rmSync(file, { force: true });
|
|
190
|
+
});
|
|
191
|
+
generatedClasses.set(hash, loading);
|
|
192
|
+
}
|
|
193
|
+
return loading;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Load a located class in the build host. With an `$implementation`, the module is imported and the
|
|
198
|
+
* class is its export of the located name, or that member of its default export; without one, the
|
|
199
|
+
* class is generated from the descriptor's schema (compiler.md §5.4).
|
|
200
|
+
*
|
|
201
|
+
* @param {LocatedClass} located
|
|
202
|
+
* @returns {Promise<ExternalClassCtor>}
|
|
203
|
+
*/
|
|
204
|
+
export async function loadClass(located: LocatedClass): Promise<ExternalClassCtor> {
|
|
205
|
+
const { classDef, classJsonPath, exportName } = located;
|
|
206
|
+
if (!classDef.$implementation) {
|
|
207
|
+
return loadGeneratedClass(located);
|
|
208
|
+
}
|
|
209
|
+
const mod = await importImplementation(resolve(dirname(classJsonPath), classDef.$implementation));
|
|
210
|
+
/* SAFETY: trust boundary, the external class contract (spec.md §12.3). The export a `.class.json`
|
|
211
|
+
names as its implementation is written as a class taking this config; that it is a function is
|
|
212
|
+
all that can be checked before `new`, which the guard below does, and its instance is read only
|
|
213
|
+
through the optional members `instantiateAndResolve` checks. */
|
|
214
|
+
const exported = (mod[exportName] ?? mod.default?.[exportName]) as
|
|
215
|
+
| ExternalClassCtor
|
|
216
|
+
| null
|
|
217
|
+
| undefined;
|
|
218
|
+
if (!isFunction(exported)) {
|
|
219
|
+
throw new Error(`Module ${classDef.$implementation} does not export "${exportName}"`);
|
|
220
|
+
}
|
|
221
|
+
return exported;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Whether a constructed instance computes its value through `resolve()`. */
|
|
225
|
+
function isResolvingInstance(instance: ExternalClassInstance): instance is ResolvingInstance {
|
|
226
|
+
return "resolve" in instance && isFunction(instance.resolve);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Whether a constructed instance holds its value as `value`, own or inherited. */
|
|
230
|
+
function isValueInstance(instance: ExternalClassInstance): instance is ValueInstance {
|
|
231
|
+
return "value" in instance;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Construct an external class and take its value, by the order spec.md §12.3 states: `resolve()`
|
|
236
|
+
* when the instance has one, else `value` when it has that, else the instance itself. The browser
|
|
237
|
+
* half of the same rule is `externalClassHelperSource()` (`shared.ts`).
|
|
238
|
+
*
|
|
239
|
+
* @param {ExternalClassCtor} Ctor
|
|
240
|
+
* @param {ExternalClassConfig} config
|
|
241
|
+
* @returns {Promise<{ value: JsonValue; instance: ExternalClassInstance }>}
|
|
242
|
+
*/
|
|
243
|
+
export async function instantiateAndResolve(
|
|
244
|
+
Ctor: ExternalClassCtor,
|
|
245
|
+
config: ExternalClassConfig,
|
|
246
|
+
): Promise<{ value: JsonValue; instance: ExternalClassInstance }> {
|
|
247
|
+
const instance = new Ctor(config);
|
|
248
|
+
if (isResolvingInstance(instance)) {
|
|
249
|
+
return { instance, value: await instance.resolve() };
|
|
250
|
+
}
|
|
251
|
+
if (isValueInstance(instance)) {
|
|
252
|
+
return { instance, value: instance.value };
|
|
253
|
+
}
|
|
254
|
+
return { instance, value: instance };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Whether a class descriptor reads the build host's context (`#/$context/…`): a content
|
|
259
|
+
* collection's types, a connector's connections. A browser cannot supply that, so such a class runs
|
|
260
|
+
* only during the build.
|
|
261
|
+
*
|
|
262
|
+
* @param {JxClassDef} classDef
|
|
263
|
+
* @returns {boolean}
|
|
264
|
+
*/
|
|
265
|
+
export function readsBuildContext(classDef: JxClassDef): boolean {
|
|
266
|
+
return JSON.stringify(classDef).includes('"#/$context/');
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* The entry module a `timing: "client"` class is bundled from (compiler.md §12): a module whose
|
|
271
|
+
* default export is the class. With an `$implementation` it re-exports that module's class, by the
|
|
272
|
+
* lookup {@link loadClass} makes; without one it is the class generated from the schema.
|
|
273
|
+
*
|
|
274
|
+
* @param {LocatedClass} located
|
|
275
|
+
* @returns {string}
|
|
276
|
+
*/
|
|
277
|
+
export function classEntrySource(located: LocatedClass): string {
|
|
278
|
+
const { classDef, classJsonPath, exportName } = located;
|
|
279
|
+
if (!classDef.$implementation) {
|
|
280
|
+
refuseDocumentBase(located);
|
|
281
|
+
return compileClassJson(classDef);
|
|
282
|
+
}
|
|
283
|
+
const file = implementationFile(resolve(dirname(classJsonPath), classDef.$implementation));
|
|
284
|
+
const name = JSON.stringify(exportName);
|
|
285
|
+
return [
|
|
286
|
+
`import * as m from ${JSON.stringify(file)};`,
|
|
287
|
+
`export default m[${name}] ?? m.default?.[${name}];`,
|
|
288
|
+
"",
|
|
289
|
+
].join("\n");
|
|
290
|
+
}
|
package/src/site/format-host.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* discovered through their jx-extension.json manifests; see specs/extensions.md.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
import { readFileSync } from "node:fs";
|
|
9
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
10
10
|
import { dirname, isAbsolute, resolve, sep } from "node:path";
|
|
11
11
|
import { pathToFileURL } from "node:url";
|
|
12
12
|
import { createRequire } from "node:module";
|
|
@@ -26,18 +26,14 @@ export type { ExtensionRegistry } from "@jxsuite/schema/extension-registry";
|
|
|
26
26
|
export type { FormatRegistry, FormatEntry } from "@jxsuite/schema/format-registry";
|
|
27
27
|
|
|
28
28
|
/**
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
* the package's `dist/` directory. Tries, in order: the literal path, src/ → dist/, that same file
|
|
33
|
-
* with its `.ts` extension read as `.js` (a descriptor that names its TypeScript source, whose
|
|
34
|
-
* built module is JavaScript), and .js → .ts.
|
|
29
|
+
* The files an `$implementation` path may mean, in the order they are tried: the literal path, its
|
|
30
|
+
* `src/` read as `dist/`, that built file with a `.ts` extension read as `.js`, and a `.js` read as
|
|
31
|
+
* the `.ts` beside it. See {@link importImplementation} for why each exists.
|
|
35
32
|
*
|
|
36
33
|
* @param {string} path - Absolute path to the implementation module
|
|
37
|
-
* @returns {
|
|
38
|
-
* `default`) are read by name
|
|
34
|
+
* @returns {string[]}
|
|
39
35
|
*/
|
|
40
|
-
export
|
|
36
|
+
export function implementationCandidates(path: string): string[] {
|
|
41
37
|
const candidates = [path];
|
|
42
38
|
const srcSeg = `${sep}src${sep}`;
|
|
43
39
|
const distSeg = `${sep}dist${sep}`;
|
|
@@ -51,6 +47,49 @@ export async function importImplementation(path: string): Promise<Implementation
|
|
|
51
47
|
if (path.endsWith(".js")) {
|
|
52
48
|
candidates.push(`${path.slice(0, -3)}.ts`);
|
|
53
49
|
}
|
|
50
|
+
return candidates;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The file an `$implementation` path names, for a bundler, which needs the file itself where
|
|
55
|
+
* {@link importImplementation} can simply try each import.
|
|
56
|
+
*
|
|
57
|
+
* The candidates are {@link implementationCandidates}', with the source beside the literal path
|
|
58
|
+
* ahead of a built copy: that is the file a Bun import of the literal path loads, so the class a
|
|
59
|
+
* build ran and the class it ships are one source, and a stale `dist/` beside a newer `src/` is not
|
|
60
|
+
* what reaches the browser. A published package has no `src/`, and its built module is found.
|
|
61
|
+
*
|
|
62
|
+
* @param {string} path - Absolute path to the implementation module
|
|
63
|
+
* @returns {string}
|
|
64
|
+
*/
|
|
65
|
+
export function implementationFile(path: string): string {
|
|
66
|
+
const candidates = implementationCandidates(path);
|
|
67
|
+
const beside = dirname(path);
|
|
68
|
+
const ordered = [
|
|
69
|
+
...candidates.filter((candidate) => dirname(candidate) === beside),
|
|
70
|
+
...candidates.filter((candidate) => dirname(candidate) !== beside),
|
|
71
|
+
];
|
|
72
|
+
const found = ordered.find((candidate) => existsSync(candidate));
|
|
73
|
+
if (found === undefined) {
|
|
74
|
+
throw new Error(`no module at ${path} (tried ${ordered.join(", ")})`);
|
|
75
|
+
}
|
|
76
|
+
return found;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Import a class $implementation module by absolute path, tolerating source-vs-built layouts. A
|
|
81
|
+
* `.class.json` typically declares `"$implementation": "./markdown.js"` next to its TypeScript
|
|
82
|
+
* source: under Bun the sibling `.ts` resolves directly, while under node the built module lives in
|
|
83
|
+
* the package's `dist/` directory. Tries, in order: the literal path, src/ → dist/, that same file
|
|
84
|
+
* with its `.ts` extension read as `.js` (a descriptor that names its TypeScript source, whose
|
|
85
|
+
* built module is JavaScript), and .js → .ts.
|
|
86
|
+
*
|
|
87
|
+
* @param {string} path - Absolute path to the implementation module
|
|
88
|
+
* @returns {Promise<ImplementationExport>} The module's namespace object, whose named exports (and
|
|
89
|
+
* `default`) are read by name
|
|
90
|
+
*/
|
|
91
|
+
export async function importImplementation(path: string): Promise<ImplementationExport> {
|
|
92
|
+
const candidates = implementationCandidates(path);
|
|
54
93
|
|
|
55
94
|
let lastError: unknown;
|
|
56
95
|
for (const candidate of candidates) {
|
|
@@ -32,8 +32,8 @@ export interface HeaderRuleSet {
|
|
|
32
32
|
|
|
33
33
|
/**
|
|
34
34
|
* The only content-addressed output the build produces. A variant's file name embeds an 8-character
|
|
35
|
-
* digest of the source bytes
|
|
36
|
-
* forever (RFC 8246).
|
|
35
|
+
* digest of the source bytes and the settings they were encoded with, so a changed image or a
|
|
36
|
+
* changed quality is a changed URL and the old one can be cached forever (RFC 8246).
|
|
37
37
|
*/
|
|
38
38
|
export const IMMUTABLE_PATTERN = "/images/_optimized/*";
|
|
39
39
|
|
|
@@ -241,9 +241,10 @@ export function writeHeaders(outDir: string, rules: readonly HeaderRule[]): numb
|
|
|
241
241
|
/**
|
|
242
242
|
* Write `dist/.nojekyll`.
|
|
243
243
|
*
|
|
244
|
-
* GitHub Pages runs Jekyll, which
|
|
245
|
-
*
|
|
246
|
-
*
|
|
244
|
+
* GitHub Pages runs Jekyll, which leaves every `_`-prefixed path out of the published site, at any
|
|
245
|
+
* depth. The one the build writes that a page needs is `images/_optimized/`, and a project may ship
|
|
246
|
+
* its own from `public/`. One empty file closes the whole class of "works locally, half-broken on
|
|
247
|
+
* Pages", so it is unconditional rather than an adapter option.
|
|
247
248
|
*/
|
|
248
249
|
export function writeNoJekyll(outDir: string): number {
|
|
249
250
|
const path = join(outDir, ".nojekyll");
|
package/src/site/image-cache.ts
CHANGED
|
@@ -3,12 +3,16 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Stores a manifest of previously processed images so that unchanged sources can skip re-encoding
|
|
5
5
|
* on subsequent builds. Cache lives in the npm global cache directory under jxsuite-images/ so that
|
|
6
|
-
* CI environments (e.g. Cloudflare Pages) can persist it via their npm cache layer.
|
|
6
|
+
* CI environments (e.g. Cloudflare Pages) can persist it via their npm cache layer. Each project
|
|
7
|
+
* has its own directory there, named for its directory and a digest of its absolute path: the name
|
|
8
|
+
* alone put two checkouts called `site` in one cache, where each one's pruning deleted the other's
|
|
9
|
+
* variants.
|
|
7
10
|
*/
|
|
8
11
|
|
|
9
12
|
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
10
13
|
import { basename, extname, resolve } from "node:path";
|
|
11
14
|
import { execSync } from "node:child_process";
|
|
15
|
+
import { createHash } from "node:crypto";
|
|
12
16
|
import { tmpdir } from "node:os";
|
|
13
17
|
import { configHash, contentHash } from "./image-optimizer.ts";
|
|
14
18
|
|
|
@@ -94,6 +98,11 @@ function npmCacheBase(): string | null {
|
|
|
94
98
|
* Cloudflare Pages) automatically persist optimized images across builds. Falls back to
|
|
95
99
|
* .cache/images inside the project root when npm is unavailable or does not answer in time.
|
|
96
100
|
*
|
|
101
|
+
* Inside npm's cache the directory is `<project directory name>-<digest>`, the digest being 8 hex
|
|
102
|
+
* characters of the project root's absolute path, so two projects with one directory name never
|
|
103
|
+
* share a cache (site-architecture.md §9.2.5). A directory under the bare name, written by an older
|
|
104
|
+
* compiler, is left in place and never read: it may belong to a project still on that compiler.
|
|
105
|
+
*
|
|
97
106
|
* Result is memoized — npm is asked at most once per process.
|
|
98
107
|
*
|
|
99
108
|
* @param {string} projectRoot
|
|
@@ -104,7 +113,9 @@ export function getImageCacheDir(projectRoot: string): string {
|
|
|
104
113
|
_npmCacheBase = npmCacheBase();
|
|
105
114
|
}
|
|
106
115
|
if (_npmCacheBase) {
|
|
107
|
-
|
|
116
|
+
const root = resolve(projectRoot);
|
|
117
|
+
const digest = createHash("md5").update(root).digest("hex").slice(0, 8);
|
|
118
|
+
return resolve(_npmCacheBase, "jxsuite-images", `${basename(root)}-${digest}`);
|
|
108
119
|
}
|
|
109
120
|
return resolve(projectRoot, ".cache/images");
|
|
110
121
|
}
|
|
@@ -214,7 +225,27 @@ function pruneStale(cache: CacheManifest, touched: Set<string>) {
|
|
|
214
225
|
// ─── Entry access ─────────────────────────────────────────────────────────────
|
|
215
226
|
|
|
216
227
|
/**
|
|
217
|
-
*
|
|
228
|
+
* The variant files of every entry this build resolved, each once: what the build copies into
|
|
229
|
+
* `dist/images/_optimized/`. A key that was looked up and never stored (its image failed) names no
|
|
230
|
+
* entry and contributes nothing.
|
|
231
|
+
*
|
|
232
|
+
* @param {CacheManifest} cache
|
|
233
|
+
* @returns {string[]} Absolute paths
|
|
234
|
+
*/
|
|
235
|
+
export function usedVariantPaths(cache: CacheManifest): string[] {
|
|
236
|
+
const paths = new Set<string>();
|
|
237
|
+
const entries = new Map<string, PersistedEntry>(Object.entries(cache.entries));
|
|
238
|
+
for (const key of cache.touched ?? []) {
|
|
239
|
+
for (const variant of entries.get(key)?.manifest.variants ?? []) {
|
|
240
|
+
paths.add(variant.absolutePath);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return [...paths];
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Look an entry up, and mark its key as resolved by this build. Whether the entry's variant files
|
|
248
|
+
* are still on disk is the caller's check (`resolveManifest` in image-transform.ts).
|
|
218
249
|
*
|
|
219
250
|
* @param {CacheManifest} cache
|
|
220
251
|
* @param {string} key
|