@jxsuite/server 9.3.0 → 9.4.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,93 @@
1
+ /**
2
+ * The browser modules a live preview serves under `/__jx_live__/`: the runtime every page imports,
3
+ * and the body eraser a page fetches when a function body is TypeScript.
4
+ *
5
+ * Neither is a file of this package. Each is a workspace package's source, bundled for the browser,
6
+ * so wherever the server runs it has to find that source and bundle it, or find the bytes already
7
+ * bundled. In a checkout and in an npm install the source resolves from this module, and that is
8
+ * the whole story. A desktop backend is a single bundled `index.js` with no workspace around it:
9
+ * the packages resolve from nowhere, both modules answered 500, and every page opened from the
10
+ * desktop app was blank, because the page's own script imports the runtime and nothing else draws
11
+ * it.
12
+ *
13
+ * So a host that bundles the server STAGES the two modules beside its bundle, in
14
+ * {@link PREVIEW_BUNDLES_DIR}, built by {@link buildPreviewBundle} at the same time and from the
15
+ * same source as the bundle itself, and {@link loadPreviewBundle} reads them from there first. The
16
+ * directory is found with `import.meta.dirname`, which a bundler leaves as the bundle's own
17
+ * directory (`@jxsuite/catalog` finds `catalog.json` the same way).
18
+ *
19
+ * @docs framework/build/dev-server
20
+ */
21
+
22
+ import { existsSync } from "node:fs";
23
+ import { readFile } from "node:fs/promises";
24
+ import { createRequire } from "node:module";
25
+ import { join } from "node:path";
26
+ import { bundleToString } from "@jxsuite/compiler/bundler";
27
+
28
+ /** The directory, beside a bundled server, that holds the staged browser modules. */
29
+ export const PREVIEW_BUNDLES_DIR = "preview-bundles";
30
+
31
+ /** Each browser module: the file it is staged as, the package it is built from, and how. */
32
+ export const PREVIEW_BUNDLES = {
33
+ eraser: { file: "eraser.js", minify: true, specifier: "@jxsuite/erase/browser" },
34
+ runtime: {
35
+ /* A package's own published bundle, preferred to building one when no staged copy exists. */
36
+ built: "@jxsuite/runtime/dist/runtime.js",
37
+ file: "runtime.js",
38
+ minify: false,
39
+ specifier: "@jxsuite/runtime",
40
+ },
41
+ } as const;
42
+
43
+ /** The name of one of {@link PREVIEW_BUNDLES}. */
44
+ export type PreviewBundleName = keyof typeof PREVIEW_BUNDLES;
45
+
46
+ /** Where this module looks for staged bundles: {@link PREVIEW_BUNDLES_DIR} beside itself. */
47
+ const STAGED_DIR = join(import.meta.dirname, PREVIEW_BUNDLES_DIR);
48
+
49
+ /**
50
+ * Bundle one browser module from its package's source.
51
+ *
52
+ * @param name Which module.
53
+ * @param from Where its package resolves from; this module by default.
54
+ */
55
+ export async function buildPreviewBundle(
56
+ name: PreviewBundleName,
57
+ from: string = import.meta.url,
58
+ ): Promise<string> {
59
+ const { minify, specifier } = PREVIEW_BUNDLES[name];
60
+ return bundleToString(createRequire(from).resolve(specifier), { minify, target: "browser" });
61
+ }
62
+
63
+ /**
64
+ * One browser module's bytes: the staged copy when a host staged one, then the package's own built
65
+ * file where it publishes one, then a bundle built here from source.
66
+ *
67
+ * @param name Which module.
68
+ * @param stagedDir Where staged copies live; {@link PREVIEW_BUNDLES_DIR} beside this module by
69
+ * default.
70
+ * @param from Where its package resolves from; this module by default.
71
+ */
72
+ export async function loadPreviewBundle(
73
+ name: PreviewBundleName,
74
+ stagedDir: string = STAGED_DIR,
75
+ from: string = import.meta.url,
76
+ ): Promise<string> {
77
+ const entry = PREVIEW_BUNDLES[name];
78
+ const staged = join(stagedDir, entry.file);
79
+ if (existsSync(staged)) {
80
+ return readFile(staged, "utf8");
81
+ }
82
+ if ("built" in entry) {
83
+ try {
84
+ const built = createRequire(from).resolve(entry.built);
85
+ if (existsSync(built)) {
86
+ return await readFile(built, "utf8");
87
+ }
88
+ } catch {
89
+ // No published dist on this install; fall through and build one.
90
+ }
91
+ }
92
+ return buildPreviewBundle(name, from);
93
+ }
@@ -28,7 +28,12 @@ import { resolve, sep } from "node:path";
28
28
  import { serve } from "#serve";
