@jxsuite/server 9.2.1 → 9.3.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jxsuite/server",
3
- "version": "9.2.1",
3
+ "version": "9.3.1",
4
4
  "description": "Jx development server with live reload, server-side proxy, and studio integration",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -34,6 +34,12 @@
34
34
  "./live-preview": "./src/live-preview.ts",
35
35
  "./site-preview": "./src/site-preview.ts",
36
36
  "./refactor": "./src/refactor/index.ts",
37
+ "./refactor/refs": "./src/refactor/refs.ts",
38
+ "./project-state/collections": "./src/project-state/collections.ts",
39
+ "./project-state/graph": "./src/project-state/graph.ts",
40
+ "./project-state/host": "./src/project-state/host.ts",
41
+ "./project-state/overlays": "./src/project-state/overlays.ts",
42
+ "./project-state/settle": "./src/project-state/settle.ts",
37
43
  "./resolve": "./src/resolve.ts",
38
44
  "./types": "./src/types.ts",
39
45
  "./jx-mounts": "./src/jx-mounts.ts",
@@ -56,30 +62,30 @@
56
62
  "upgrade": "bun update --latest && bun install"
57
63
  },
58
64
  "dependencies": {
59
- "@jxsuite/ai": "^0.45.1",
60
- "@jxsuite/catalog": "^0.1.18",
61
- "@jxsuite/collab": "^0.12.5",
62
- "@jxsuite/compiler": "^11.1.0",
63
- "@jxsuite/create": "^1.8.6",
64
- "@jxsuite/erase": "^0.3.5",
65
- "@jxsuite/import": "^0.44.8",
66
- "@jxsuite/protocol": "^6.6.1",
67
- "@jxsuite/runtime": "^9.0.1",
68
- "@jxsuite/schema": "^8.1.0",
69
- "@jxsuite/site": "^4.1.0",
70
- "@jxsuite/starters": "^5.1.0",
71
- "@npmcli/arborist": "^10.0.4",
65
+ "@jxsuite/ai": "^0.45.3",
66
+ "@jxsuite/catalog": "^0.1.20",
67
+ "@jxsuite/collab": "^0.13.1",
68
+ "@jxsuite/compiler": "^11.1.2",
69
+ "@jxsuite/create": "^1.8.8",
70
+ "@jxsuite/erase": "^0.3.7",
71
+ "@jxsuite/import": "^0.44.10",
72
+ "@jxsuite/protocol": "^7.0.0",
73
+ "@jxsuite/runtime": "^9.0.3",
74
+ "@jxsuite/schema": "^8.2.1",
75
+ "@jxsuite/site": "^4.1.2",
76
+ "@jxsuite/starters": "^5.2.1",
77
+ "@npmcli/arborist": "^10.0.5",
72
78
  "chokidar": "^6.0.0",
73
79
  "kysely": "^0.29.9",
74
80
  "npm-package-arg": "^14.0.0",
75
- "oxfmt": "^0.78.0",
81
+ "oxfmt": "^0.79.0",
76
82
  "ws": "^8.23.0",
77
83
  "zod": "^4.6.7"
78
84
  },
