@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
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which components a site build compiles.
|
|
3
|
+
*
|
|
4
|
+
* Two rules meet here. Every file directly in `components/` is compiled whether or not anything
|
|
5
|
+
* names it, because a page may use `components/<tag>.json` undeclared (imports.md §1.4) and the
|
|
6
|
+
* build only learns which of those a page wrote by scanning its HTML for the tags it compiled. A
|
|
7
|
+
* component anywhere else (a subdirectory of `components/`, a `_`-prefixed file beside the page
|
|
8
|
+
* that uses it) reaches the build by being declared: a `{ "$ref" }` in the `$elements` of a page,
|
|
9
|
+
* of a layout wrapping it, of `project.json`, or of a component already in the set
|
|
10
|
+
* (site-architecture.md §10.3).
|
|
11
|
+
*
|
|
12
|
+
* The walk runs before any page is composed, over the documents as written, because a `$ref` is
|
|
13
|
+
* relative to the file that declares it and the merged page no longer says which file that was.
|
|
14
|
+
*
|
|
15
|
+
* @docs framework/build
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { existsSync, readdirSync } from "node:fs";
|
|
19
|
+
import { dirname, isAbsolute, relative, resolve } from "node:path";
|
|
20
|
+
import { isJsonObject, isString } from "@jxsuite/schema/guards";
|
|
21
|
+
import { errorMessage } from "@jxsuite/schema/parse";
|
|
22
|
+
import { projectFilePath } from "@jxsuite/schema/project-file/node";
|
|
23
|
+
import type { FormatRegistry } from "@jxsuite/schema/format-registry";
|
|
24
|
+
import type { JxDocument, ProjectConfig } from "@jxsuite/schema/types";
|
|
25
|
+
import { qualifiedDocument } from "./document-scripts.ts";
|
|
26
|
+
import { layoutChain } from "./layout-resolver.ts";
|
|
27
|
+
import { readPageDocument } from "./pages-discovery.ts";
|
|
28
|
+
|
|
29
|
+
/** One component a build compiles: where it was read from, the tag it defines, and its document. */
|
|
30
|
+
export interface SiteComponent {
|
|
31
|
+
/** Absolute path of the component's source file. */
|
|
32
|
+
path: string;
|
|
33
|
+
tagName: string;
|
|
34
|
+
doc: JxDocument;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** What {@link collectSiteComponents} reads. A dependent that adds a declaring root adds it here. */
|
|
38
|
+
export interface SiteComponentInput {
|
|
39
|
+
projectRoot: string;
|
|
40
|
+
projectConfig: ProjectConfig;
|
|
41
|
+
/** Absolute path of every route's source file. Repeats are read once. */
|
|
42
|
+
pageSources: readonly string[];
|
|
43
|
+
formatRegistry: FormatRegistry;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Who named a component: the declaring file (project-relative) and the entry as it wrote it. */
|
|
47
|
+
interface Declaration {
|
|
48
|
+
declarer: string;
|
|
49
|
+
ref: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The `{ "$ref" }` entries of a document's `$elements`. A bare string is an npm specifier. */
|
|
53
|
+
function refEntries(doc: { $elements?: unknown }): string[] {
|
|
54
|
+
const { $elements: entries } = doc;
|
|
55
|
+
if (!Array.isArray(entries)) {
|
|
56
|
+
return [];
|
|
57
|
+
}
|
|
58
|
+
const refs: string[] = [];
|
|
59
|
+
for (const entry of entries) {
|
|
60
|
+
if (isJsonObject(entry) && isString(entry.$ref) && entry.$ref !== "") {
|
|
61
|
+
refs.push(entry.$ref);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return refs;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The components a build of this project compiles, in compile order: the files directly in
|
|
69
|
+
* `components/` (sorted by name), then every declared component not already among them, each
|
|
70
|
+
* followed through its own `$elements`. Deduplicated by absolute path and unique by tag.
|
|
71
|
+
*
|
|
72
|
+
* A declared entry the build cannot compile is an error naming the declaring file, the entry and
|
|
73
|
+
* the path it resolved to; so are two files that declare one `tagName`, where the first keeps the
|
|
74
|
+
* tag. Nothing here throws: a page or layout that cannot be read is skipped, because compiling its
|
|
75
|
+
* route reports it with the route.
|
|
76
|
+
*/
|
|
77
|
+
export async function collectSiteComponents(
|
|
78
|
+
input: SiteComponentInput,
|
|
79
|
+
): Promise<{ components: SiteComponent[]; errors: string[] }> {
|
|
80
|
+
const { formatRegistry, pageSources, projectConfig, projectRoot } = input;
|
|
81
|
+
const components: SiteComponent[] = [];
|
|
82
|
+
const errors: string[] = [];
|
|
83
|
+
const visited = new Set<string>();
|
|
84
|
+
const pathByTag = new Map<string, string>();
|
|
85
|
+
const rel = (path: string) => relative(projectRoot, path).replaceAll("\\", "/");
|
|
86
|
+
|
|
87
|
+
const visit = async (path: string, from: Declaration | null): Promise<void> => {
|
|
88
|
+
if (visited.has(path)) {
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
const where = rel(path);
|
|
92
|
+
const named = from ? `${from.declarer}: $elements entry "${from.ref}" names` : "";
|
|
93
|
+
if (from) {
|
|
94
|
+
if (where.startsWith("..") || isAbsolute(where)) {
|
|
95
|
+
visited.add(path);
|
|
96
|
+
errors.push(`${named} ${where}, outside the project`);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
if (!existsSync(path)) {
|
|
100
|
+
visited.add(path);
|
|
101
|
+
errors.push(`${named} no file (${where})`);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
visited.add(path);
|
|
106
|
+
let doc: JxDocument;
|
|
107
|
+
try {
|
|
108
|
+
// Each `#client` and `#server` names this component from here on (spec.md §23.2).
|
|
109
|
+
doc = qualifiedDocument(await readPageDocument(path, formatRegistry), path, projectRoot);
|
|
110
|
+
} catch (error) {
|
|
111
|
+
errors.push(`Error compiling component ${where}: ${errorMessage(error)}`);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
const tagName = isString(doc.tagName) ? doc.tagName : "";
|
|
115
|
+
if (!tagName.includes("-")) {
|
|
116
|
+
errors.push(
|
|
117
|
+
from
|
|
118
|
+
? `${named} ${where}, which is not a component (no hyphenated tagName)`
|
|
119
|
+
: `Error compiling component ${where}: tagName "${tagName}" must contain a hyphen`,
|
|
120
|
+
);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
const holder = pathByTag.get(tagName);
|
|
124
|
+
if (holder !== undefined) {
|
|
125
|
+
errors.push(`${rel(holder)} and ${where} both declare tagName "${tagName}"; rename one`);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
pathByTag.set(tagName, path);
|
|
129
|
+
components.push({ doc, path, tagName });
|
|
130
|
+
await visitDeclared(doc, path);
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
/** Visit what one declaring document names, each `$ref` against that document's directory. */
|
|
134
|
+
const visitDeclared = async (
|
|
135
|
+
doc: { $elements?: unknown },
|
|
136
|
+
declarerPath: string,
|
|
137
|
+
baseDir = dirname(declarerPath),
|
|
138
|
+
): Promise<void> => {
|
|
139
|
+
for (const ref of refEntries(doc)) {
|
|
140
|
+
// oxlint-disable-next-line no-await-in-loop -- Compile order is declaration order.
|
|
141
|
+
await visit(resolve(baseDir, ref), { declarer: rel(declarerPath), ref });
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const componentsDir = resolve(projectRoot, "components");
|
|
146
|
+
if (existsSync(componentsDir)) {
|
|
147
|
+
const extensions = [".json", ...formatRegistry.documentExtensions("component")];
|
|
148
|
+
/* Sorted, because this order is the order of the sheets in every page's `<head>`, and readdir
|
|
149
|
+
has none of its own: on ext4 it follows a hash of the name, so the same project built to
|
|
150
|
+
different bytes on different machines. */
|
|
151
|
+
const seeds = readdirSync(componentsDir)
|
|
152
|
+
.filter((file) => extensions.some((ext) => file.endsWith(ext)))
|
|
153
|
+
.toSorted();
|
|
154
|
+
for (const file of seeds) {
|
|
155
|
+
// oxlint-disable-next-line no-await-in-loop -- Compile order is listing order.
|
|
156
|
+
await visit(resolve(componentsDir, file), null);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
await visitDeclared(projectConfig, projectFilePath(projectRoot), projectRoot);
|
|
161
|
+
|
|
162
|
+
for (const pagePath of new Set(pageSources)) {
|
|
163
|
+
try {
|
|
164
|
+
// oxlint-disable-next-line no-await-in-loop -- Compile order is route order.
|
|
165
|
+
const pageDoc = await readPageDocument(pagePath, formatRegistry);
|
|
166
|
+
const levels = layoutChain(pageDoc, projectConfig, projectRoot);
|
|
167
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
168
|
+
await visitDeclared(pageDoc, pagePath);
|
|
169
|
+
for (const level of levels) {
|
|
170
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
171
|
+
await visitDeclared(level.doc, level.path);
|
|
172
|
+
}
|
|
173
|
+
} catch {
|
|
174
|
+
// A page or layout that cannot be read is reported by its route's compile, with the route.
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return { components, errors };
|
|
179
|
+
}
|
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Convert command: `jx convert`
|
|
3
|
-
*
|
|
4
|
-
* refactor pass that repairs references ships as TypeScript this Node entry cannot load.
|
|
2
|
+
* Convert command: `jx convert` is the project's `@jxsuite/server/convert`, run under Bun. The
|
|
3
|
+
* refactor pass that repairs references is the server's.
|
|
5
4
|
*
|
|
6
5
|
* @module convert-command
|
|
7
6
|
*/
|
|
8
7
|
import { spawn } from "node:child_process";
|
|
9
8
|
import type { ChildProcess } from "node:child_process";
|
|
10
|
-
import { createRequire } from "node:module";
|
|
11
|
-
import { join } from "node:path";
|
|
12
9
|
import type { ProcessLike } from "./dev-command.ts";
|
|
10
|
+
import { resolveServerEntry, runServerCommand } from "./server-command.ts";
|
|
13
11
|
|
|
14
12
|
/**
|
|
15
13
|
* Resolve the project's converter.
|
|
@@ -18,14 +16,7 @@ import type { ProcessLike } from "./dev-command.ts";
|
|
|
18
16
|
* @throws {Error} When the server package is not installed.
|
|
19
17
|
*/
|
|
20
18
|
export function resolveConvertEntry(projectRoot: string): string {
|
|
21
|
-
|
|
22
|
-
return createRequire(join(projectRoot, "package.json")).resolve("@jxsuite/server/convert");
|
|
23
|
-
} catch {
|
|
24
|
-
throw new Error(
|
|
25
|
-
`@jxsuite/server is not installed in ${projectRoot}. ` +
|
|
26
|
-
`Add it to devDependencies (e.g. \`bun add -d @jxsuite/server\`) and retry.`,
|
|
27
|
-
);
|
|
28
|
-
}
|
|
19
|
+
return resolveServerEntry(projectRoot, "convert");
|
|
29
20
|
}
|
|
30
21
|
|
|
31
22
|
/**
|
|
@@ -42,18 +33,5 @@ export function runConvert(
|
|
|
42
33
|
spawnImpl: typeof spawn = spawn,
|
|
43
34
|
proc: ProcessLike = process,
|
|
44
35
|
): ChildProcess {
|
|
45
|
-
|
|
46
|
-
const child = spawnImpl("bun", [entry, "--root", projectRoot, ...argv], { stdio: "inherit" });
|
|
47
|
-
child.on("error", (error: NodeJS.ErrnoException) => {
|
|
48
|
-
console.error(
|
|
49
|
-
error.code === "ENOENT"
|
|
50
|
-
? "jx convert runs on Bun, which was not found on your PATH. Install it from https://bun.sh and retry."
|
|
51
|
-
: `Failed to start jx convert: ${error.message}`,
|
|
52
|
-
);
|
|
53
|
-
proc.exitCode = 1;
|
|
54
|
-
});
|
|
55
|
-
child.on("exit", (code) => {
|
|
56
|
-
proc.exitCode = code ?? 0;
|
|
57
|
-
});
|
|
58
|
-
return child;
|
|
36
|
+
return runServerCommand("convert", projectRoot, argv, spawnImpl, proc);
|
|
59
37
|
}
|
package/src/site/csp.ts
CHANGED
|
@@ -54,11 +54,22 @@ export function emptyCspSources(): CspSources {
|
|
|
54
54
|
/**
|
|
55
55
|
* Script `type` values the browser executes, and therefore the ones `script-src` governs.
|
|
56
56
|
*
|
|
57
|
-
* An empty or absent type is classic JavaScript.
|
|
58
|
-
* — is a _data block_: the browser never executes it, CSP never checks it, and hashing it
|
|
59
|
-
* a hash that authorizes nothing. Verified in Chrome against an enforced policy.
|
|
57
|
+
* An empty or absent type is classic JavaScript. Almost everything else — `application/ld+json`
|
|
58
|
+
* above all — is a _data block_: the browser never executes it, CSP never checks it, and hashing it
|
|
59
|
+
* would add a hash that authorizes nothing. Verified in Chrome against an enforced policy.
|
|
60
60
|
*/
|
|
61
|
-
const EXECUTABLE_TYPES = new Set([
|
|
61
|
+
const EXECUTABLE_TYPES = new Set([
|
|
62
|
+
"",
|
|
63
|
+
"module",
|
|
64
|
+
"importmap",
|
|
65
|
+
"text/javascript",
|
|
66
|
+
"module-shim",
|
|
67
|
+
/* Not executed, and governed all the same: an inline speculation rule set is refused under
|
|
68
|
+
`script-src` unless a hash, a nonce or `'inline-speculation-rules'` admits it, because a rule
|
|
69
|
+
set decides what the page fetches and prerenders. Unhashed, an author's rules were silently
|
|
70
|
+
dropped the moment the policy was switched on. */
|
|
71
|
+
"speculationrules",
|
|
72
|
+
]);
|
|
62
73
|
|
|
63
74
|
const SCRIPT_TAG = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
|
|
64
75
|
const LINK_TAG = /<link\b([^>]*)>/gi;
|
|
@@ -157,6 +168,21 @@ function srcsetUrls(srcset: string | undefined): string[] {
|
|
|
157
168
|
.filter(Boolean);
|
|
158
169
|
}
|
|
159
170
|
|
|
171
|
+
/** `build.headers.security.frameOptions`: a header value, or `false` for no framing rule at all. */
|
|
172
|
+
export type FrameOptions = NonNullable<HeadersConfig["security"]>["frameOptions"];
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* The `frame-ancestors` source each `frameOptions` setting means. `false` is the author saying the
|
|
176
|
+
* site may be framed by anyone, so the directive is left out rather than set to `'self'`, which
|
|
177
|
+
* would overrule them: where both are present a browser ignores `X-Frame-Options`.
|
|
178
|
+
*/
|
|
179
|
+
function frameAncestors(frameOptions: FrameOptions): string | false {
|
|
180
|
+
if (frameOptions === false) {
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
return frameOptions === "DENY" ? "'none'" : "'self'";
|
|
184
|
+
}
|
|
185
|
+
|
|
160
186
|
/** Normalize the config's three spellings into one shape, or null when CSP is off. */
|
|
161
187
|
export function normalizeCspConfig(security: HeadersConfig["security"]): CspConfig | null {
|
|
162
188
|
const csp = security?.csp;
|
|
@@ -187,7 +213,11 @@ export function normalizeCspConfig(security: HeadersConfig["security"]): CspConf
|
|
|
187
213
|
* @param {CspConfig} config
|
|
188
214
|
* @returns {CspHeaders}
|
|
189
215
|
*/
|
|
190
|
-
export function buildCspHeaders(
|
|
216
|
+
export function buildCspHeaders(
|
|
217
|
+
sources: CspSources,
|
|
218
|
+
config: CspConfig,
|
|
219
|
+
frameOptions: FrameOptions = "SAMEORIGIN",
|
|
220
|
+
): CspHeaders {
|
|
191
221
|
const list = (fixed: string[], origins: Set<string>) => [...fixed, ...origins].join(" ");
|
|
192
222
|
|
|
193
223
|
// The computed directives, in the same shape as the overrides `config.directives` merges in.
|
|
@@ -196,9 +226,9 @@ export function buildCspHeaders(sources: CspSources, config: CspConfig): CspHead
|
|
|
196
226
|
"default-src": "'self'",
|
|
197
227
|
"font-src": list(["'self'"], sources.fontOrigins),
|
|
198
228
|
"form-action": "'self'",
|
|
199
|
-
//
|
|
200
|
-
//
|
|
201
|
-
"frame-ancestors":
|
|
229
|
+
// Follows the `X-Frame-Options` emitted beside it; two headers disagreeing about framing is a
|
|
230
|
+
// Worse outcome than either answer, and `frame-ancestors` is the one a browser obeys.
|
|
231
|
+
"frame-ancestors": frameAncestors(frameOptions),
|
|
202
232
|
"frame-src": list(["'self'"], sources.frameOrigins),
|
|
203
233
|
"img-src": list(["'self'", "data:"], sources.imgOrigins),
|
|
204
234
|
"object-src": "'none'",
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A document's own modules, as the build sees them (spec.md §23.2, compiler.md §12).
|
|
3
|
+
*
|
|
4
|
+
* A document carries its client and server modules as text in `$script`. To a bundler that text has
|
|
5
|
+
* to be a module somewhere, because a module's relative imports are relative to where it stands. So
|
|
6
|
+
* each one is given a place beside its document, in a file that is never written:
|
|
7
|
+
*
|
|
8
|
+
* components/counter.jxn → components/counter.jxn.jx-client.ts
|
|
9
|
+
* components/counter.jxn.jx-server.ts
|
|
10
|
+
*
|
|
11
|
+
* One plugin, in the shape both bundler backends accept, answers for those places. It resolves a
|
|
12
|
+
* qualified specifier (`jx-script:components/counter.jxn#client`, which is how an entry names its
|
|
13
|
+
* own document's module once the document is read) and an import of another `.jxn` document (that
|
|
14
|
+
* document's client module), and it loads either from the document on disk. Nothing else in the
|
|
15
|
+
* build knows that a module can live inside a document.
|
|
16
|
+
*
|
|
17
|
+
* @docs framework/concepts/functions
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { readFileSync } from "node:fs";
|
|
21
|
+
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
|
|
22
|
+
import { EraseError, eraseModule } from "@jxsuite/erase";
|
|
23
|
+
import { parseScriptSpecifier, qualifyScripts } from "@jxsuite/schema/document-scripts";
|
|
24
|
+
import type { ScriptSide } from "@jxsuite/schema/document-scripts";
|
|
25
|
+
import { parseNativeDocument } from "@jxsuite/schema/jxn";
|
|
26
|
+
import type { JxDocument } from "@jxsuite/schema/types";
|
|
27
|
+
import type { BundlePlugin, LoadedModule } from "./bundler-backend.ts";
|
|
28
|
+
|
|
29
|
+
/** What a document's path gains to name the place its client module stands. */
|
|
30
|
+
export const CLIENT_MODULE_SUFFIX = ".jx-client.ts";
|
|
31
|
+
|
|
32
|
+
/** What a document's path gains to name the place its server module stands. */
|
|
33
|
+
export const SERVER_MODULE_SUFFIX = ".jx-server.ts";
|
|
34
|
+
|
|
35
|
+
/** Matches the place of either module. */
|
|
36
|
+
const MODULE_PATH = /\.jx-(?:client|server)\.ts$/;
|
|
37
|
+
|
|
38
|
+
/** Matches a qualified script specifier. */
|
|
39
|
+
const SCRIPT_SPECIFIER = /^jx-script:/;
|
|
40
|
+
|
|
41
|
+
/** Matches an import of a `.jxn` document. */
|
|
42
|
+
const JXN_IMPORT = /\.jxn$/;
|
|
43
|
+
|
|
44
|
+
/** One of a document's modules: where it stands, and its text. */
|
|
45
|
+
export interface DocumentModule {
|
|
46
|
+
/** Absolute path of the place the module stands. No file is there. */
|
|
47
|
+
path: string;
|
|
48
|
+
/** The module's TypeScript, as the document holds it. */
|
|
49
|
+
contents: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** What {@link documentScripts} hands a build. */
|
|
53
|
+
export interface DocumentScripts {
|
|
54
|
+
/**
|
|
55
|
+
* Resolves and loads documents' modules for a bundle a browser runs. Hand it to every such
|
|
56
|
+
* bundle, because any module may import a `.jxn` document. It refuses a server module, so no
|
|
57
|
+
* import, however it was spelled, can carry server text into a page.
|
|
58
|
+
*/
|
|
59
|
+
clientPlugin: BundlePlugin;
|
|
60
|
+
/** The same for the site worker's bundle, where a server module is what is being bundled. */
|
|
61
|
+
serverPlugin: BundlePlugin;
|
|
62
|
+
/**
|
|
63
|
+
* The module a qualified specifier names, to bundle as an entry.
|
|
64
|
+
*
|
|
65
|
+
* @throws {Error} When the specifier is not a qualified one, the document cannot be read, or it
|
|
66
|
+
* carries no module for that side.
|
|
67
|
+
*/
|
|
68
|
+
module: (specifier: string) => Promise<DocumentModule>;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Reads a document from an absolute path. A build passes one that knows its registered formats. */
|
|
72
|
+
export type DocumentReader = (path: string) => JxDocument | Promise<JxDocument>;
|
|
73
|
+
|
|
74
|
+
/** The place a document's module stands: the document's own path with the side's suffix. */
|
|
75
|
+
export function scriptModulePath(documentPath: string, side: ScriptSide): string {
|
|
76
|
+
return `${documentPath}${side === "client" ? CLIENT_MODULE_SUFFIX : SERVER_MODULE_SUFFIX}`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The document and side a module's place names, or `null` when the path is not such a place. */
|
|
80
|
+
export function scriptModuleOwner(
|
|
81
|
+
modulePath: string,
|
|
82
|
+
): { documentPath: string; side: ScriptSide } | null {
|
|
83
|
+
if (modulePath.endsWith(CLIENT_MODULE_SUFFIX)) {
|
|
84
|
+
return { documentPath: modulePath.slice(0, -CLIENT_MODULE_SUFFIX.length), side: "client" };
|
|
85
|
+
}
|
|
86
|
+
if (modulePath.endsWith(SERVER_MODULE_SUFFIX)) {
|
|
87
|
+
return { documentPath: modulePath.slice(0, -SERVER_MODULE_SUFFIX.length), side: "server" };
|
|
88
|
+
}
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* A document as the build holds it: every `$src: "#client"` and `$src: "#server"` in it naming this
|
|
94
|
+
* document by its project-relative path (spec.md §23.2).
|
|
95
|
+
*
|
|
96
|
+
* Applied wherever the build reads a document it may later merge with another, a page with its
|
|
97
|
+
* layout above all, because the merged document no longer says which file an entry was written in.
|
|
98
|
+
*
|
|
99
|
+
* @param doc The document as read.
|
|
100
|
+
* @param documentPath Absolute path it was read from.
|
|
101
|
+
* @param projectRoot The project root its specifiers are relative to.
|
|
102
|
+
*/
|
|
103
|
+
export function qualifiedDocument<T extends JxDocument>(
|
|
104
|
+
doc: T,
|
|
105
|
+
documentPath: string,
|
|
106
|
+
projectRoot: string,
|
|
107
|
+
): T {
|
|
108
|
+
return qualifyScripts(doc, projectRelative(documentPath, projectRoot));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** `path` from the project root, with `/` separators whatever the platform's own. */
|
|
112
|
+
function projectRelative(path: string, projectRoot: string): string {
|
|
113
|
+
return relative(projectRoot, path).split(sep).join("/");
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Read a `.json` or `.jxn` document, the two formats every build reads without an extension. */
|
|
117
|
+
function readNativeDocument(path: string): JxDocument {
|
|
118
|
+
return parseNativeDocument(readFileSync(path, "utf8"), path);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The build's view of every document's modules under one project root.
|
|
123
|
+
*
|
|
124
|
+
* A document is read once however many of its modules, or importers of them, a build bundles.
|
|
125
|
+
*
|
|
126
|
+
* @param projectRoot The project root qualified specifiers are relative to.
|
|
127
|
+
* @param read How a document is read. Defaults to the two native formats.
|
|
128
|
+
*/
|
|
129
|
+
export function documentScripts(
|
|
130
|
+
projectRoot: string,
|
|
131
|
+
read: DocumentReader = readNativeDocument,
|
|
132
|
+
): DocumentScripts {
|
|
133
|
+
const documents = new Map<string, Promise<JxDocument>>();
|
|
134
|
+
const named = (path: string) => projectRelative(path, projectRoot);
|
|
135
|
+
|
|
136
|
+
const documentAt = (path: string): Promise<JxDocument> => {
|
|
137
|
+
let pending = documents.get(path);
|
|
138
|
+
if (pending === undefined) {
|
|
139
|
+
pending = (async () => read(path))();
|
|
140
|
+
documents.set(path, pending);
|
|
141
|
+
}
|
|
142
|
+
return pending;
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const scriptOf = async (documentPath: string, side: ScriptSide): Promise<string> => {
|
|
146
|
+
let doc: JxDocument;
|
|
147
|
+
try {
|
|
148
|
+
doc = await documentAt(documentPath);
|
|
149
|
+
} catch (error) {
|
|
150
|
+
throw new Error(`Cannot read ${named(documentPath)} for its ${side} script`, {
|
|
151
|
+
cause: error,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
const text = doc.$script?.[side];
|
|
155
|
+
if (text === undefined) {
|
|
156
|
+
throw new Error(
|
|
157
|
+
`${named(documentPath)} has no ${side} script: nothing in it is $script.${side}, ` +
|
|
158
|
+
`but something names its ${side} module`,
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
/* What a browser's module loader would refuse, a build refuses (spec.md §23.2): the bundler
|
|
162
|
+
compiles an `enum` without a word, and the same script would then run built and stop a page
|
|
163
|
+
that interprets it. A server module is held to the one rule, so a script is one language. */
|
|
164
|
+
const [refused, ...rest] = eraseModule(text).problems;
|
|
165
|
+
if (refused !== undefined) {
|
|
166
|
+
throw new EraseError({ path: named(documentPath), pointer: `/$script/${side}` }, [
|
|
167
|
+
refused,
|
|
168
|
+
...rest,
|
|
169
|
+
]);
|
|
170
|
+
}
|
|
171
|
+
return text;
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
const placeOf = (specifier: string): { documentPath: string; side: ScriptSide } | null => {
|
|
175
|
+
const parsed = parseScriptSpecifier(specifier);
|
|
176
|
+
if (parsed === null) {
|
|
177
|
+
return null;
|
|
178
|
+
}
|
|
179
|
+
return { documentPath: resolve(projectRoot, parsed.path), side: parsed.side };
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
const pluginFor = (bundle: ScriptSide): BundlePlugin => ({
|
|
183
|
+
name: `jx-document-scripts-${bundle}`,
|
|
184
|
+
setup: (build) => {
|
|
185
|
+
build.onResolve({ filter: SCRIPT_SPECIFIER }, ({ path }) => {
|
|
186
|
+
const place = placeOf(path);
|
|
187
|
+
if (place === null) {
|
|
188
|
+
// Not a specifier this build wrote: the bundler reports it as the import it cannot find.
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (place.side === "server" && bundle === "client") {
|
|
192
|
+
throw new Error(
|
|
193
|
+
`${named(place.documentPath)}: its server script cannot be imported by code a ` +
|
|
194
|
+
`browser runs`,
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
return { path: scriptModulePath(place.documentPath, place.side) };
|
|
198
|
+
});
|
|
199
|
+
// Importing a document means importing what it exports, and only its client module exports
|
|
200
|
+
// To other modules: a server module is reached by a `timing: "server"` entry and nothing else.
|
|
201
|
+
build.onResolve({ filter: JXN_IMPORT }, ({ importer, path }) => {
|
|
202
|
+
if (isAbsolute(path)) {
|
|
203
|
+
return { path: scriptModulePath(path, "client") };
|
|
204
|
+
}
|
|
205
|
+
// A bare specifier that happens to end in `.jxn` is the bundler's own to resolve.
|
|
206
|
+
return path.startsWith("./") || path.startsWith("../")
|
|
207
|
+
? { path: scriptModulePath(resolve(dirname(importer), path), "client") }
|
|
208
|
+
: undefined;
|
|
209
|
+
});
|
|
210
|
+
build.onLoad({ filter: MODULE_PATH }, async ({ path }): Promise<LoadedModule> => {
|
|
211
|
+
/* SAFETY: the filter matched one of the two suffixes `scriptModuleOwner` reads, so the path
|
|
212
|
+
has an owner. */
|
|
213
|
+
const owner = scriptModuleOwner(path)!;
|
|
214
|
+
return { contents: await scriptOf(owner.documentPath, owner.side), loader: "ts" };
|
|
215
|
+
});
|
|
216
|
+
},
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
const module = async (specifier: string): Promise<DocumentModule> => {
|
|
220
|
+
const place = placeOf(specifier);
|
|
221
|
+
if (place === null) {
|
|
222
|
+
throw new Error(`"${specifier}" does not name a document's script`);
|
|
223
|
+
}
|
|
224
|
+
return {
|
|
225
|
+
contents: await scriptOf(place.documentPath, place.side),
|
|
226
|
+
path: scriptModulePath(place.documentPath, place.side),
|
|
227
|
+
};
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
return { clientPlugin: pluginFor("client"), module, serverPlugin: pluginFor("server") };
|
|
231
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Format command: `jx format` is the project's `@jxsuite/server/format`, run under Bun. The
|
|
3
|
+
* formatter it asks is the one Studio's code editor asks, and it is the server's dependency.
|
|
4
|
+
*
|
|
5
|
+
* @module format-command
|
|
6
|
+
* @docs framework/build/cli
|
|
7
|
+
*/
|
|
8
|
+
import { spawn } from "node:child_process";
|
|
9
|
+
import type { ChildProcess } from "node:child_process";
|
|
10
|
+
import type { ProcessLike } from "./dev-command.ts";
|
|
11
|
+
import { runServerCommand } from "./server-command.ts";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Spawn the formatter under Bun.
|
|
15
|
+
*
|
|
16
|
+
* @param projectRoot Absolute project root.
|
|
17
|
+
* @param argv The arguments after the command.
|
|
18
|
+
* @param spawnImpl Injectable for tests.
|
|
19
|
+
* @param proc Injectable for tests.
|
|
20
|
+
* @throws {Error} When the server package is not installed.
|
|
21
|
+
*/
|
|
22
|
+
export function runFormat(
|
|
23
|
+
projectRoot: string,
|
|
24
|
+
argv: readonly string[],
|
|
25
|
+
spawnImpl: typeof spawn = spawn,
|
|
26
|
+
proc: ProcessLike = process,
|
|
27
|
+
): ChildProcess {
|
|
28
|
+
return runServerCommand("format", projectRoot, argv, spawnImpl, proc);
|
|
29
|
+
}
|
|
@@ -125,7 +125,7 @@ export function buildHeaderRules(
|
|
|
125
125
|
"policy would block every one of them.",
|
|
126
126
|
);
|
|
127
127
|
} else {
|
|
128
|
-
Object.assign(wide, buildCspHeaders(cspSources, cspConfig));
|
|
128
|
+
Object.assign(wide, buildCspHeaders(cspSources, cspConfig, security.frameOptions));
|
|
129
129
|
}
|
|
130
130
|
}
|
|
131
131
|
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import { erasedDocument } from "../erased.ts";
|
|
12
|
+
import { qualifiedDocument } from "./document-scripts.ts";
|
|
12
13
|
import { existsSync, readFileSync } from "node:fs";
|
|
13
14
|
import { parseNativeDocument } from "@jxsuite/schema/jxn";
|
|
14
15
|
import { errorMessage } from "@jxsuite/schema/parse";
|
|
@@ -28,10 +29,10 @@ export function nodeLayoutLoader(projectRoot: string): (layoutRef: string) => Jx
|
|
|
28
29
|
throw new Error(`Layout not found: ${layoutRef} (resolved to ${layoutPath})`);
|
|
29
30
|
}
|
|
30
31
|
try {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
);
|
|
32
|
+
// Qualified here, as the layout is read, so its `#client` and the page's stay two modules
|
|
33
|
+
// Through the merge (spec.md §23.2).
|
|
34
|
+
const layout = parseNativeDocument(readFileSync(layoutPath, "utf8"), layoutPath);
|
|
35
|
+
return qualifiedDocument(erasedDocument(layout, layoutPath), layoutPath, projectRoot);
|
|
35
36
|
} catch (error) {
|
|
36
37
|
throw new Error(`Invalid layout at ${layoutPath}: ${errorMessage(error)}`, {
|
|
37
38
|
cause: error,
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A command the project's `@jxsuite/server` holds: `jx convert` and `jx format` resolve its entry
|
|
3
|
+
* from the project and run it under Bun, as `jx dev` does and for the same reasons. The compiler
|
|
4
|
+
* cannot depend on the server, and the server ships as TypeScript this Node entry cannot load.
|
|
5
|
+
*
|
|
6
|
+
* @module server-command
|
|
7
|
+
* @docs framework/build/cli
|
|
8
|
+
*/
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
10
|
+
import type { ChildProcess } from "node:child_process";
|
|
11
|
+
import { createRequire } from "node:module";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import type { ProcessLike } from "./dev-command.ts";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Resolve the entry of one of the project's server commands.
|
|
17
|
+
*
|
|
18
|
+
* @param projectRoot Absolute project root.
|
|
19
|
+
* @param name The command, which is the server's export of that name.
|
|
20
|
+
* @throws {Error} When the server package is not installed.
|
|
21
|
+
*/
|
|
22
|
+
export function resolveServerEntry(projectRoot: string, name: string): string {
|
|
23
|
+
try {
|
|
24
|
+
return createRequire(join(projectRoot, "package.json")).resolve(`@jxsuite/server/${name}`);
|
|
25
|
+
} catch {
|
|
26
|
+
throw new Error(
|
|
27
|
+
`@jxsuite/server is not installed in ${projectRoot}. ` +
|
|
28
|
+
`Add it to devDependencies (e.g. \`bun add -d @jxsuite/server\`) and retry.`,
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Spawn one of the project's server commands under Bun.
|
|
35
|
+
*
|
|
36
|
+
* @param name The command.
|
|
37
|
+
* @param projectRoot Absolute project root.
|
|
38
|
+
* @param argv The arguments after the command.
|
|
39
|
+
* @param spawnImpl Injectable for tests.
|
|
40
|
+
* @param proc Injectable for tests.
|
|
41
|
+
*/
|
|
42
|
+
export function runServerCommand(
|
|
43
|
+
name: string,
|
|
44
|
+
projectRoot: string,
|
|
45
|
+
argv: readonly string[],
|
|
46
|
+
spawnImpl: typeof spawn = spawn,
|
|
47
|
+
proc: ProcessLike = process,
|
|
48
|
+
): ChildProcess {
|
|
49
|
+
const entry = resolveServerEntry(projectRoot, name);
|
|
50
|
+
const child = spawnImpl("bun", [entry, "--root", projectRoot, ...argv], { stdio: "inherit" });
|
|
51
|
+
child.on("error", (error: NodeJS.ErrnoException) => {
|
|
52
|
+
console.error(
|
|
53
|
+
error.code === "ENOENT"
|
|
54
|
+
? `jx ${name} runs on Bun, which was not found on your PATH. Install it from https://bun.sh and retry.`
|
|
55
|
+
: `Failed to start jx ${name}: ${error.message}`,
|
|
56
|
+
);
|
|
57
|
+
proc.exitCode = 1;
|
|
58
|
+
});
|
|
59
|
+
child.on("exit", (code) => {
|
|
60
|
+
proc.exitCode = code ?? 0;
|
|
61
|
+
});
|
|
62
|
+
return child;
|
|
63
|
+
}
|