@jxsuite/server 9.2.0 → 9.3.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.
@@ -45,6 +45,7 @@ import { createLoopbackAuthorizer, OAUTH_CALLBACK_PATH } from "./oauth-loopback.
45
45
  import type { LoopbackAuthorizer } from "./oauth-loopback.ts";
46
46
  import type { FsEventBatch } from "./sse.ts";
47
47
  import type { JsonPrimitive, JsonValue } from "@jxsuite/schema/types";
48
+ import type { ProblemDetails } from "@jxsuite/protocol";
48
49
  import { bundleToString } from "@jxsuite/compiler/bundler";
49
50
 
50
51
  /**
@@ -54,8 +55,53 @@ import { bundleToString } from "@jxsuite/compiler/bundler";
54
55
  */
55
56
  export type RpcResult = JsonPrimitive | object | undefined;
56
57
 
57
- /** One RPC method: the request frame's decoded `params` in, the reply's `result` out. */
58
- export type RpcHandler = (params: JsonValue | undefined) => Promise<RpcResult>;
58
+ /**
59
+ * The socket a request arrived on, for a handler that keeps talking to it after its reply: the
60
+ * project state subscription (`project-state.md` §3.2), whose later events go to the subscribing
61
+ * socket alone and end when it closes.
62
+ */
63
+ export interface RpcConnection {
64
+ /** The socket's number, the same for every request it carries and unique within the server. */
65
+ readonly id: number;
66
+ /** Send one text frame to this socket; `false` when it has closed. */
67
+ send: (frame: string) => boolean;
68
+ /**
69
+ * How many bytes this socket still holds for a peer that has not read them, `0` once it has
70
+ * closed: a handler that streams checks it before it sends more.
71
+ */
72
+ buffered: () => number;
73
+ /** Run `listener` once this socket closes (at once when it already has). */
74
+ onClose: (listener: () => void) => void;
75
+ /**
76
+ * Run `listener` right after this request's reply is sent, before any other frame can be, so a
77
+ * frame the handler holds back cannot overtake the reply it follows.
78
+ */
79
+ afterReply: (listener: () => void) => void;
80
+ }
81
+
82
+ /**
83
+ * A refusal carried as an RFC 9457 problem document: the reply frame carries it as `problem` beside
84
+ * the `error` sentence, so a client can read its members (a `412` precondition failure names what
85
+ * is on disk, `project-state.md` §5).
86
+ */
87
+ export class RpcProblemError extends Error {
88
+ readonly problem: ProblemDetails;
89
+
90
+ constructor(details: ProblemDetails) {
91
+ super(details.detail ?? details.title);
92
+ this.name = "RpcProblemError";
93
+ this.problem = details;
94
+ }
95
+ }
96
+
97
+ /**
98
+ * One RPC method: the request frame's decoded `params` in, the reply's `result` out. The connection
99
+ * is given to every request the server dispatches; a handler that never needs it leaves it off.
100
+ */
101
+ export type RpcHandler = (
102
+ params: JsonValue | undefined,
103
+ connection?: RpcConnection,
104
+ ) => Promise<RpcResult>;
59
105
 
60
106
  /**
61
107
  * What an unsolicited push carries as its `params`: JSON, or the filesystem batch the sidebar
@@ -152,6 +198,38 @@ export async function createProjectServer(
152
198
  the socket's whole lifetime — added on open, dropped on close — so a push after a window is
153
199
  gone reaches nobody rather than throwing. */
154
200
  const sockets = new Set<ServeSocket<{ winId: string | null }>>();
