@jxsuite/compiler 8.6.0 → 8.7.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 +250 -215
- package/dist/compiler.js +145 -123
- package/package.json +11 -9
- package/src/cli.ts +12 -5
- package/src/shared.ts +249 -1
- package/src/site/bun-plugin.ts +61 -0
- package/src/site/bundler-backend.bun.ts +15 -3
- package/src/site/bundler-backend.node.ts +24 -1
- package/src/site/bundler-backend.ts +21 -4
- package/src/site/bundler.ts +28 -6
- package/src/site/component-set.ts +179 -0
- package/src/site/convert-command.ts +5 -27
- package/src/site/csp.ts +38 -8
- package/src/site/document-scripts.ts +231 -0
- package/src/site/format-command.ts +29 -0
- package/src/site/headers-emitter.ts +1 -1
- package/src/site/layout-resolver.ts +5 -4
- package/src/site/server-command.ts +63 -0
- package/src/site/service-worker.ts +19 -1
- package/src/site/site-build.ts +296 -84
- package/src/site/validate-command.ts +15 -6
- package/src/targets/compile-client.ts +9 -20
- package/src/targets/compile-element.ts +53 -73
- package/src/targets/compile-server.ts +49 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jxsuite/compiler",
|
|
3
|
-
"version": "8.
|
|
3
|
+
"version": "8.7.0",
|
|
4
4
|
"description": "Jx static HTML compiler, island detector, and site builder",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -37,7 +37,9 @@
|
|
|
37
37
|
"./site-loader": "./src/site/site-loader.ts",
|
|
38
38
|
"./types": "./src/types.ts",
|
|
39
39
|
"./db-push": "./src/site/db-push.ts",
|
|
40
|
-
"./
|
|
40
|
+
"./document-scripts": "./src/site/document-scripts.ts",
|
|
41
|
+
"./bundler": "./src/site/bundler.ts",
|
|
42
|
+
"./bun-plugin": "./src/site/bun-plugin.ts"
|
|
41
43
|
},
|
|
42
44
|
"publishConfig": {
|
|
43
45
|
"provenance": true
|
|
@@ -52,11 +54,11 @@
|
|
|
52
54
|
"upgrade": "bun update --latest && bun install"
|
|
53
55
|
},
|
|
54
56
|
"dependencies": {
|
|
55
|
-
"@jxsuite/create": "^1.8.
|
|
56
|
-
"@jxsuite/erase": "^0.
|
|
57
|
-
"@jxsuite/runtime": "^
|
|
58
|
-
"@jxsuite/schema": "^
|
|
59
|
-
"@jxsuite/site": "^2.
|
|
57
|
+
"@jxsuite/create": "^1.8.1",
|
|
58
|
+
"@jxsuite/erase": "^0.3.0",
|
|
59
|
+
"@jxsuite/runtime": "^7.0.0",
|
|
60
|
+
"@jxsuite/schema": "^6.0.0",
|
|
61
|
+
"@jxsuite/site": "^2.7.0",
|
|
60
62
|
"@vue/reactivity": "3.5.44",
|
|
61
63
|
"esbuild": "^0.28.2",
|
|
62
64
|
"lit-html": "^3.3.3",
|
|
@@ -64,8 +66,8 @@
|
|
|
64
66
|
},
|
|
65
67
|
"devDependencies": {
|
|
66
68
|
"@happy-dom/global-registrator": "^21.0.4",
|
|
67
|
-
"@jxsuite/connector": "^0.8.
|
|
68
|
-
"@jxsuite/parser": "^
|
|
69
|
+
"@jxsuite/connector": "^0.8.9",
|
|
70
|
+
"@jxsuite/parser": "^5.0.0",
|
|
69
71
|
"@jxsuite/test-support": "^0.0.0",
|
|
70
72
|
"@types/mdast": "^4.0.4"
|
|
71
73
|
}
|
package/src/cli.ts
CHANGED
|
@@ -30,6 +30,7 @@ Commands:
|
|
|
30
30
|
schema [root] Generate project.schema.json + document.schema.json from project.json#/extensions
|
|
31
31
|
validate [root] Validate the whole project: project.json, documents, classes, and fragments
|
|
32
32
|
convert <paths…> Move documents and the project file between .json and .jxn, repairing references
|
|
33
|
+
format [paths…] Format .jxn files and the code they hold (requires @jxsuite/server and Bun)
|
|
33
34
|
db push [root] Sync the data section's tables to their connections (additive-only)
|
|
34
35
|
|
|
35
36
|
Options:
|
|
@@ -41,15 +42,21 @@ Options:
|
|
|
41
42
|
--connection db push: restrict to one connection name
|
|
42
43
|
--strict validate: fail on an overlay or accessibility lint error, not only a schema error
|
|
43
44
|
--to <format> convert: jxn or json
|
|
44
|
-
--drop-comments convert: convert a .jxn file to .json even though it has comments
|
|
45
|
+
--drop-comments convert: convert a .jxn file to .json even though it has comments
|
|
46
|
+
--check format: write nothing, and fail when a file would change`);
|
|
45
47
|
process.exit(0);
|
|
46
48
|
}
|
|
47
49
|
|
|
48
|
-
//
|
|
49
|
-
if (command === "convert") {
|
|
50
|
+
// Their positionals are paths and not a project root, so they do not join the split below.
|
|
51
|
+
if (command === "convert" || command === "format") {
|
|
50
52
|
try {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
+
if (command === "convert") {
|
|
54
|
+
const { runConvert } = await import("./site/convert-command.ts");
|
|
55
|
+
runConvert(process.cwd(), args.slice(1));
|
|
56
|
+
} else {
|
|
57
|
+
const { runFormat } = await import("./site/format-command.ts");
|
|
58
|
+
runFormat(process.cwd(), args.slice(1));
|
|
59
|
+
}
|
|
53
60
|
} catch (error) {
|
|
54
61
|
console.error(errorMessage(error));
|
|
55
62
|
process.exit(1);
|
package/src/shared.ts
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
declaresBodyAndSrc,
|
|
12
12
|
handlerParamNames,
|
|
13
13
|
} from "@jxsuite/schema/function-role";
|
|
14
|
+
import type { FunctionRole } from "@jxsuite/schema/function-role";
|
|
14
15
|
import {
|
|
15
16
|
COLOR_SCHEME_ATTR,
|
|
16
17
|
COLOR_SCHEME_STORAGE_KEY,
|
|
@@ -29,7 +30,14 @@ import {
|
|
|
29
30
|
splitSelectorList,
|
|
30
31
|
} from "@jxsuite/runtime";
|
|
31
32
|
import { spliceNestingSelector } from "@jxsuite/runtime/css";
|
|
32
|
-
import {
|
|
33
|
+
import {
|
|
34
|
+
compileOperandSource,
|
|
35
|
+
evaluateExpression,
|
|
36
|
+
formulaScopeReads,
|
|
37
|
+
inheritableFormulas,
|
|
38
|
+
isMutating,
|
|
39
|
+
isPureNamedFormula,
|
|
40
|
+
} from "@jxsuite/runtime/expression";
|
|
33
41
|
import { runStatements } from "@jxsuite/runtime/statements";
|
|
34
42
|
import { buildSiteStyleCSS } from "@jxsuite/site/site-style";
|
|
35
43
|
import {
|
|
@@ -62,8 +70,10 @@ import type { JxScope } from "@jxsuite/runtime/types";
|
|
|
62
70
|
import type {
|
|
63
71
|
CemParameter,
|
|
64
72
|
JsonValue,
|
|
73
|
+
JxDocument,
|
|
65
74
|
JxDocumentValue,
|
|
66
75
|
JxElement,
|
|
76
|
+
JxExpressionDef,
|
|
67
77
|
JxMappedArray,
|
|
68
78
|
JxMutableNode,
|
|
69
79
|
JxPrototypeDef,
|
|
@@ -394,6 +404,117 @@ export function isClassJsonSrc(src?: unknown): src is string {
|
|
|
394
404
|
return typeof src === "string" && src.endsWith(".class.json");
|
|
395
405
|
}
|
|
396
406
|
|
|
407
|
+
/** White space between tokens of a body, as JSON serializes it: itself, or an escaped line end. */
|
|
408
|
+
const BODY_SPACE = String.raw`(?:\s|\\[nrt])*`;
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* `state` handed on whole in a body: assigned or destructured (`const { fmt } = state;`) or spread
|
|
412
|
+
* (`{ ...state }`). Whatever takes it can read any entry by a name the scan below never sees, so
|
|
413
|
+
* such a fragment counts as reading every key. What must follow it (punctuation, a line end, the
|
|
414
|
+
* end of the body) keeps prose out (`a = state of mind`), and `state.x` and `state[…]` are member
|
|
415
|
+
* reads, judged by name.
|
|
416
|
+
*/
|
|
417
|
+
const STATE_HANDED_ON = new RegExp(
|
|
418
|
+
String.raw`(?:=|\.\.\.)${BODY_SPACE}state[ \t]*(?:[;,)}\]"]|\\[nr])`,
|
|
419
|
+
);
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Whether a serialized document fragment still reads a given state key: as a `${state.key}`
|
|
423
|
+
* template, a `state.key` or `state?.key` inside a handler or computed body, a literal-keyed
|
|
424
|
+
* `state["key"]`, or a `#/state/key` $ref. A fragment that hands `state` on whole
|
|
425
|
+
* ({@link STATE_HANDED_ON}) reads every key.
|
|
426
|
+
*
|
|
427
|
+
* What it cannot see is a key that is computed (`state[name]`), and a read made by code outside the
|
|
428
|
+
* document (a `$src` module), which callers account for themselves.
|
|
429
|
+
*
|
|
430
|
+
* @param {string} haystack - JSON-serialized document fragment
|
|
431
|
+
* @param {string} key
|
|
432
|
+
* @returns {boolean}
|
|
433
|
+
*/
|
|
434
|
+
export function referencesStateKey(haystack: string, key: string): boolean {
|
|
435
|
+
const escaped = key.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
|
|
436
|
+
/* The name must end where the key does. `(?![\w$])` and not `\b`: a key may end in `$`, after
|
|
437
|
+
which `\b` sees no boundary before `(` and a read of `state.fmt$(…)` went unseen. */
|
|
438
|
+
const member = String.raw`\bstate${BODY_SPACE}\??\.${BODY_SPACE}${escaped}(?![\w$])`;
|
|
439
|
+
/* A quote inside a body is `\"` once the document is serialized; `'` and a backtick are bare. */
|
|
440
|
+
const quote = "(?:\\\\\"|['`])";
|
|
441
|
+
const bracket = String.raw`\bstate${BODY_SPACE}(?:\?\.)?\[${BODY_SPACE}${quote}${escaped}${quote}`;
|
|
442
|
+
const pointer = String.raw`#/state/${escaped}(?=["/])`;
|
|
443
|
+
return (
|
|
444
|
+
new RegExp(`${member}|${bracket}|${pointer}`).test(haystack) || STATE_HANDED_ON.test(haystack)
|
|
445
|
+
);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/* The predicate lives beside the expression engine, where the runtime reads it too: a component
|
|
449
|
+
inherits the same formulas in the interpreter as in a build (spec.md §13.4). */
|
|
450
|
+
export { isPureNamedFormula } from "@jxsuite/runtime/expression";
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* A component document as a project compiles it (spec.md §13.4): the project's closed pure named
|
|
454
|
+
* formulas the component reads, under its own `state`.
|
|
455
|
+
*
|
|
456
|
+
* Inheritance is from the PROJECT, never from the page an instance stands on, so a definition is
|
|
457
|
+
* the same document on every page and its one emitted module serves them all. Only what the
|
|
458
|
+
* component reads is merged, so a component that calls no project formula is byte-for-byte what it
|
|
459
|
+
* was, and each formula it does call is written once, into that component's own module:
|
|
460
|
+
*
|
|
461
|
+
* - A formula is read when the document names it ({@link referencesStateKey}), or when another merged
|
|
462
|
+
* formula's body calls it.
|
|
463
|
+
* - An entry the component declares is never replaced. That includes one a merged formula calls: the
|
|
464
|
+
* call resolves in the component's scope, so it reaches the component's entry.
|
|
465
|
+
* - While the component declares a `$src` Function every inheritable formula is merged, because that
|
|
466
|
+
* module's reads cannot be seen (the rule compiler.md §3 states for a page).
|
|
467
|
+
*
|
|
468
|
+
* @param {T} doc - The component definition
|
|
469
|
+
* @param {Record<string, JxStateDefinition> | null | undefined} projectState - `project.json`
|
|
470
|
+
* `state`
|
|
471
|
+
* @returns {T} `doc` itself when it inherits nothing
|
|
472
|
+
*/
|
|
473
|
+
export function inheritProjectFormulas<T extends JxElement | JxDocument>(
|
|
474
|
+
doc: T,
|
|
475
|
+
projectState: Record<string, JxStateDefinition> | null | undefined,
|
|
476
|
+
): T {
|
|
477
|
+
const available = inheritableFormulas(projectState);
|
|
478
|
+
const own = doc.state ?? {};
|
|
479
|
+
const names = Object.keys(available).filter((key) => !(key in own));
|
|
480
|
+
if (names.length === 0) {
|
|
481
|
+
return doc;
|
|
482
|
+
}
|
|
483
|
+
const text = JSON.stringify(doc);
|
|
484
|
+
const opaque = Object.values(own).some(
|
|
485
|
+
(entry) => isNonNullObject(entry) && !Array.isArray(entry) && isString(entry.$src),
|
|
486
|
+
);
|
|
487
|
+
const taken = new Set(names.filter((key) => opaque || referencesStateKey(text, key)));
|
|
488
|
+
// What a taken formula calls is taken with it. A Set visits members added while it is walked.
|
|
489
|
+
for (const key of taken) {
|
|
490
|
+
/* SAFETY: every member of `available` passed `isPureNamedFormula`, an expression entry. */
|
|
491
|
+
for (const read of formulaScopeReads(available[key] as JxExpressionDef)) {
|
|
492
|
+
if (!(read in own)) {
|
|
493
|
+
taken.add(read);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
if (taken.size === 0) {
|
|
498
|
+
return doc;
|
|
499
|
+
}
|
|
500
|
+
const inherited = Object.fromEntries(
|
|
501
|
+
names.filter((k) => taken.has(k)).map((k) => [k, available[k]!]),
|
|
502
|
+
);
|
|
503
|
+
return { ...doc, state: { ...inherited, ...own } };
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* A node as the text a read of its pure named formulas is looked for in: the whole node, without
|
|
508
|
+
* the formulas themselves. One formula calling another is not a read that reaches the browser
|
|
509
|
+
* unless something else reads the caller, and the caller is then found on its own.
|
|
510
|
+
*/
|
|
511
|
+
function withoutPureFormulas(def: JxElement | JxMutableNode): string {
|
|
512
|
+
const state = Object.fromEntries(
|
|
513
|
+
Object.entries(def.state ?? {}).filter(([, entry]) => !isPureNamedFormula(entry)),
|
|
514
|
+
);
|
|
515
|
+
return JSON.stringify({ ...def, state });
|
|
516
|
+
}
|
|
517
|
+
|
|
397
518
|
/**
|
|
398
519
|
* Determine whether a node (or any of its descendants) requires client-side JavaScript.
|
|
399
520
|
*
|
|
@@ -406,6 +527,8 @@ export function isDynamic(def: JxElement | JxMutableNode | string) {
|
|
|
406
527
|
}
|
|
407
528
|
|
|
408
529
|
if (def.state) {
|
|
530
|
+
/** Built on the first formula met, since most nodes with state declare none. */
|
|
531
|
+
let readers: string | undefined;
|
|
409
532
|
for (const [k, d] of Object.entries(def.state)) {
|
|
410
533
|
// Skip injected context (read-only, not reactive)
|
|
411
534
|
if (k === "$site" || k === "$page") {
|
|
@@ -418,6 +541,16 @@ export function isDynamic(def: JxElement | JxMutableNode | string) {
|
|
|
418
541
|
if (d.timing === "compiler") {
|
|
419
542
|
continue;
|
|
420
543
|
}
|
|
544
|
+
/* A pure named formula is a function, not state: it makes the node dynamic only when
|
|
545
|
+
something on the node still reads it (compiler.md §3). A page whose every call was
|
|
546
|
+
resolved at build time keeps no reader, so the declaration alone ships nothing. */
|
|
547
|
+
if (isPureNamedFormula(d)) {
|
|
548
|
+
readers ??= withoutPureFormulas(def);
|
|
549
|
+
if (referencesStateKey(readers, k)) {
|
|
550
|
+
return true;
|
|
551
|
+
}
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
421
554
|
if (d.$prototype) {
|
|
422
555
|
return true;
|
|
423
556
|
}
|
|
@@ -597,6 +730,19 @@ function runtimeOnlyKeysOf(scope: JxScope): Set<string> | undefined {
|
|
|
597
730
|
return (scope as { [RUNTIME_ONLY_KEYS]?: Set<string> })[RUNTIME_ONLY_KEYS];
|
|
598
731
|
}
|
|
599
732
|
|
|
733
|
+
/**
|
|
734
|
+
* Whether prerender holds a state entry to be runtime-only: its real value exists only after
|
|
735
|
+
* hydration, or some handler in the document writes it (see `buildInitialScope`). A scope built
|
|
736
|
+
* anywhere else has no marks and answers false.
|
|
737
|
+
*
|
|
738
|
+
* @param {JxScope} scope - The build-time scope, or a row scope whose prototype chain reaches it
|
|
739
|
+
* @param {string} key - A top-level state key
|
|
740
|
+
* @returns {boolean}
|
|
741
|
+
*/
|
|
742
|
+
export function isRuntimeOnlyStateKey(scope: JxScope, key: string): boolean {
|
|
743
|
+
return runtimeOnlyKeysOf(scope)?.has(key) ?? false;
|
|
744
|
+
}
|
|
745
|
+
|
|
600
746
|
/**
|
|
601
747
|
* `state.x = …`, `state.x += …`, `state.x++` — every form a string handler body can use to write a
|
|
602
748
|
* state entry. `===`/`!==`/`<=`/`>=` are excluded by the `(?!=)` guard and by the operator set.
|
|
@@ -742,6 +888,108 @@ export function refuseBodyWithSrc(
|
|
|
742
888
|
}
|
|
743
889
|
}
|
|
744
890
|
|
|
891
|
+
/** What a document's `$src` Function entries import, split by when the module loads. */
|
|
892
|
+
export interface SrcImports {
|
|
893
|
+
/** Statically imported modules → the `import { … }` clause members each one supplies. */
|
|
894
|
+
eager: Map<string, Set<string>>;
|
|
895
|
+
/** `$lazy` modules → the (export, local binding) pairs each one supplies. */
|
|
896
|
+
lazy: Map<string, { binding: string; exportName: string }[]>;
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/** The module text for a document's `$src` imports: static `import` lines, then lazy loaders. */
|
|
900
|
+
export interface SrcImportText {
|
|
901
|
+
imports: string[];
|
|
902
|
+
loaders: string[];
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
/**
|
|
906
|
+
* The `$src` modules a document's Function entries import (spec.md §5.3 4d), for every compiled
|
|
907
|
+
* target. A `$lazy` entry is split off from the eager imports, because its module loads on the
|
|
908
|
+
* first call rather than with the page. One reader of `$lazy` is the point: two emitters of one
|
|
909
|
+
* feature is how the client target came to ignore it and ship a static import.
|
|
910
|
+
*
|
|
911
|
+
* Refuses a lazy entry the document uses as a computed value: a computed reads its value
|
|
912
|
+
* synchronously and a lazy binding can only hand back a promise, so binding it would render
|
|
913
|
+
* `[object Promise]`.
|
|
914
|
+
*
|
|
915
|
+
* @param defs The document's `state`.
|
|
916
|
+
* @param roles The document's verdicts from `classifyFunctionEntries`.
|
|
917
|
+
*/
|
|
918
|
+
export function collectFunctionImports(
|
|
919
|
+
defs: Record<string, JxStateDefinition>,
|
|
920
|
+
roles: ReadonlyMap<string, FunctionRole>,
|
|
921
|
+
): SrcImports {
|
|
922
|
+
const imports: SrcImports = { eager: new Map(), lazy: new Map() };
|
|
923
|
+
for (const [key, def] of Object.entries(defs)) {
|
|
924
|
+
refuseBodyWithSrc(`state entry "${key}"`, def);
|
|
925
|
+
if (!isFunctionDef(def) || !def.$src) {
|
|
926
|
+
continue;
|
|
927
|
+
}
|
|
928
|
+
if (def.$lazy === true) {
|
|
929
|
+
if (roles.get(key) === "computed") {
|
|
930
|
+
throw new Error(
|
|
931
|
+
`"${key}" declares "$lazy": true but is used as a computed value, not called. ` +
|
|
932
|
+
`A lazily loaded function resolves to a promise; a computed must resolve now. ` +
|
|
933
|
+
`Remove "$lazy", or call ${key}() from a handler instead of binding its value.`,
|
|
934
|
+
);
|
|
935
|
+
}
|
|
936
|
+
let bindings = imports.lazy.get(def.$src);
|
|
937
|
+
if (!bindings) {
|
|
938
|
+
bindings = [];
|
|
939
|
+
imports.lazy.set(def.$src, bindings);
|
|
940
|
+
}
|
|
941
|
+
bindings.push({ binding: key, exportName: srcExportName(key, def) });
|
|
942
|
+
continue;
|
|
943
|
+
}
|
|
944
|
+
let names = imports.eager.get(def.$src);
|
|
945
|
+
if (!names) {
|
|
946
|
+
names = new Set();
|
|
947
|
+
imports.eager.set(def.$src, names);
|
|
948
|
+
}
|
|
949
|
+
names.add(srcImportBinding(key, def));
|
|
950
|
+
}
|
|
951
|
+
return imports;
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
/**
|
|
955
|
+
* The module text for {@link collectFunctionImports}: the static `import` lines, and the memoized
|
|
956
|
+
* dynamic loaders for `$lazy` entries. A static import is a download, a parse and an evaluate on
|
|
957
|
+
* every page that renders the component, whether or not anybody calls the function: jxsuite.com's
|
|
958
|
+
* search client is 70 kB of MiniSearch fetched by every visitor, most of whom never open search.
|
|
959
|
+
* The local binding keeps its name so every call site is unchanged; what changes is that it now
|
|
960
|
+
* returns a promise.
|
|
961
|
+
*
|
|
962
|
+
* @param imports What the document imports.
|
|
963
|
+
* @param rewriteSrc Maps a bundleable specifier (`npm:…`, `./relative`) to its `/assets/` bundle
|
|
964
|
+
* URL; the site build bundles them after all documents compile (spec.md §12).
|
|
965
|
+
*/
|
|
966
|
+
export function emitSrcImports(
|
|
967
|
+
imports: SrcImports,
|
|
968
|
+
rewriteSrc?: (specifier: string) => string,
|
|
969
|
+
): SrcImportText {
|
|
970
|
+
const importLines: string[] = [];
|
|
971
|
+
for (const [src, names] of imports.eager) {
|
|
972
|
+
importLines.push(
|
|
973
|
+
`import { ${[...names].join(", ")} } from '${rewriteSrc ? rewriteSrc(src) : src}';`,
|
|
974
|
+
);
|
|
975
|
+
}
|
|
976
|
+
const loaders: string[] = [];
|
|
977
|
+
let index = 0;
|
|
978
|
+
for (const [src, entries] of imports.lazy) {
|
|
979
|
+
const mod = `_jxLazy${index}`;
|
|
980
|
+
index += 1;
|
|
981
|
+
loaders.push(
|
|
982
|
+
`let ${mod};`,
|
|
983
|
+
`const ${mod}Load = () => (${mod} ??= import('${rewriteSrc ? rewriteSrc(src) : src}'));`,
|
|
984
|
+
...entries.map(
|
|
985
|
+
({ binding, exportName }) =>
|
|
986
|
+
`const ${binding} = (...args) => ${mod}Load().then((m) => m.${exportName}(...args));`,
|
|
987
|
+
),
|
|
988
|
+
);
|
|
989
|
+
}
|
|
990
|
+
return { imports: importLines, loaders };
|
|
991
|
+
}
|
|
992
|
+
|
|
745
993
|
/**
|
|
746
994
|
* @param {Record<string, JxStateDefinition>} [defs]
|
|
747
995
|
* @param {JxScope | null} [parentScope]
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lets Bun import a `.jxn` document as the module it carries (spec.md §23.2), so a document's
|
|
3
|
+
* functions can be unit tested where they are written.
|
|
4
|
+
*
|
|
5
|
+
* Importing this file registers the plugin. A project names it in `bunfig.toml`:
|
|
6
|
+
*
|
|
7
|
+
* [test];
|
|
8
|
+
* preload = ["@jxsuite/compiler/bun-plugin"];
|
|
9
|
+
*
|
|
10
|
+
* After that `import { bump } from "./components/counter.jxn"` is the document's client module,
|
|
11
|
+
* exactly as the build's bundler resolves the same import, and `./pages/index.jxn?server` is its
|
|
12
|
+
* server module. The query is a test's spelling only: nothing a browser runs can import a server
|
|
13
|
+
* module, and the build refuses one that tries.
|
|
14
|
+
*
|
|
15
|
+
* A module's own relative imports resolve from the document's directory, because the module is
|
|
16
|
+
* loaded at the document's path.
|
|
17
|
+
*
|
|
18
|
+
* @docs framework/concepts/functions
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { readFileSync } from "node:fs";
|
|
22
|
+
import type { BunPlugin } from "bun";
|
|
23
|
+
import type { ScriptSide } from "@jxsuite/schema/document-scripts";
|
|
24
|
+
import { parseNativeDocument } from "@jxsuite/schema/jxn";
|
|
25
|
+
|
|
26
|
+
/** What an import of a document's server module ends with. */
|
|
27
|
+
const SERVER_QUERY = "?server";
|
|
28
|
+
|
|
29
|
+
/** Matches an import of a `.jxn` document, with or without the server query. */
|
|
30
|
+
const JXN_MODULE = /\.jxn(?:\?server)?$/;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The text of one of a document's modules.
|
|
34
|
+
*
|
|
35
|
+
* @param modulePath The document's absolute path, ending in `?server` for its server module.
|
|
36
|
+
* @throws {Error} When the document carries no module for that side.
|
|
37
|
+
*/
|
|
38
|
+
export function documentModuleText(modulePath: string): string {
|
|
39
|
+
const side: ScriptSide = modulePath.endsWith(SERVER_QUERY) ? "server" : "client";
|
|
40
|
+
const documentPath = side === "server" ? modulePath.slice(0, -SERVER_QUERY.length) : modulePath;
|
|
41
|
+
const text = parseNativeDocument(readFileSync(documentPath, "utf8"), documentPath).$script?.[
|
|
42
|
+
side
|
|
43
|
+
];
|
|
44
|
+
if (text === undefined) {
|
|
45
|
+
throw new Error(`${documentPath} has no ${side} script, so there is nothing to import from it`);
|
|
46
|
+
}
|
|
47
|
+
return text;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The plugin itself, for a process that would rather register it than preload this file. */
|
|
51
|
+
export const documentScriptsPlugin: BunPlugin = {
|
|
52
|
+
name: "jx-document-scripts",
|
|
53
|
+
setup: (build) => {
|
|
54
|
+
build.onLoad({ filter: JXN_MODULE }, ({ path }) => ({
|
|
55
|
+
contents: documentModuleText(path),
|
|
56
|
+
loader: "ts",
|
|
57
|
+
}));
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
void Bun.plugin(documentScriptsPlugin);
|
|
@@ -38,8 +38,15 @@ function bunTarget(target: BundleTargetName): "browser" | "node" | "bun" {
|
|
|
38
38
|
return target;
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
-
/**
|
|
42
|
-
|
|
41
|
+
/**
|
|
42
|
+
* Bundle one file with `Bun.build` and return the output's text. With `contents`, the file is the
|
|
43
|
+
* text given and nothing is read from `entryPath`.
|
|
44
|
+
*/
|
|
45
|
+
async function buildFile(
|
|
46
|
+
entryPath: string,
|
|
47
|
+
request: BackendBuild,
|
|
48
|
+
contents?: string,
|
|
49
|
+
): Promise<string> {
|
|
43
50
|
const config: BuildConfig = {
|
|
44
51
|
entrypoints: [entryPath],
|
|
45
52
|
external: request.external,
|
|
@@ -55,6 +62,11 @@ async function buildFile(entryPath: string, request: BackendBuild): Promise<stri
|
|
|
55
62
|
if (request.define) {
|
|
56
63
|
config.define = request.define;
|
|
57
64
|
}
|
|
65
|
+
if (contents !== undefined) {
|
|
66
|
+
// An in-memory file: Bun never asks a plugin to resolve an entry point, so a module that is not
|
|
67
|
+
// On disk can only be an entry this way.
|
|
68
|
+
config.files = { [entryPath]: contents };
|
|
69
|
+
}
|
|
58
70
|
const result = await Bun.build(config);
|
|
59
71
|
if (!result.success || result.outputs.length === 0) {
|
|
60
72
|
const logs = result.logs.map(String).join("\n");
|
|
@@ -70,7 +82,7 @@ export async function build(request: BackendBuild): Promise<string> {
|
|
|
70
82
|
}
|
|
71
83
|
const { entry } = request;
|
|
72
84
|
if ("path" in entry) {
|
|
73
|
-
return buildFile(entry.path, request);
|
|
85
|
+
return buildFile(entry.path, request, entry.contents);
|
|
74
86
|
}
|
|
75
87
|
// Bun.build has no stdin input: write a transient entry in `resolveDir` so resolution matches
|
|
76
88
|
// The stdin/resolveDir behaviour, and always remove it.
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
import { createRequire } from "node:module";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import type { BuildOptions } from "esbuild";
|
|
8
|
-
import type { BackendBuild, BundleTargetName } from "./bundler-backend.ts";
|
|
8
|
+
import type { BackendBuild, BundlePlugin, BundleTargetName } from "./bundler-backend.ts";
|
|
9
9
|
|
|
10
10
|
/** Which bundler this backend runs. */
|
|
11
11
|
export function backendName(): "bun" | "esbuild" {
|
|
@@ -22,6 +22,26 @@ function esbuildPlatform(target: BundleTargetName): "browser" | "node" {
|
|
|
22
22
|
return target === "node" || target === "bun" ? "node" : "browser";
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
/** Escape a string for use as a literal inside a `RegExp`. */
|
|
26
|
+
function literalPattern(text: string): RegExp {
|
|
27
|
+
return new RegExp(`^${text.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`)}$`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* A plugin that makes `path` a module whose text is `contents`, whether or not a file is there.
|
|
32
|
+
* esbuild asks plugins to resolve an entry point, so answering for the one path is enough.
|
|
33
|
+
*/
|
|
34
|
+
function inMemoryEntry(path: string, contents: string): BundlePlugin {
|
|
35
|
+
const filter = literalPattern(path);
|
|
36
|
+
return {
|
|
37
|
+
name: "jx-in-memory-entry",
|
|
38
|
+
setup: (plugin) => {
|
|
39
|
+
plugin.onResolve({ filter }, () => ({ path }));
|
|
40
|
+
plugin.onLoad({ filter }, () => ({ contents, loader: "ts" }));
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
25
45
|
/** Bundle to one ESM module and return its text. Throws with esbuild's diagnostics on failure. */
|
|
26
46
|
export async function build(request: BackendBuild): Promise<string> {
|
|
27
47
|
// Dynamic import keeps esbuild (a native-binary dependency) off the load path until a bundle runs.
|
|
@@ -45,6 +65,9 @@ export async function build(request: BackendBuild): Promise<string> {
|
|
|
45
65
|
}
|
|
46
66
|
if ("path" in entry) {
|
|
47
67
|
options.entryPoints = [entry.path];
|
|
68
|
+
if (entry.contents !== undefined) {
|
|
69
|
+
options.plugins = [inMemoryEntry(entry.path, entry.contents), ...request.plugins];
|
|
70
|
+
}
|
|
48
71
|
} else {
|
|
49
72
|
options.stdin = {
|
|
50
73
|
contents: entry.source,
|
|
@@ -20,15 +20,28 @@ export type BundleTargetName = "browser" | "node" | "bun" | "workerd";
|
|
|
20
20
|
* backend.
|
|
21
21
|
*/
|
|
22
22
|
export interface PluginBuild {
|
|
23
|
+
/**
|
|
24
|
+
* `external: true` leaves the import in the output as written. A result without it names the file
|
|
25
|
+
* the import IS, which need not exist when an `onLoad` answers for it.
|
|
26
|
+
*/
|
|
23
27
|
onResolve: (
|
|
24
28
|
options: { filter: RegExp },
|
|
25
29
|
callback: (args: {
|
|
26
30
|
path: string;
|
|
27
31
|
importer: string;
|
|
28
|
-
}) => { path: string; external
|
|
32
|
+
}) => { path: string; external?: boolean } | undefined,
|
|
29
33
|
) => void;
|
|
30
34
|
/** An `undefined` result hands the file back to the backend's own loader. */
|
|
31
|
-
onLoad: (
|
|
35
|
+
onLoad: (
|
|
36
|
+
options: { filter: RegExp },
|
|
37
|
+
callback: (args: { path: string }) => LoadedModule | undefined | Promise<LoadedModule>,
|
|
38
|
+
) => void;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A module's text as a plugin supplies it, in place of a read from disk. Always TypeScript. */
|
|
42
|
+
export interface LoadedModule {
|
|
43
|
+
contents: string;
|
|
44
|
+
loader: "ts";
|
|
32
45
|
}
|
|
33
46
|
|
|
34
47
|
/** A plugin in the one shape both `Bun.build` and `esbuild.build` accept. */
|
|
@@ -39,8 +52,12 @@ export interface BundlePlugin {
|
|
|
39
52
|
|
|
40
53
|
/** One bundle, with every option already decided by `bundler.ts`. */
|
|
41
54
|
export interface BackendBuild {
|
|
42
|
-
/**
|
|
43
|
-
|
|
55
|
+
/**
|
|
56
|
+
* A file to start from; source text resolved as though it sat in `resolveDir`; or a TypeScript
|
|
57
|
+
* module AT `path`, which need not exist: its text is `contents`, and its relative imports
|
|
58
|
+
* resolve from `path`'s own directory, as a file there would.
|
|
59
|
+
*/
|
|
60
|
+
entry: { path: string; contents?: string } | { source: string; resolveDir: string };
|
|
44
61
|
target: BundleTargetName;
|
|
45
62
|
external: string[];
|
|
46
63
|
conditions?: string[];
|
package/src/site/bundler.ts
CHANGED
|
@@ -25,7 +25,7 @@ import type {
|
|
|
25
25
|
} from "./bundler-backend.ts";
|
|
26
26
|
import { TRANSIENT_ENTRY_PREFIX } from "./bundler-backend.ts";
|
|
27
27
|
|
|
28
|
-
export type { BundleTargetName } from "./bundler-backend.ts";
|
|
28
|
+
export type { BundlePlugin, BundleTargetName, PluginBuild } from "./bundler-backend.ts";
|
|
29
29
|
|
|
30
30
|
/** Import specifiers left external in client bundles — provided by the page importmap. */
|
|
31
31
|
export const CLIENT_EXTERNALS = ["@vue/reactivity", "lit-html"];
|
|
@@ -75,6 +75,12 @@ export interface BundleRequest {
|
|
|
75
75
|
entryPath: string;
|
|
76
76
|
/** Absolute path of the bundled output file. */
|
|
77
77
|
outfile: string;
|
|
78
|
+
/**
|
|
79
|
+
* The module's text, when it is not a file: a document's own script (spec.md §23.2), which lives
|
|
80
|
+
* inside the document. `entryPath` then only says where the module stands, so its relative
|
|
81
|
+
* imports resolve from that directory, and nothing is read from or written to it. TypeScript.
|
|
82
|
+
*/
|
|
83
|
+
contents?: string;
|
|
78
84
|
}
|
|
79
85
|
|
|
80
86
|
/**
|
|
@@ -102,6 +108,8 @@ export interface BundleOptions {
|
|
|
102
108
|
conditions?: string[];
|
|
103
109
|
/** Resolution hooks, applied before the bundler's own resolution. */
|
|
104
110
|
resolver?: BundleResolver;
|
|
111
|
+
/** Whole plugins, consulted after the hooks above. Written against {@link BundlePlugin}. */
|
|
112
|
+
plugins?: readonly BundlePlugin[];
|
|
105
113
|
/**
|
|
106
114
|
* Whether to minify the bundle.
|
|
107
115
|
*
|
|
@@ -124,8 +132,9 @@ export interface BundleOptions {
|
|
|
124
132
|
/** Wrap the hooks as the one-plugin array both backends take. */
|
|
125
133
|
function hookPlugins(opts: BundleOptions): BundlePlugin[] {
|
|
126
134
|
const { onFileLoaded, resolver } = opts;
|
|
135
|
+
const plugins = opts.plugins ?? [];
|
|
127
136
|
if (resolver === undefined && onFileLoaded === undefined) {
|
|
128
|
-
return [];
|
|
137
|
+
return [...plugins];
|
|
129
138
|
}
|
|
130
139
|
const setup = (build: PluginBuild): void => {
|
|
131
140
|
if (resolver !== undefined) {
|
|
@@ -138,7 +147,7 @@ function hookPlugins(opts: BundleOptions): BundlePlugin[] {
|
|
|
138
147
|
});
|
|
139
148
|
}
|
|
140
149
|
};
|
|
141
|
-
return [{ name: "jx-bundle-hooks", setup }];
|
|
150
|
+
return [{ name: "jx-bundle-hooks", setup }, ...plugins];
|
|
142
151
|
}
|
|
143
152
|
|
|
144
153
|
/**
|
|
@@ -220,7 +229,11 @@ function backendOptions(opts: BundleOptions): Omit<BackendBuild, "entry"> {
|
|
|
220
229
|
* diagnostics on failure.
|
|
221
230
|
*/
|
|
222
231
|
export async function bundleEntry(request: BundleRequest, opts: BundleOptions): Promise<void> {
|
|
223
|
-
const
|
|
232
|
+
const entry: BackendBuild["entry"] = { path: request.entryPath };
|
|
233
|
+
if (request.contents !== undefined) {
|
|
234
|
+
entry.contents = request.contents;
|
|
235
|
+
}
|
|
236
|
+
const code = await backend.build({ entry, ...backendOptions(opts) });
|
|
224
237
|
writeFileSync(request.outfile, code, "utf8");
|
|
225
238
|
}
|
|
226
239
|
|
|
@@ -301,7 +314,16 @@ export async function bundleSource(
|
|
|
301
314
|
*/
|
|
302
315
|
export async function bundleWorkerSource(
|
|
303
316
|
source: string,
|
|
304
|
-
{
|
|
317
|
+
{
|
|
318
|
+
projectRoot,
|
|
319
|
+
outfile,
|
|
320
|
+
adapter,
|
|
321
|
+
plugins,
|
|
322
|
+
}: { projectRoot: string; outfile: string; adapter: string; plugins?: readonly BundlePlugin[] },
|
|
305
323
|
): Promise<void> {
|
|
306
|
-
|
|
324
|
+
const opts = workerBundleOptions(adapter);
|
|
325
|
+
if (plugins !== undefined) {
|
|
326
|
+
opts.plugins = plugins;
|
|
327
|
+
}
|
|
328
|
+
await bundleSource(source, { outfile, resolveDir: projectRoot }, opts);
|
|
307
329
|
}
|