@jxsuite/compiler 8.5.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.
@@ -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,9 +9,13 @@
9
9
  * in every project, because deciding not to optimize an image says nothing about when to fetch it.
10
10
  * The **variant** pass (`images.optimize`) is the expensive half and is the one the master switch
11
11
  * turns off.
12
+ *
13
+ * A third, cheap pass runs on every image too: a picture whose own file names a **focal point**
14
+ * (studio.md §22.6, an IPTC Image Region read by `@jxsuite/site/xmp-packet`) is given it as its
15
+ * `object-position`, unless the author set one, so any `object-fit` crop keeps that point in view.
12
16
  */
13
17
 
14
- import { existsSync } from "node:fs";
18
+ import { existsSync, readFileSync, statSync } from "node:fs";
15
19
  import { basename, extname, resolve } from "node:path";
16
20
  import {
17
21
  buildSrcset,
@@ -25,6 +29,8 @@ import { imgLoadingAttrs } from "./img-loading.ts";
25
29
  import { resolveAssetUrl } from "@jxsuite/schema/asset-paths";
26
30
  import { isNodeObject, isNonNullObject, isString } from "@jxsuite/schema/guards";
27
31
  import { errorMessage } from "@jxsuite/schema/parse";
32
+ import { extractXmp, xmpFormatOf } from "@jxsuite/site/xmp-containers";
33
+ import { readMediaRecord } from "@jxsuite/site/xmp-packet";
28
34
 
29
35
  import type { AssetMount } from "@jxsuite/schema/asset-paths";
30
36
  import type { ImageConfig, ImageManifest, ImageVariant } from "./image-optimizer.ts";
@@ -234,6 +240,78 @@ function resolveImagePath(src: string, projectRoot: string, mounts?: readonly As
234
240
  return resolve(projectRoot, src);
235
241
  }
236
242
 
243
+ /** Focal points already read, keyed by the file's path, modified time and size. */
244
+ const focusCache = new Map<string, string | null>();
245
+
246
+ /** A fraction as a CSS percentage, to one decimal place. */
247
+ function percent(fraction: number): string {
248
+ return `${Math.round(fraction * 1000) / 10}%`;
249
+ }
250
+
251
+ /**
252
+ * The `object-position` a picture's own focal point asks for, or `null` when the file names none,
253
+ * cannot hold one, or cannot be read. A file whose metadata does not parse is a picture, not a
254
+ * broken build: it is drawn as it was before it had a focal point.
255
+ */
256
+ function focusPosition(absolute: string): string | null {
257
+ const format = xmpFormatOf(absolute);
258
+ if (format === null) {
259
+ return null;
260
+ }
261
+ let stamp: string;
262
+ try {
263
+ const stat = statSync(absolute);
264
+ stamp = `${absolute}|${stat.mtimeMs}|${stat.size}`;
265
+ } catch {
266
+ return null;
267
+ }
268
+ const cached = focusCache.get(stamp);
269
+ if (cached !== undefined) {
270
+ return cached;
271
+ }
272
+ let position: string | null = null;
273
+ try {
274
+ const bytes = new Uint8Array(readFileSync(absolute));
275
+ const { focus } = readMediaRecord(extractXmp(bytes, format));
276
+ position = focus === null ? null : `${percent(focus.x)} ${percent(focus.y)}`;
277
+ } catch {
278
+ position = null;
279
+ }
280
+ focusCache.set(stamp, position);
281
+ return position;
282
+ }
283
+
284
+ /**
285
+ * Give an `<img>` its file's focal point as `object-position`. The author's own `objectPosition`
286
+ * wins, a style written as something other than an object is left alone, and a bound, remote or
287
+ * inline `src` names no file to read.
288
+ */
289
+ function applyFocalPoint(
290
+ node: JxMutableNode | JxDocument,
291
+ src: JxAttributeValue | undefined,
292
+ projectRoot: string,
293
+ mounts: readonly AssetMount[],
294
+ ): void {
295
+ if (!isString(src) || src === "" || src.includes("${")) {
296
+ return;
297
+ }
298
+ if (EXTERNAL_PREFIXES.some((prefix) => src.startsWith(prefix))) {
299
+ return;
300
+ }
301
+ const { style } = node;
302
+ if (style !== undefined && !isNonNullObject(style)) {
303
+ return;
304
+ }
305
+ if (style?.objectPosition !== undefined) {
306
+ return;
307
+ }
308
+ const [path = ""] = src.split(/[?#]/);
309
+ const position = focusPosition(resolveImagePath(path, projectRoot, mounts));
310
+ if (position !== null) {
311
+ node.style = { ...style, objectPosition: position };
312
+ }
313
+ }
314
+
237
315
  /**
238
316
  * Transform image nodes in a Jx document tree.
239
317
  *
@@ -576,6 +654,7 @@ async function transformImgNode(
576
654
  attrs.src = node.src;
577
655
  delete node.src;
578
656
  }
657
+ applyFocalPoint(node, attrs.src, projectRoot, mounts);
579
658
 
580
659
  const variants = config.optimize
581
660
  ? await resolveVariants(
@@ -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
- return erasedDocument(
32
- parseNativeDocument(readFileSync(layoutPath, "utf8"), layoutPath),
33
- layoutPath,
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
+ }
@@ -39,6 +39,12 @@ export const SERVICE_WORKER_PATH = "sw.js";
39
39
  */
40
40
  export const CACHE_FIRST_PREFIX = "/images/_optimized/";
41
41
 
42
+ /**
43
+ * The subtree the site worker answers (compiler.md §6.4): sessions, table rows and server-function
44
+ * results. The emitted worker leaves every request under it alone.
45
+ */
46
+ export const DYNAMIC_PREFIX = "/_jx";
47
+
42
48
  export interface ServiceWorkerOutput {
43
49
  /** Path relative to `outDir`, or null when nothing should be emitted. */
44
50
  path: string | null;
@@ -152,6 +158,7 @@ export function buildServiceWorker(
152
158
  const cachedPrecache = precache.map((url) => withBase(base, url));
153
159
  const cacheFirst = withBase(base, CACHE_FIRST_PREFIX);
154
160
  const offlineFallback = fallback === undefined ? null : withBase(base, fallback);
161
+ const dynamic = `${withBase(base, DYNAMIC_PREFIX)}/`;
155
162
 
156
163
  const cache = `jx-${configId(config)}`;
157
164
  const source = `/*
@@ -162,6 +169,11 @@ const CACHE = ${JSON.stringify(cache)};
162
169
  const PRECACHE = ${JSON.stringify(cachedPrecache)};
163
170
  const CACHE_FIRST = ${JSON.stringify(cacheFirst)};
164
171
  const OFFLINE_FALLBACK = ${JSON.stringify(offlineFallback)};
172
+ const DYNAMIC = ${JSON.stringify(dynamic)};
173
+
174
+ // A response its server marked as one visitor's, or as not to be kept, is never written to a cache.
175
+ const storable = (res) =>
176
+ res.ok && !/\\b(?:no-store|private)\\b/i.test(res.headers.get("Cache-Control") ?? "");
165
177
 
166
178
  self.addEventListener("install", (event) => {
167
179
  // Take over as soon as possible: a half-updated pair of workers is harder to reason about than
@@ -202,6 +214,12 @@ self.addEventListener("fetch", (event) => {
202
214
  if (request.method !== "GET") return;
203
215
  const url = new URL(request.url);
204
216
  if (url.origin !== self.location.origin) return;
217
+ /*
218
+ * Sessions and application data. They are answered by the site worker for one visitor at one
219
+ * moment, so a cached copy is somebody's rows served after sign-out, or to the next person on the
220
+ * device. Not handled at all: the request goes to the network exactly as if no worker existed.
221
+ */
222
+ if (url.pathname.startsWith(DYNAMIC)) return;
205
223
 
206
224
  // Content-addressed output only: the filename embeds a digest, so a hit can never be stale.
207
225
  if (url.pathname.startsWith(CACHE_FIRST)) {
@@ -227,7 +245,7 @@ self.addEventListener("fetch", (event) => {
227
245
  (async () => {
228
246
  try {
229
247
  const res = await fetch(request);
230
- if (res.ok) {
248
+ if (storable(res)) {
231
249
  const copy = res.clone();
232
250
  caches.open(CACHE).then((c) => c.put(request, copy));
233
251
  }