201
+ /** What each socket runs when it closes (see RpcConnection.onClose). */
202
+ const closeListeners = new WeakMap<ServeSocket<{ winId: string | null }>, (() => void)[]>();
203
+ /** Each socket's number (see RpcConnection.id). */
204
+ const socketIds = new WeakMap<ServeSocket<{ winId: string | null }>, number>();
205
+ let socketSerial = 0;
206
+
207
+ /** The connection a handler is handed for a request on `ws`; `replied` collects afterReply. */
208
+ const connectionFor = (
209
+ ws: ServeSocket<{ winId: string | null }>,
210
+ replied: (() => void)[],
211
+ ): RpcConnection => ({
212
+ id: socketIds.get(ws) ?? 0,
213
+ afterReply: (listener) => {
214
+ replied.push(listener);
215
+ },
216
+ buffered: () => (sockets.has(ws) ? ws.getBufferedAmount() : 0),
217
+ onClose: (listener) => {
218
+ const listeners = closeListeners.get(ws);
219
+ if (listeners === undefined) {
220
+ listener();
221
+ } else {
222
+ listeners.push(listener);
223
+ }
224
+ },
225
+ send: (frame) => {
226
+ if (!sockets.has(ws)) {
227
+ return false;
228
+ }
229
+ ws.send(frame);
230
+ return true;
231
+ },
232
+ });
155
233
 