79
85
  "devDependencies": {
80
- "@jxsuite/auth": "^0.8.14",
81
- "@jxsuite/connector": "^0.8.14",
82
- "@jxsuite/parser": "^5.2.1",
86
+ "@jxsuite/auth": "^0.8.16",
87
+ "@jxsuite/connector": "^0.8.16",
88
+ "@jxsuite/parser": "^5.2.3",
83
89
  "@jxsuite/test-support": "^0.0.0",
84
90
  "@types/npm-package-arg": "^6.1.4",
85
91
  "@types/npmcli__arborist": "^6.3.3",
package/src/collab.ts CHANGED
@@ -2,19 +2,29 @@
2
2
  * Collab.ts — the dev server's realtime co-editing endpoint (`/__studio/collab`): the reference
3
3
  * implementation of the Jx collab wire contract, built on `@jxsuite/collab/room`.
4
4
  *
5
- * Rooms are keyed by server-root-relative path; a room's Y.Text source seeds from the file on disk.
6
- * Persistence is EXPLICIT: the shared source is written back to disk only on an explicit flush
7
- * (Cmd+S / Save) and, as a last-ditch safety, on graceful server shutdown. Unsaved collaborative
8
- * edits therefore live only in the room's in-memory Y.Doc until saved — non-collab consumers
9
- * (preview, live reload, plain editors) intentionally keep working off the last-saved file until
10
- * then. The host owns the room-level dirty signal broadcast to every peer; the embedder just tells
11
- * it a persist landed via `markPersisted`. Genuinely external file changes (not our own write-back
12
- * echo) bump the doc's epoch and reset subscribers, per the contract. No persistence beyond the
13
- * files themselves: this is deliberately a reference implementation.
5
+ * A room is addressed by server-root-relative path on the wire. Inside the active project, where
6
+ * the dev server runs a project state host (`project-state.md` §10.2, §11.3), it is keyed by the
7
+ * document's `DocId`: it follows the document across a rename the host observes, is closed when the
8
+ * document is removed, and saves through the host's conditional write with the hash it loaded or
9
+ * last saved as the base, so a save over a file that changed under it is refused and the refusal
10
+ * reaches every participant (`doc-conflict`). Outside it, a room is keyed by its path and saves
11
+ * unconditionally, as before. A room's Y.Text source seeds from the file on disk. Persistence is
12
+ * EXPLICIT: the shared source is written back to disk only on an explicit flush (Cmd+S / Save) and,
13
+ * as a last-ditch safety, on graceful server shutdown. Unsaved collaborative edits therefore live
14
+ * only in the room's in-memory Y.Doc until saved — non-collab consumers (preview, live reload,
15
+ * plain editors) intentionally keep working off the last-saved file until then. The host owns the
16
+ * room-level dirty signal broadcast to every peer; the embedder just tells it a persist landed via
17
+ * `markPersisted`. Genuinely external file changes (not our own write-back echo) bump the doc's
18
+ * epoch and reset subscribers, per the contract, except that a room inside the project holding
19
+ * unsaved edits keeps them and tells its participants of the conflict instead. No persistence
20
+ * beyond the files themselves: this is deliberately a reference implementation.
14
21
  */
15
22
 
16
- import { resolve } from "node:path";
23
+ import { randomUUID } from "node:crypto";
24
+ import { isAbsolute, relative, resolve, sep } from "node:path";
17
25
  import { readFile, writeFile } from "node:fs/promises";
26
+ import { contentHash, isContentHash } from "@jxsuite/protocol/project-state";
27
+ import type { ContentHash, ProjectEvent, ProjectSnapshot } from "@jxsuite/protocol/project-state";
18
28
  import { colorForKey } from "@jxsuite/collab/awareness-types";
19
29
  import { createCollabHost } from "@jxsuite/collab/room";
20
30
  import { isString } from "@jxsuite/schema/guards";
@@ -27,6 +37,8 @@ import { assertAccessible } from "./studio-api";
27
37
  import type { ServeServer, ServeSocket, ServeWebSocketHandler } from "./serve.ts";
28
38
  import type { HostConnection } from "@jxsuite/collab/room";
29
39
  import { problem } from "./problem.ts";
40
+ import type { ProjectEventsService } from "./project-events.ts";
41
+ import type { ProjectStateHost } from "./project-state/host.ts";
30
42
 
31
43
  const EMPTY_ROOM_GRACE_MS = 30_000;
32
44
 
@@ -81,13 +93,35 @@ export interface CollabRegistry {
81
93
  stop: () => Promise<void>;
82
94
  }
83
95
 