29
29
  import type { ServeServer, ServeSocket } from "./serve.ts";
30
30
  import { handleJxMounts } from "./jx-mounts.ts";
31
- import { handleResolve, handleServerFunction, projectAssetMounts } from "./resolve.ts";
31
+ import {
32
+ handleResolve,
33
+ handleServerFunction,
34
+ projectAssetMounts,
35
+ withProjectMediaType,
36
+ } from "./resolve.ts";
32
37
  import { handleAiApi } from "./ai-api.ts";
33
38
  import { handleImportApi } from "./import-api.ts";
34
39
  import { resolveNpmPath } from "./npm-path.ts";
@@ -401,7 +406,7 @@ export async function createProjectServer(
401
406
  }
402
407
  const fileRes = await serveProjectFile(normPath, root, await projectAssetMounts(root));
403
408
  if (fileRes) {
404
- return fileRes;
409
+ return withProjectMediaType(fileRes, root, normPath);
405
410
  }
406
411
 
407
412
  // 7. npm bare specifiers via node_modules (on-demand bundle, mirrors server.ts).
@@ -63,7 +63,7 @@ import type {
63
63
  import type { GitRunner } from "@jxsuite/protocol/git-scope";
64
64
  import { isJsonObject, isString } from "@jxsuite/schema/guards";
65
65
  import { parseJxn } from "@jxsuite/schema/jxn";
66
- import { toError } from "@jxsuite/schema/parse";
66
+ import { parseJson, toError } from "@jxsuite/schema/parse";
67
67
  import { PROJECT_FILE_NAMES, parseProjectFile } from "@jxsuite/schema/project-file";
68
68
  import type { JsonObject, JsonValue, ProjectConfig } from "@jxsuite/schema/types";
69
69
  import { createWatchIgnore } from "../watch-policy.ts";
@@ -753,8 +753,7 @@ export async function createProjectStateHost(
753
753
  let doc: JsonValue;
754
754
  try {
755
755
  if (extension === ".json") {
756
- // SAFETY: JSON.parse without a reviver yields a JSON value; its `any` says no more.
757
- doc = JSON.parse(text) as JsonValue;
756
+ doc = parseJson(text, path);
758
757
  } else if (extension === ".jxn") {
759
758
  const document = parseJxn(text);
760
759
  doc = isJsonObject(document) ? document : null;
@@ -12,6 +12,7 @@ import { readFile } from "node:fs/promises";
12
12
  import type { FormatRegistry, ValueEdit } from "@jxsuite/schema/format-registry";
13
13
  import { isJsonObject } from "@jxsuite/schema/guards";
14
14
  import { rewriteJson } from "@jxsuite/schema/json-layout";
15
+ import { parseJson } from "@jxsuite/schema/parse";
15
16
  import {
16
17
  classifyJxn,
17
18
  isJxnPath,
@@ -101,8 +102,10 @@ export async function parseDoc(
101
102
  ): Promise<LoadedDoc> {
102
103
  if (isJsonPath(fp)) {
103
104
  return {
104
- // SAFETY: JSON.parse without a reviver only ever yields a JSON value; its `any` says no more.
105
- doc: JSON.parse(raw) as JsonValue,
105
+ /* Any top-level value, since the walk covers data files too, read through the parse boundary
106
+ (schema.md §3.4, §3.5): a refusal lands in the caller's per-file catch, which leaves the file
107
+ unwritten, rather than a repeated key silently dropped on read and gone from disk. */
108
+ doc: parseJson(raw, fp),
106
109
  rewrite: null,
107
110
  // Over the text it replaces, so a rename changes the references and not the formatting.
108
111
  serialize: (doc) => Promise.resolve(rewriteJson(doc, raw)),
package/src/resolve.ts CHANGED
@@ -5,6 +5,8 @@ import { siteBasePath } from "@jxsuite/schema/asset-paths";
5
5
  import { dirname, isAbsolute, relative, resolve } from "node:path";
6
6
  import { errorMessage, parseClassDef } from "@jxsuite/schema/parse";
7
7
  import { isScriptSpecifier } from "@jxsuite/schema/document-scripts";
8
+ import { mediaTypeForPath } from "@jxsuite/schema/media-type";
9
+ import { isJxnPath } from "@jxsuite/schema/jxn";
8
10
  import { isFunction, isNonNullObject, isString } from "@jxsuite/schema/guards";
9
11
  import { readFileSync } from "node:fs";
10
12
  import { createRequire } from "node:module";
@@ -80,7 +82,7 @@ interface ProjectEntry {
80
82
  config: ProjectConfig;
81
83
  registry: ExtensionRegistry;
82
84
  mounts: AssetMount[];
83
- /** The full `_project` context, started by the first {@link loadProjectContext} and shared. */
85
+ /** The full `_project` context, started by the first {@link projectContext} and shared. */
84
86
  context?: Promise<ProjectContext> | undefined;
85
87
  }
86
88
 
@@ -238,7 +240,7 @@ const projectEntryCache = new Map<
238
240
  * @param {string} projectRoot
239
241
  * @returns {Promise<ProjectContext | null>} `{ config, root, ...sections }` or null
240
242
  */
241
- async function loadProjectContext(projectRoot: string): Promise<ProjectContext | null> {
243
+ export async function projectContext(projectRoot: string): Promise<ProjectContext | null> {
242
244
  const entry = await loadProjectEntry(projectRoot);
243
245
  if (!entry) {
244
246
  return null;
@@ -337,6 +339,44 @@ export async function projectSiteBase(projectRoot: string): Promise<string> {
337
339
  return siteBasePath(entry?.config.url);
338
340
  }
339
341
 
342
+ /**
343
+ * The `Content-Type` a server sends for a project file: the media type an enabled format declares
344
+ * for its extension, else the core correction table (specs/extensions.md §7).
345
+ *
346
+ * @param {string} projectRoot
347
+ * @param {string} path - A file path or name; only its extension is read
348
+ * @returns {Promise<string | null>} Null leaves the host's own answer alone
349
+ */
350
+ export async function projectMediaType(projectRoot: string, path: string): Promise<string | null> {
351
+ const entry = await loadProjectEntry(projectRoot);
352
+ return mediaTypeForPath(path, entry?.registry.formats);
353
+ }
354
+
355
+ /**
356
+ * Set `Content-Type` on a static response when {@link projectMediaType} answers.
357
+ *
358
+ * A `.jxn` file is left alone: its responder already serves it as the JSON a reader parses.
359
+ *
360
+ * @param {Response} res
361
+ * @param {string} projectRoot
362
+ * @param {string} path
363
+ * @returns {Promise<Response>} `res`
364
+ */
365
+ export async function withProjectMediaType(
366
+ res: Response,
367
+ projectRoot: string,
368
+ path: string,
369
+ ): Promise<Response> {
370
+ if (isJxnPath(path)) {
371
+ return res;
372
+ }
373
+ const type = await projectMediaType(projectRoot, path);
374
+ if (type !== null) {
375
+ res.headers.set("Content-Type", type);
376
+ }
377
+ return res;
378
+ }
379
+
340
380
  /**
341
381
  * Extension asset mounts for a project (specs/extensions.md §8.5) — the directories the dev server
342
382
  * serves at their site URLs, so content-relative images resolve exactly as they will once built.
@@ -419,7 +459,7 @@ export async function handleResolve(
419
459
 
420
460
  // Inject project context for classes that need it
421
461
  const projectRoot = activeProjectRoot || root;
422
- const projectCtx = await loadProjectContext(projectRoot);
462
+ const projectCtx = await projectContext(projectRoot);
423
463
  if (projectCtx) {
424
464
  config._project = projectCtx;
425
465
  }
package/src/server.ts CHANGED
@@ -27,6 +27,8 @@ import {
27
27
  handleResolve,
28
28
  handleServerFunction,
29
29
  projectAssetMounts,
30
+ projectMediaType,
31
+ withProjectMediaType,
30
32
  projectSiteBase,
31
33
  } from "./resolve.ts";
32
34
  import {
@@ -46,7 +48,6 @@ import { handleCodeApi } from "./code-api.ts";
46
48
  import { clearLivePreviewOverlay, setLivePreviewOverlay } from "./live-preview.ts";
47
49
  import { handleAiApi } from "./ai-api.ts";
48
50
  import { handleImportApi } from "./import-api.ts";
49
- import { mediaTypeForPath } from "@jxsuite/schema/media-type";
50
51
  import { isJxnPath } from "@jxsuite/schema/jxn";
51
52
  import { jxnAsJson } from "@jxsuite/site/serve";
52
53
  import { problem } from "./problem.ts";
@@ -178,12 +179,10 @@ export async function createDevServer(options: {
178
179
  // Are query-cache-busted per mount, the parent bundle is not).
179
180
  const NO_CACHE = { "Cache-Control": "no-cache" };
180
181
  /*
181
- * `Bun.file` already infers a type from the extension, and for almost everything it is right. The
182
- * exceptions are the two RFCs Jx has an opinion about, and `.jxn`, which Bun has never heard of:
183
- * `.md` comes back as bare `text/markdown`
184
- * with no `variant`, and `.yaml` comes back as `text/yaml`, the spelling RFC 9512 §5 asks
185
- * implementations to stop using. `mediaTypeForPath` answers null everywhere else, so the
186
- * inference stays in charge of the ordinary cases.
182
+ * The type a format the active project enables declares for the extension comes first
183
+ * (extensions.md §7). Then the two corrections Jx makes to `Bun.file`'s inference: `.md` comes
184
+ * back as bare `text/markdown` with no `variant`, and `.yaml` as `text/yaml`, the spelling RFC
185
+ * 9512 §5 asks implementations to stop using. Everything else keeps Bun's inference.
187
186
  */
188
187
  const fileResponse = async (file: ReturnType<typeof Bun.file>) => {
189
188
  if (file.name !== undefined && isJxnPath(file.name)) {
@@ -194,7 +193,7 @@ export async function createDevServer(options: {
194
193
  "Content-Type": type,
195
194
  }));
196
195
  }
197
- const corrected = file.name === undefined ? null : mediaTypeForPath(file.name);
196
+ const corrected = await projectMediaType(activeProjectRoot ?? absRoot, file.name ?? "");
198
197
  return new Response(file, {
199
198
  headers: corrected === null ? NO_CACHE : { ...NO_CACHE, "Content-Type": corrected },
200
199
  });
@@ -491,7 +490,11 @@ export async function createDevServer(options: {
491
490
  headers.set(name, value);
492
491
  }
493
492
  // The status too: a `.jxn` that does not parse answers 422 with its reason.
494
- return new Response(mountRes.body, { headers, status: mountRes.status });
493
+ return withProjectMediaType(
494
+ new Response(mountRes.body, { headers, status: mountRes.status }),
495
+ activeProjectRoot,
496
+ path,
497
+ );
495
498
  }
496
499
  }
497
500
 
@@ -32,6 +32,7 @@ import { join, resolve } from "node:path";
32
32
  import { isJsonObject, isString } from "@jxsuite/schema/guards";
33
33
 
34
34
  import { serveContained } from "./net-guard.ts";
35
+ import { withProjectMediaType } from "./resolve.ts";
35
36
  import { parseProjectSource } from "@jxsuite/schema/project-file";
36
37
  import { isSameStamp, projectFileStamp } from "@jxsuite/schema/project-file/node";
37
38
 
@@ -97,7 +98,8 @@ export async function serveSiteOutput(
97
98
 
98
99
  // A file (an asset, or a page under `trailingSlash: "never"`).
99
100
  if (existsSync(direct) && statSync(direct).isFile()) {
100
- return serveContained(direct, outDir);
101
+ const res = await serveContained(direct, outDir);
102
+ return res && withProjectMediaType(res, projectRoot, direct);
101
103
  }
102
104
  // A route: its directory's index.html, with or without the trailing slash the reader typed.
103
105
  const asIndex = join(direct, "index.html");