156
234
  const server = await serve<{ winId: string | null }>({
157
235
  hostname,
@@ -357,9 +435,21 @@ export async function createProjectServer(
357
435
  websocket: {
358
436
  open(ws) {
359
437
  sockets.add(ws);
438
+ closeListeners.set(ws, []);
439
+ socketSerial += 1;
440
+ socketIds.set(ws, socketSerial);
360
441
  },
361
442
  close(ws) {
362
443
  sockets.delete(ws);
444
+ const listeners = closeListeners.get(ws) ?? [];
445
+ closeListeners.delete(ws);
446
+ for (const listener of listeners) {
447
+ try {
448
+ listener();
449
+ } catch (error) {
450
+ console.error("[project-server] a close listener failed:", error);
451
+ }
452
+ }
363
453
  },
364
454
  async message(ws, raw) {
365
455
  let msg: RpcRequestFrame;
@@ -405,14 +495,23 @@ export async function createProjectServer(
405
495
  return;
406
496
  }
407
497
 
498
+ const replied: (() => void)[] = [];
408
499
  try {
409
- const result = await handler(msg.params);
500
+ const result = await handler(msg.params, connectionFor(ws, replied));
410
501
  ws.send(JSON.stringify({ id: msg.id, result: result ?? null }));
502
+ for (const listener of replied) {
503
+ try {
504
+ listener();
505
+ } catch (error) {
506
+ console.error("[project-server] an after-reply listener failed:", error);
507
+ }
508
+ }
411
509
  } catch (error: unknown) {
412
510
  ws.send(
413
511
  JSON.stringify({
414
512
  error: error instanceof Error ? error.message : String(error),
415
513
  id: msg.id,
514
+ ...(error instanceof RpcProblemError && { problem: error.problem }),
416
515
  }),
417
516
  );
418
517
  }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * The collection loader's lists for the project state host's dependency graph
3
+ * (`specs/project-state.md` §8.1): each content type's entry files as the project's own `content`
4
+ * section owner resolves them, so `where` and `hold` count as well as `exclude`. Shared by every
5
+ * host that runs `createProjectStateHost` (the desktop session and the dev server, §10.1, §10.2).
6
+ *
7
+ * @docs studio/desktop
8
+ */
9
+
10
+ import { extname } from "node:path";
11
+ import { isJsonObject, isString } from "@jxsuite/schema/guards";
12
+ import type { ExtensionRegistry } from "@jxsuite/schema/extension-registry";
13
+ import type { ProjectSectionData } from "@jxsuite/schema/format-registry";
14
+ import type { ContentLoaderEntry, ProjectConfig } from "@jxsuite/schema/types";
15
+ import { sourceCollections } from "./host-deps.ts";
16
+ import type { CollectionResolver } from "./host-deps.ts";
17
+
18
+ /** What the collection loader is asked for: every project section an extension loads. */
19
+ export type SectionLoader = (
20
+ root: string,
21
+ config: ProjectConfig | undefined,
22
+ registry: ExtensionRegistry,
23
+ options: { includeHeld: boolean },
24
+ ) => Promise<Record<string, ProjectSectionData>>;
25
+
26
+ /**
27
+ * Whether `file` is the one `entry` came from: its source-relative path and its locale. An entry of
28
+ * a single-file source names no path, and comes from that file.
29
+ */
30
+ function cameFrom(entry: ContentLoaderEntry, file: string, singleFile: boolean): boolean {
31
+ const path = entry._meta?.path;
32
+ if (path === undefined) {
33
+ return singleFile;
34
+ }
35
+ if (file !== path && !file.endsWith(`/${path}`)) {
36
+ return false;
37
+ }
38
+ const locale = entry._meta?.locale?.toLowerCase();
39
+ return (
40
+ locale === undefined ||
41
+ file
42
+ .slice(0, file.length - path.length)
43
+ .split("/")
44
+ .some((segment) => segment.toLowerCase() === locale)
45
+ );
46
+ }
47
+
48
+ /**
49
+ * The compiler's section loader, imported when a collection is first resolved: the build pipeline
50
+ * is not loaded for a window that never subscribes.
51
+ */
52
+ const compilerSections: SectionLoader = async (root, config, registry, options) => {
53
+ const { loadProjectSections } = await import("@jxsuite/compiler/project-sections");
54
+ return loadProjectSections(root, config, registry, options);
55
+ };
56
+
57
+ /**
58
+ * Each content type's entry files as the collection loader resolves them (§8.1): the files the
59
+ * type's `source` covers (`sourceCollections`), less the ones the loader left out, so `where` and
60
+ * `hold` count as well as `exclude`. The loader is the project's own `content` section owner,
61
+ * reached through its extension registry; a project that installs none, a type the loader did not
62
+ * answer, or a load that failed falls back to the source's files.
63
+ *
64
+ * @param registryFor The project's extension registry, as the session builds it.
65
+ * @param loadSections The section loader; the compiler's by default.
66
+ */
67
+ export function collectionLoaderResolver(
68
+ registryFor: () => Promise<ExtensionRegistry>,
69
+ loadSections: SectionLoader = compilerSections,
70
+ ): CollectionResolver {
71
+ return async (input) => {
72
+ const candidates = await sourceCollections(input);
73
+ if (Object.keys(candidates).length === 0) {
74
+ return candidates;
75
+ }
76
+ let section: ProjectSectionData | undefined;
77
+ try {
78
+ const sections = await loadSections(input.root, input.config, await registryFor(), {
79
+ includeHeld: true,
80
+ });
81
+ section = sections.content;
82
+ } catch {
83
+ return candidates;
84
+ }
85
+ if (!(section instanceof Map)) {
86
+ return candidates;
87
+ }
88
+ const resolved: Record<string, readonly string[]> = {};
89
+ const sources = new Map<string, string>();
90
+ const content = input.config?.content;
91
+ if (isJsonObject(content)) {
92
+ for (const [type, def] of Object.entries(content)) {
93
+ if (isJsonObject(def) && isString(def.source)) {
94
+ sources.set(type, def.source);
95
+ }
96
+ }
97
+ }
98
+ for (const [type, files] of Object.entries(candidates)) {
99
+ const entries = section.get(type);
100
+ const singleFile = extname(sources.get(type) ?? "") !== "";
101
+ resolved[type] =
102
+ entries === undefined
103
+ ? files
104
+ : files.filter((file) => entries.some((entry) => cameFrom(entry, file, singleFile)));
105
+ }
106
+ return resolved;
107
+ };
108
+ }
@@ -0,0 +1,302 @@
1
+ /**
2
+ * The project state host's git monitor (`specs/project-state.md` §4.5): a watch on the repository's
3
+ * `HEAD`, `index` and `refs`, a debounce, then one `git status --porcelain=v2 -z`, reported only
4
+ * when the summary differs from the last one reported. A commit, checkout, stage or pull is
5
+ * observed this way whoever ran it; the host also asks for a run after each file event, because an
6
+ * edit to the working tree moves the summary without touching the repository's own files.
7
+ *
8
+ * Paths are project-relative through `git-scope.ts`, the rules both backends already share, so a
9
+ * project nested inside a larger repository sees only its own changes.
10
+ *
11
+ * Runs on Node (the desktop backend's utility process) and on Bun: it spawns git through
12
+ * `node:child_process` and watches through chokidar.
13
+ *
14
+ * @module
15
+ */
16
+
17
+ import { spawn } from "node:child_process";
18
+ import { watch } from "chokidar";
19
+ import { projectRelativePath } from "@jxsuite/protocol/git-scope";
20
+ import { toError } from "@jxsuite/schema/parse";
21
+ import type { GitRunner } from "@jxsuite/protocol/git-scope";
22
+ import type { GitSummary, WorkingState } from "@jxsuite/protocol/project-state";
23
+
24
+ /** The quiet period between the last repository change and the status run (§4.5). */
25
+ export const GIT_DEBOUNCE_MS = 150;
26
+
27
+ /** Run git in `cwd` through `node:child_process`, resolving stdout and rejecting on failure. */
28
+ export function nodeGitRunner(cwd: string): GitRunner {
29
+ return (args) =>
30
+ new Promise((resolve, reject) => {
31
+ const proc = spawn("git", args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
32
+ const out: Buffer[] = [];
33
+ const err: Buffer[] = [];
34
+ proc.stdout.on("data", (chunk: Buffer) => out.push(chunk));
35
+ proc.stderr.on("data", (chunk: Buffer) => err.push(chunk));
36
+ proc.once("error", reject);
37
+ proc.once("close", (code) => {
38
+ if (code === 0) {
39
+ resolve(Buffer.concat(out).toString("utf8"));
40
+ } else {
41
+ const message = Buffer.concat(err).toString("utf8").trim();
42
+ reject(new Error(`git ${args[0] ?? ""} failed: ${message || `exit ${code}`}`));
43
+ }
44
+ });
45
+ });
46
+ }
47
+
48
+ /** The working state an entry's two status letters (index, worktree) give it (§6.2). */
49
+ function stateOf(xy: string): WorkingState {
50
+ if (xy.includes("D")) {
51
+ return "deleted";
52
+ }
53
+ return xy.startsWith("A") ? "added" : "modified";
54
+ }
55
+
56
+ /** The rest of a record after `count` space-separated fields: a path, which may hold spaces. */
57
+ function afterFields(record: string, count: number): string {
58
+ let at = 0;
59
+ for (let field = 0; field < count; field += 1) {
60
+ at = record.indexOf(" ", at) + 1;
61
+ }
62
+ return record.slice(at);
63
+ }
64
+
65
+ /**
66
+ * Read `git status --porcelain=v2 -z --branch` output as a {@link GitSummary}, with every path made
67
+ * project-relative against `prefix` (`git rev-parse --show-prefix`). A path outside the project is
68
+ * left out: its working state belongs to another project in the same repository.
69
+ */
70
+ export function parseStatus(out: string, prefix: string): GitSummary {
71
+ const summary: GitSummary = { branch: null, changed: {}, head: null };
72
+ const records = out.split("\0");
73
+ const put = (path: string, state: WorkingState): void => {
74
+ if (path.startsWith(prefix)) {
75
+ summary.changed[projectRelativePath(prefix, path)] = state;
76
+ }
77
+ };
78
+ for (let at = 0; at < records.length; at += 1) {
79
+ const record = records[at]!;
80
+ if (record.startsWith("# branch.oid ")) {
81
+ const oid = record.slice("# branch.oid ".length);
82
+ summary.head = oid === "(initial)" ? null : oid;
83
+ } else if (record.startsWith("# branch.head ")) {
84
+ const head = record.slice("# branch.head ".length);
85
+ summary.branch = head === "(detached)" ? null : head;
86
+ } else if (record.startsWith("1 ")) {
87
+ put(afterFields(record, 8), stateOf(record.slice(2, 4)));
88
+ } else if (record.startsWith("2 ")) {
89
+ put(afterFields(record, 9), "renamed");
90
+ // A rename's original path is the next record.
91
+ at += 1;
92
+ } else if (record.startsWith("u ")) {
93
+ put(afterFields(record, 10), "modified");
94
+ } else if (record.startsWith("? ")) {
95
+ put(record.slice(2), "untracked");
96
+ }
97
+ }
98
+ const sorted: Record<string, WorkingState> = {};
99
+ for (const path of Object.keys(summary.changed).toSorted()) {
100
+ sorted[path] = summary.changed[path]!;
101
+ }
102
+ summary.changed = sorted;
103
+ return summary;
104
+ }
105
+
106
+ /** A watch over the repository's own files; told of every change, whatever it was. */
107
+ export interface GitWatchHandle {
108
+ ready: Promise<void>;
109
+ close: () => Promise<void>;
110
+ }
111
+
112
+ /** Watch `paths` (absolute), calling `onChange` for every change and `onError` for a failure. */
113
+ export type GitWatchFactory = (
114
+ paths: readonly string[],
115
+ onChange: () => void,
116
+ onError: (error: Error) => void,
117
+ ) => GitWatchHandle;
118
+
119
+ /** The default {@link GitWatchFactory}: chokidar, with no write-finish wait (git writes by rename). */
120
+ export const chokidarGitWatch: GitWatchFactory = (paths, onChange, onError) => {
121
+ const watcher = watch([...paths], { ignoreInitial: true, ignorePermissionErrors: true });
122
+ watcher.on("all", () => onChange());
123
+ watcher.on("error", (cause) =>
124
+ onError(cause instanceof Error ? cause : new Error(String(cause))),
125
+ );
126
+ const ready = new Promise<void>((resolve) => {
127
+ watcher.once("ready", () => resolve());
128
+ });
129
+ return { close: () => watcher.close(), ready };
130
+ };
131
+
132
+ export interface GitMonitorOptions {
133
+ /** The absolute project root, git's working directory. */
134
+ root: string;
135
+ /** Runs git in the root; defaults to {@link nodeGitRunner}. */
136
+ run?: GitRunner;
137
+ /** Watches the repository's files; defaults to {@link chokidarGitWatch}. */
138
+ watch?: GitWatchFactory;
139
+ /** Defaults to {@link GIT_DEBOUNCE_MS}. */
140
+ debounceMs?: number;
141
+ /** Told each summary that differs from the last one reported. */
142
+ onChange: (summary: GitSummary) => void;
143
+ /** Told of a failed status run or watch error; never fatal. */
144
+ onError?: (error: Error) => void;
145
+ /** Told whenever the repository's files move, before the debounce. */
146
+ onActivity?: () => void;
147
+ }
148
+
149
+ export interface GitMonitor {
150
+ /** The last summary reported, or read at start; `undefined` outside a repository. */
151
+ readonly summary: GitSummary | undefined;
152
+ /** Ask for a status run after the debounce (a working-tree change). */
153
+ schedule: () => void;
154
+ /** Whether no run is waiting, running or owed. */
155
+ idle: () => boolean;
156
+ close: () => Promise<void>;
157
+ }
158
+
159
+ /** The repository's own directories, read once at start. */
160
+ interface RepositoryDirs {
161
+ gitDir: string;
162
+ commonDir: string;
163
+ prefix: string;
164
+ }
165
+
166
+ /** Git's own answer for a directory outside every repository, which is no failure. */
167
+ const NOT_A_REPOSITORY = /not a git repository/i;
168
+
169
+ /**
170
+ * The repository's directories, or `null` outside one. Any other failure (no git on the `PATH`, a
171
+ * git too old for `--path-format`) is reported too, so a missing summary always has a reason.
172
+ */
173
+ async function repositoryDirs(
174
+ run: GitRunner,
175
+ report: (error: Error) => void,
176
+ ): Promise<RepositoryDirs | null> {
177
+ try {
178
+ const out = await run([
179
+ "rev-parse",
180
+ "--path-format=absolute",
181
+ "--git-dir",
182
+ "--git-common-dir",
183
+ "--show-prefix",
184
+ ]);
185
+ const [gitDir = "", commonDir = "", prefix = ""] = out.split("\n");
186
+ return { commonDir, gitDir, prefix };
187
+ } catch (error) {
188
+ const failure = toError(error);
189
+ if (!NOT_A_REPOSITORY.test(failure.message)) {
190
+ report(failure);
191
+ }
192
+ return null;
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Start a git monitor over `root`. Resolves once the first summary is read (or the root is found to
198
+ * be outside any repository) and the watch is armed; that first summary is not reported.
199
+ */
200
+ export async function createGitMonitor(options: GitMonitorOptions): Promise<GitMonitor> {
201
+ const run = options.run ?? nodeGitRunner(options.root);
202
+ const debounceMs = options.debounceMs ?? GIT_DEBOUNCE_MS;
203
+ const report = (error: Error): void => {
204
+ options.onError?.(error);
205
+ };
206
+ const dirs = await repositoryDirs(run, report);
207
+ let summary: GitSummary | undefined;
208
+ let last = "";
209
+ let timer: ReturnType<typeof setTimeout> | null = null;
210
+ let running = false;
211
+ let owed = false;
212
+ let closed = false;
213
+
214
+ const read = async (prefix: string): Promise<GitSummary> =>
215
+ parseStatus(
216
+ await run([
217
+ "--no-optional-locks",
218
+ "status",
219
+ "--porcelain=v2",
220
+ "-z",
221
+ "--branch",
222
+ "--untracked-files=all",
223
+ "--",
224
+ ".",
225
+ ]),
226
+ prefix,
227
+ );
228
+
229
+ const runStatus = async (prefix: string): Promise<void> => {
230
+ running = true;
231
+ try {
232
+ const next = await read(prefix);
233
+ const key = JSON.stringify(next);
234
+ if (key !== last) {
235
+ last = key;
236
+ summary = next;
237
+ options.onChange(next);
238
+ }
239
+ } catch (error) {
240
+ report(toError(error));
241
+ } finally {
242
+ running = false;
243
+ }
244
+ if (owed) {
245
+ owed = false;
246
+ schedule();
247
+ }
248
+ };
249
+
250
+ const schedule = (): void => {
251
+ if (dirs === null || closed) {
252
+ return;
253
+ }
254
+ if (running) {
255
+ owed = true;
256
+ return;
257
+ }
258
+ if (timer !== null) {
259
+ clearTimeout(timer);
260
+ }
261
+ const { prefix } = dirs;
262
+ timer = setTimeout(() => {
263
+ timer = null;
264
+ void runStatus(prefix);
265
+ }, debounceMs);
266
+ };
267
+
268
+ let handle: GitWatchHandle | null = null;
269
+ if (dirs !== null) {
270
+ try {
271
+ summary = await read(dirs.prefix);
272
+ last = JSON.stringify(summary);
273
+ } catch (error) {
274
+ report(toError(error));
275
+ }
276
+ handle = (options.watch ?? chokidarGitWatch)(
277
+ [`${dirs.gitDir}/HEAD`, `${dirs.gitDir}/index`, `${dirs.commonDir}/refs`],
278
+ () => {
279
+ options.onActivity?.();
280
+ schedule();
281
+ },
282
+ report,
283
+ );
284
+ await handle.ready;
285
+ }
286
+
287
+ return {
288
+ close: async () => {
289
+ closed = true;
290
+ if (timer !== null) {
291
+ clearTimeout(timer);
292
+ timer = null;
293
+ }
294
+ await handle?.close();
295
+ },
296
+ idle: () => timer === null && !running && !owed,
297
+ schedule,
298
+ get summary() {
299
+ return summary === undefined ? undefined : structuredClone(summary);
300
+ },
301
+ };
302
+ }