96
+ /** A room inside the project the host serves: where its document is, and the bytes it holds. */
97
+ interface HostedRoom {
98
+ /** The document's absolute path now; a rename the host observes moves it. */
99
+ abs: string;
100
+ /** The project root of the host the room saves through. */
101
+ root: string;
102
+ /** The hash of the file the room loaded or last saved, the base of its next save (§5). */
103
+ base: ContentHash | null;
104
+ }
105
+
84
106
  export function createCollabRegistry(opts: {
85
107
  absRoot: string;
86
108
  activeProjectRoot: () => string | null;
109
+ /** The project state service; without it every room is keyed by path and saves unconditionally. */
110
+ projectEvents?: ProjectEventsService;
87
111
  }): CollabRegistry {
88
- const { absRoot } = opts;
112
+ const { absRoot, projectEvents } = opts;
89
113
  let connectionCounter = 0;
90
114
  let stopped = false;
115
+ /** Rooms keyed by document, by key. */
116
+ const hosted = new Map<string, HostedRoom>();
117
+ /** Rooms keyed by their path (outside the project the host serves) that have loaded. */
118
+ const plain = new Set<string>();
119
+ /** Each room's save in flight, so two saves of one room run one after the other. */
120
+ const persisting = new Map<string, Promise<void>>();
121
+ /** The key of the document at each absolute path. */
122
+ const keyAt = new Map<string, string>();
123
+ /** The write ids of saves in flight, whose events are the room's own. */
124
+ const ownWrites = new Set<string>();
91
125
 
92
126
  const destroyTimers = new Map<string, ReturnType<typeof setTimeout>>();
93
127
  /** Paths with unsaved edits (source changed since the last persist) — the shutdown worklist. */
@@ -108,11 +142,134 @@ export function createCollabRegistry(opts: {
108
142
  return rel.replaceAll("\\", "/");
109
143
  };
110
144
 
111
- const persist = async (path: string): Promise<void> => {
112
- const source = host.sourceOf(path);
113
- if (source === null) {
145
+ /** The project a path is inside, when the service serves it; `null` for any other path. */
146
+ const coverage = (abs: string): string | null => {
147
+ const root = projectEvents?.root ?? null;
148
+ if (root === null) {
149
+ return null;
150
+ }
151
+ const inside = relative(root, abs);
152
+ return inside === "" || inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside)
153
+ ? null
154
+ : root;
155
+ };
156
+
157
+ /**
158
+ * The room a path names (`project-state.md` §11.3): the document's, inside the active project, so
159
+ * every path that names it shares one room; the path itself anywhere else. Registers nothing: a
160
+ * room is recorded when it loads ({@link load}), so a path that is only asked about, or a room
161
+ * that never loads, leaves nothing behind. The one thing it records is where a live room's
162
+ * document is now, when the host has indexed a move the room has not been told of yet.
163
+ */
164
+ const keyOf = (path: string): string => {
165
+ const abs = resolve(absRoot, path);
166
+ const known = keyAt.get(abs);
167
+ if (known !== undefined) {
168
+ return known;
169
+ }
170
+ const root = coverage(abs);
171
+ if (root === null) {
172
+ return path;
173
+ }
174
+ const running = projectEvents?.host ?? null;
175
+ const docId =
176
+ running !== null && running.root === root
177
+ ? running.docIdAt(relative(root, abs).replaceAll("\\", "/"))
178
+ : null;
179
+ if (docId === null) {
180
+ return `path:${abs}`;
181
+ }
182
+ const key = `doc:${docId}`;
183
+ const room = hosted.get(key);
184
+ if (room !== undefined) {
185
+ // The host moved the document before its event reached the room: it saves at the new path.
186
+ room.abs = abs;
187
+ keyAt.set(abs, key);
188
+ }
189
+ return key;
190
+ };
191
+
192
+ /** Forget a hosted room's document, by every path that named it: its next open finds anew. */
193
+ const forget = (key: string): void => {
194
+ hosted.delete(key);
195
+ for (const [at, named] of keyAt) {
196
+ if (named === key) {
197
+ keyAt.delete(at);
198
+ }
199
+ }
200
+ };
201
+
202
+ /**
203
+ * Record the room `key` names as it loads, before its first read so a second open of the path
204
+ * names the same room. Returns the call that undoes it, for a room that does not load.
205
+ */
206
+ const record = (path: string, key: string): (() => void) => {
207
+ if (key === path) {
208
+ plain.add(key);
209
+ return () => {
210
+ plain.delete(key);
211
+ };
212
+ }
213
+ const abs = resolve(absRoot, path);
214
+ keyAt.set(abs, key);
215
+ if (!hosted.has(key)) {
216
+ hosted.set(key, { abs, base: null, root: coverage(abs) ?? absRoot });
217
+ }
218
+ return () => {
219
+ forget(key);
220
+ };
221
+ };
222
+
223
+ /**
224
+ * Save a hosted room through the host, with its base (§5); a stale base reaches the room. The
225
+ * active project's host by default, or `through`, the host of a project being retired. `override`
226
+ * is a base the participant named in place of the room's own: they chose to keep the room's edits
227
+ * over what is on disk now (§6.1).
228
+ */
229
+ const persistHosted = async (
230
+ key: string,
231
+ room: HostedRoom,
232
+ source: string,
233
+ through?: ProjectStateHost,
234
+ override?: { baseHash: ContentHash | null },
235
+ ): Promise<void> => {
236
+ const hash = await contentHash(source);
237
+ const base = override === undefined ? room.base : override.baseHash;
238
+ if (hash === base) {
239
+ room.base = hash;
240
+ pendingPersist.delete(key);
241
+ host.markPersisted(key);
242
+ return;
243
+ }
244
+ if (through === undefined && projectEvents?.root !== room.root) {
114
245
  return;
115
246
  }
247
+ const writeId = `collab-${randomUUID()}`;
248
+ ownWrites.add(writeId);
249
+ try {
250
+ const running = through ?? (await projectEvents!.start());
251
+ const result = await running.write({
252
+ baseHash: base,
253
+ contents: source,
254
+ path: relative(room.root, room.abs).replaceAll("\\", "/"),
255
+ writeId,
256
+ });
257
+ if (result.ok) {
258
+ room.base = result.hash;
259
+ pendingPersist.delete(key);
260
+ host.markPersisted(key);
261
+ return;
262
+ }
263
+ ownWrites.delete(writeId);
264
+ host.conflict(key, { diskHash: result.conflict.diskHash, docId: result.conflict.docId });
265
+ } catch {
266
+ // The write failed (or the host could not start): the next explicit save retries.
267
+ ownWrites.delete(writeId);
268
+ }
269
+ };
270
+
271
+ /** Save a room keyed by its path, unconditionally: last writer wins, as before (§11.3). */
272
+ const persistPlain = async (path: string, source: string): Promise<void> => {
116
273
  if (lastWritten.get(path) === source) {
117
274
  pendingPersist.delete(path);
118
275
  return;
@@ -130,11 +287,60 @@ export function createCollabRegistry(opts: {
130
287
  }
131
288
  };
132
289
 
290
+ /**
291
+ * Run `save` after the room's save in flight, if any. A save reads the room's base when it runs,
292
+ * so two saves pressed together never both name the base the first one replaces.
293
+ */
294
+ const serialize = (key: string, save: () => Promise<void>): Promise<void> => {
295
+ const next = (persisting.get(key) ?? Promise.resolve()).then(save);
296
+ persisting.set(key, next);
297
+ void next.finally(() => {
298
+ if (persisting.get(key) === next) {
299
+ persisting.delete(key);
300
+ }
301
+ });
302
+ return next;
303
+ };
304
+
305
+ /**
306
+ * Save the room `key` names now, through `through` when given, and against `override` when the
307
+ * participant named a base (see {@link persistHosted}). A room keyed by its path saves without a
308
+ * base, so it has none to override.
309
+ */
310
+ const persist = (
311
+ key: string,
312
+ through?: ProjectStateHost,
313
+ override?: { baseHash: ContentHash | null },
314
+ ): Promise<void> =>
315
+ serialize(key, async () => {
316
+ const source = host.sourceOf(key);
317
+ if (source === null) {
318
+ return;
319
+ }
320
+ const room = hosted.get(key);
321
+ await (room === undefined
322
+ ? persistPlain(key, source)
323
+ : persistHosted(key, room, source, through, override));
324
+ });
325
+
326
+ /** Decodes a file as `readFile(path, "utf8")` does, keeping a byte order mark in the text. */
327
+ const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
328
+
133
329
  const host = createCollabHost({
134
- loadSource: async (path) => {
330
+ keyOf,
331
+ loadSource: async (path, key) => {
332
+ const undo = record(path, key);
135
333
  try {
136
- return await readFile(absPathFor(path), "utf8");
334
+ const bytes = await readFile(absPathFor(path));
335
+ const room = hosted.get(key);
336
+ if (room !== undefined) {
337
+ room.base = await contentHash(bytes);
338
+ // The room saves through the host, so it starts now rather than on the first save.
339
+ projectEvents?.start().catch(() => {});
340
+ }
341
+ return decoder.decode(bytes);
137
342
  } catch {
343
+ undo();
138
344
  return null;
139
345
  }
140
346
  },
@@ -151,10 +357,26 @@ export function createCollabRegistry(opts: {
151
357
  destroyTimers.delete(path);
152
358
  pendingPersist.delete(path);
153
359
  host.destroyRoomIfEmpty(path);
360
+ if (host.sourceOf(path) === null) {
361
+ forget(path);
362
+ plain.delete(path);
363
+ }
154
364
  }, EMPTY_ROOM_GRACE_MS),
155
365
  );
156
366
  },
157
- onFlush: (path) => persist(path),
367
+ onFlush: (path, flush) => {
368
+ const named = flush?.baseHash;
369
+ // A base that names no bytes is not one: the save keeps the room's own.
370
+ return named === null || isContentHash(named)
371
+ ? persist(path, undefined, { baseHash: named })
372
+ : persist(path);
373
+ },
374
+ /* Take the disk's copy (§6.1): the room's unsaved edits go, and every participant reopens it
375
+ seeded from the file. */
376
+ onRevert: (path) => {
377
+ pendingPersist.delete(path);
378
+ host.resetDoc(path);
379
+ },
158
380
  onSourceChange: (path) => {
159
381
  // No write-back: edits reach disk only on explicit flush (or graceful shutdown). The host
160
382
  // Owns the dirty broadcast; we just note the path for the shutdown worklist.
@@ -173,6 +395,155 @@ export function createCollabRegistry(opts: {
173
395
  },
174
396
  });
175
397
 
398
+ /** Every hosted room under `abs`, the path itself included. */
399
+ const under = (abs: string): [string, string][] =>
400
+ [...keyAt].filter(([at]) => at === abs || at.startsWith(`${abs}${sep}`));
401
+
402
+ /**
403
+ * Follow the host's index (§11.3): a rename moves a room, a removal closes it, and a change that
404
+ * is not the room's own save reseeds it, unless it left the bytes the room already holds or the
405
+ * room holds unsaved edits, which it keeps as a conflict (§6.1).
406
+ */
407
+ const apply = async (root: string, event: ProjectEvent): Promise<void> => {
408
+ if (event.type === "fileRenamed") {
409
+ const from = resolve(root, event.from);
410
+ const to = resolve(root, event.to);
411
+ for (const [at, key] of under(from)) {
412
+ const moved = `${to}${at.slice(from.length)}`;
413
+ const displaced = keyAt.get(moved);
414
+ if (displaced !== undefined && displaced !== key) {
415
+ host.resetDoc(displaced);
416
+ forget(displaced);
417
+ }
418
+ keyAt.delete(at);
419
+ keyAt.set(moved, key);
420
+ const room = hosted.get(key);
421
+ if (room !== undefined && room.abs === at) {
422
+ room.abs = moved;
423
+ }
424
+ }
425
+ return;
426
+ }
427
+ if (event.type === "fileRemoved") {
428
+ for (const [, key] of under(resolve(root, event.path))) {
429
+ pendingPersist.delete(key);
430
+ host.resetDoc(key);
431
+ forget(key);
432
+ }
433
+ return;
434
+ }
435
+ if (event.type !== "fileChanged") {
436
+ return;
437
+ }
438
+ if (event.origin !== "external" && ownWrites.delete(event.origin.writeId)) {
439
+ return;
440
+ }
441
+ const key = keyAt.get(resolve(root, event.path));
442
+ const room = key === undefined ? undefined : hosted.get(key);
443
+ if (key === undefined || room === undefined || event.hash === room.base) {
444
+ return;
445
+ }
446
+ const source = host.sourceOf(key);
447
+ const held = source === null ? null : await contentHash(source);
448
+ if (held === event.hash) {
449
+ room.base = event.hash;
450
+ pendingPersist.delete(key);
451
+ host.markPersisted(key);
452
+ return;
453
+ }
454
+ if (held !== null && held !== room.base) {
455
+ /* The room holds unsaved edits, and the file changed under them: its buffer is conflicted
456
+ (§6.1). Reseeding it would drop those edits while every participant's tab still showed
457
+ them, so it keeps them and its base, and every participant is told now, as a refused save
458
+ would tell them. Its next save is refused until a participant chooses whose bytes win. */
459
+ host.conflict(key, { diskHash: event.hash, docId: event.docId });
460
+ return;
461
+ }
462
+ host.resetDoc(key);
463
+ };
464
+
465
+ /**
466
+ * The host of `root` began a new epoch and answered with `snapshot` (§4.8): whatever changed
467
+ * between reaches each room as the event it would have been, a removal or a change.
468
+ */
469
+ const resync = async (root: string, snapshot: ProjectSnapshot): Promise<void> => {
470
+ const files = new Map(snapshot.files.map((file) => [file.path, file]));
471
+ // Every hosted room is the served project's: an activation forgets the rooms of the one before.
472
+ for (const [key, room] of hosted) {
473
+ const path = relative(root, room.abs).replaceAll("\\", "/");
474
+ const file = files.get(path);
475
+ if (file === undefined) {
476
+ pendingPersist.delete(key);
477
+ host.resetDoc(key);
478
+ forget(key);
479
+ } else if (file.hash !== undefined) {
480
+ await apply(root, {
481
+ docId: file.docId,
482
+ hash: file.hash,
483
+ origin: "external",
484
+ path,
485
+ rev: 0,
486
+ type: "fileChanged",
487
+ });
488
+ }
489
+ }
490
+ };
491
+
492
+ let applying: Promise<void> = Promise.resolve();
493
+ /** Run `step` after every earlier one; one that fails is reported, and the next still runs. */
494
+ const queue = (step: () => Promise<void>): void => {
495
+ applying = applying.then(step).catch((error: Error) => {
496
+ console.error(`[collab] following the project state: ${error.message}`);
497
+ });
498
+ };
499
+ const unfollow = projectEvents?.follow({
500
+ events: (root, events) => {
501
+ queue(async () => {
502
+ for (const event of events) {
503
+ await apply(root, event);
504
+ }
505
+ });
506
+ },
507
+ resynced: (root, snapshot) => {
508
+ queue(() => resync(root, snapshot));
509
+ },
510
+ /* The last moment the project's host takes writes: every room with unsaved edits is saved
511
+ through it, with its base, before the activation closes them. */
512
+ retiring: async (running) => {
513
+ const saves: Promise<void>[] = [];
514
+ for (const [key, room] of hosted) {
515
+ if (room.root === running.root && pendingPersist.has(key)) {
516
+ saves.push(persist(key, running));
517
+ }
518
+ }
519
+ await Promise.all(saves);
520
+ },
521
+ /* Another project: its rooms re-open under the next one, which may not cover them. A room
522
+ keyed by its path that the next one covers closes too, so one file never has two rooms; its
523
+ unsaved edits are saved first, as they would have been. */
524
+ retired: (root) => {
525
+ for (const [key, room] of hosted) {
526
+ if (room.root === root) {
527
+ pendingPersist.delete(key);
528
+ host.resetDoc(key);
529
+ forget(key);
530
+ }
531
+ }
532
+ for (const key of plain) {
533
+ if (coverage(resolve(absRoot, key)) === null) {
534
+ continue;
535
+ }
536
+ const source = host.sourceOf(key);
537
+ const dirty = pendingPersist.delete(key);
538
+ host.resetDoc(key);
539
+ plain.delete(key);
540
+ if (dirty && source !== null) {
541
+ void serialize(key, () => persistPlain(key, source));
542
+ }
543
+ }
544
+ },
545
+ });
546
+
176
547
  return {
177
548
  handleExternalChange(absPath) {
178
549
  const path = relPathFor(absPath);
@@ -233,11 +604,12 @@ export function createCollabRegistry(opts: {
233
604
  return;
234
605
  }
235
606
  stopped = true;
607
+ unfollow?.();
236
608
  for (const timer of destroyTimers.values()) {
237
609
  clearTimeout(timer);
238
610
  }
239
611
  // Last-ditch safety on graceful shutdown: flush every path with unsaved edits.
240
- const flushes: Promise<void>[] = [];
612
+ const flushes: Promise<void>[] = [...persisting.values()];
241
613
  for (const path of pendingPersist) {
242
614
  flushes.push(persist(path));
243
615
  }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * A project file as an editing host answers it, which for a `.jxn` document is JSON.
3
+ *
4
+ * The runtime fetches a `$ref`, a `Jx()` source or an `$elements` entry and reads the body as JSON
5
+ * on every origin (`spec.md` §23.2), so every host that serves a project's documents answers a
6
+ * `.jxn` one as the JSON it parses to, exactly as a site origin does (`@jxsuite/site` `serve.ts`).
7
+ * The dev server did and the desktop loopback did not: it streamed the KDL source typed
8
+ * `application/octet-stream`, and a component preview in Studio's own window, which installs no KDL
9
+ * parser of its own until it asks for one, failed on every starter component.
10
+ *
11
+ * Editing a file's SOURCE never goes through this lane. Studio reads text through the platform
12
+ * (`/__studio/file` on the dev server, the `readFile` RPC on desktop), so answering JSON here takes
13
+ * nothing away from the Code view.
14
+ *
15
+ * @docs framework/concepts/jxn-files
16
+ */
17
+ import { isJxnPath } from "@jxsuite/schema/jxn";
18
+ import { jxnAsJson } from "@jxsuite/site/serve";
19
+ import { fileResponse, openFile } from "./file-response.ts";
20
+
21
+ /**
22
+ * The response for the project file at `path`, or null when there is no regular file there. A
23
+ * `.jxn` document answers JSON (422 with the reason when it does not parse); anything else streams
24
+ * as {@link fileResponse} does.
25
+ *
26
+ * @param path An absolute path the caller has already contained.
27
+ * @param headers The headers for a `.jxn` answer of a media type; the site origin's by default.
28
+ */
29
+ export async function projectFileResponse(
30
+ path: string,
31
+ headers?: (type: string) => HeadersInit,
32
+ ): Promise<Response | null> {
33
+ if (!isJxnPath(path)) {
34
+ return fileResponse(path);
35
+ }
36
+ const blob = await openFile(path);
37
+ if (!blob) {
38
+ return null;
39
+ }
40
+ return jxnAsJson(new Uint8Array(await blob.arrayBuffer()), path, headers);
41
+ }
package/src/net-guard.ts CHANGED
@@ -21,7 +21,7 @@ import { realpathSync } from "node:fs";
21
21
  import { resolveAssetUrl } from "@jxsuite/schema/asset-paths";
22
22
  import type { AssetMount } from "@jxsuite/schema/asset-paths";
23
23
  import { problem } from "./problem.ts";
24
- import { fileResponse } from "./file-response.ts";
24
+ import { projectFileResponse } from "./jxn-response.ts";
25
25
 
26
26
  export const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
27
27
 
@@ -294,14 +294,15 @@ export function containedPath(absPath: string, root: string): string | null {
294
294
 
295
295
  /**
296
296
  * Serve a file under `root` if it both exists and is contained. Returns the Response, or null when
297
- * missing/traversed (caller decides the fallthrough status).
297
+ * missing/traversed (caller decides the fallthrough status). A `.jxn` document answers as the JSON
298
+ * it parses to, as every Jx host answers one (`jxn-response.ts`).
298
299
  */
299
300
  export async function serveContained(absPath: string, root: string): Promise<Response | null> {
300
301
  const safe = containedPath(absPath, root);
301
302
  if (!safe) {
302
303
  return null;
303
304
  }
304
- return fileResponse(safe);
305
+ return projectFileResponse(safe);
305
306
  }
306
307
 
307
308
  /**