@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.
- package/package.json +24 -18
- package/src/collab.ts +390 -18
- package/src/jxn-response.ts +41 -0
- package/src/net-guard.ts +4 -3
- package/src/project-events.ts +622 -0
- package/src/project-server.ts +102 -3
- package/src/project-state/collections.ts +108 -0
- package/src/project-state/git-monitor.ts +302 -0
- package/src/project-state/graph.ts +651 -0
- package/src/project-state/host-deps.ts +224 -0
- package/src/project-state/host.ts +2113 -0
- package/src/project-state/overlays.ts +231 -0
- package/src/project-state/rename.ts +473 -0
- package/src/project-state/settle.ts +38 -0
- package/src/refactor/apply.ts +177 -67
- package/src/refactor/find-refs.ts +0 -0
- package/src/refactor/index.ts +2 -1
- package/src/refactor/paths.ts +3 -325
- package/src/refactor/refs.ts +5 -388
- package/src/refactor/scan.ts +17 -4
- package/src/refactor/watcher.ts +47 -2
- package/src/serve.node.ts +1 -0
- package/src/serve.ts +7 -5
- package/src/server.ts +40 -1
- package/src/sse.ts +1 -1
- package/src/studio-api.ts +76 -9
|
@@ -0,0 +1,2113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The project state host (`specs/project-state.md` §10.1, §10.2): the in-memory model of one
|
|
3
|
+
* project that the desktop backend and the dev server serve, over a real directory, a filesystem
|
|
4
|
+
* watcher and the git CLI.
|
|
5
|
+
*
|
|
6
|
+
* It keeps a file index with a {@link DocId} and a content hash per file (§2.1, §2.2), a revision
|
|
7
|
+
* counter with a replay log (§2.3), an echo ledger that attributes every observation by the bytes
|
|
8
|
+
* it saw (§2.4), the dependency graph (§8), the readiness machine (§7) and a git monitor (§4.5),
|
|
9
|
+
* and it answers a subscribe (§3.1) and the conditional writes and deletes of §5.
|
|
10
|
+
*
|
|
11
|
+
* Everything that changes the index happens in one queue, so a write's precondition, its disk
|
|
12
|
+
* change and its events are atomic with respect to every other write and to the processing of every
|
|
13
|
+
* watcher observation (§5). Within a queued step, the index is changed and the step's events
|
|
14
|
+
* appended without an `await` between them, so a subscribe, which is answered synchronously, always
|
|
15
|
+
* takes the snapshot and its revision together (§3.1).
|
|
16
|
+
*
|
|
17
|
+
* Runs on Node (the desktop backend's utility process) and on Bun: it uses `node:fs/promises`,
|
|
18
|
+
* `node:crypto`'s random ids, WebCrypto through `contentHash`, chokidar and the git CLI, and no
|
|
19
|
+
* Bun-only API.
|
|
20
|
+
*
|
|
21
|
+
* @module
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
25
|
+
import * as nodeFs from "node:fs/promises";
|
|
26
|
+
import { basename, dirname, extname, join, relative, sep } from "node:path";
|
|
27
|
+
import { watch } from "chokidar";
|
|
28
|
+
import type { Stats } from "node:fs";
|
|
29
|
+
import type { FileHandle } from "node:fs/promises";
|
|
30
|
+
import {
|
|
31
|
+
answerSubscribe,
|
|
32
|
+
checkDeletePrecondition,
|
|
33
|
+
checkWritePrecondition,
|
|
34
|
+
conflictEvent,
|
|
35
|
+
contentHash,
|
|
36
|
+
createEchoLedger,
|
|
37
|
+
createMemoryEventLog,
|
|
38
|
+
EVENT_LOG_CAPACITY,
|
|
39
|
+
readinessAtLeast,
|
|
40
|
+
} from "@jxsuite/protocol/project-state";
|
|
41
|
+
import type {
|
|
42
|
+
ContentHash,
|
|
43
|
+
DeleteBase,
|
|
44
|
+
DeleteRequest,
|
|
45
|
+
DeleteResult,
|
|
46
|
+
DocKind,
|
|
47
|
+
EchoLedger,
|
|
48
|
+
EventOrigin,
|
|
49
|
+
IndexedFile,
|
|
50
|
+
ProjectEvent,
|
|
51
|
+
ProjectEventInit,
|
|
52
|
+
ProjectEventLog,
|
|
53
|
+
ProjectSnapshot,
|
|
54
|
+
ReadinessState,
|
|
55
|
+
RenameOperation,
|
|
56
|
+
RenameOperationResult,
|
|
57
|
+
SubscribeRequest,
|
|
58
|
+
SubscribeResponse,
|
|
59
|
+
WriteOrigin,
|
|
60
|
+
WriteRequest,
|
|
61
|
+
WriteResult,
|
|
62
|
+
} from "@jxsuite/protocol/project-state";
|
|
63
|
+
import type { GitRunner } from "@jxsuite/protocol/git-scope";
|
|
64
|
+
import { isJsonObject, isString } from "@jxsuite/schema/guards";
|
|
65
|
+
import { parseJxn } from "@jxsuite/schema/jxn";
|
|
66
|
+
import { toError } from "@jxsuite/schema/parse";
|
|
67
|
+
import { PROJECT_FILE_NAMES, parseProjectFile } from "@jxsuite/schema/project-file";
|
|
68
|
+
import type { JsonObject, JsonValue, ProjectConfig } from "@jxsuite/schema/types";
|
|
69
|
+
import { createWatchIgnore } from "../watch-policy.ts";
|
|
70
|
+
import { createGitMonitor } from "./git-monitor.ts";
|
|
71
|
+
import { invalidateReferenceCache } from "../refactor/find-refs.ts";
|
|
72
|
+
import { runRenameCascade } from "./rename.ts";
|
|
73
|
+
import type { GitMonitor, GitMonitorOptions, GitWatchFactory } from "./git-monitor.ts";
|
|
74
|
+
import { createDependencyGraph, extractRefs, invalidationEvents, NO_REFS } from "./graph.ts";
|
|
75
|
+
import type {
|
|
76
|
+
DependencyGraph,
|
|
77
|
+
DependencyGraphConfig,
|
|
78
|
+
DocumentRefs,
|
|
79
|
+
GraphDocument,
|
|
80
|
+
Invalidation,
|
|
81
|
+
} from "./graph.ts";
|
|
82
|
+
import type { AssetMount } from "@jxsuite/schema/asset-paths";
|
|
83
|
+
import {
|
|
84
|
+
DEPENDENCY_FIELDS,
|
|
85
|
+
dependenciesInstalled,
|
|
86
|
+
installPackages,
|
|
87
|
+
loadInstalledFormats,
|
|
88
|
+
NO_FORMATS,
|
|
89
|
+
sourceCollections,
|
|
90
|
+
} from "./host-deps.ts";
|
|
91
|
+
import type {
|
|
92
|
+
CollectionResolver,
|
|
93
|
+
ExtensionLoader,
|
|
94
|
+
InstalledCheck,
|
|
95
|
+
Installer,
|
|
96
|
+
ProjectFormats,
|
|
97
|
+
} from "./host-deps.ts";
|
|
98
|
+
|
|
99
|
+
/* What a host embedder passes or falls back to: the default collection resolver, and the shapes
|
|
100
|
+
of the resolvers it may pass instead. */
|
|
101
|
+
export { sourceCollections } from "./host-deps.ts";
|
|
102
|
+
export type { CollectionInput, CollectionResolver } from "./host-deps.ts";
|
|
103
|
+
|
|
104
|
+
// ─── Options ───────────────────────────────────────────────────────────────────────────────────
|
|
105
|
+
|
|
106
|
+
/** The filesystem calls the host makes; `node:fs/promises` satisfies it and is the default. */
|
|
107
|
+
export interface ProjectStateFs {
|
|
108
|
+
chmod: (path: string, mode: number) => Promise<void>;
|
|
109
|
+
mkdir: (path: string, options: { recursive: true }) => Promise<string | undefined>;
|
|
110
|
+
/** Opened to hash a file without holding it whole (§2.1). */
|
|
111
|
+
open: (path: string) => Promise<FileHandle>;
|
|
112
|
+
readFile: (path: string) => Promise<Uint8Array>;
|
|
113
|
+
readdir: (path: string) => Promise<string[]>;
|
|
114
|
+
realpath: (path: string) => Promise<string>;
|
|
115
|
+
rename: (from: string, to: string) => Promise<void>;
|
|
116
|
+
rm: (path: string, options: { force?: boolean; recursive?: boolean }) => Promise<void>;
|
|
117
|
+
stat: (path: string) => Promise<Stats>;
|
|
118
|
+
writeFile: (path: string, data: Uint8Array) => Promise<void>;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** A change a watcher reports, by chokidar's names. */
|
|
122
|
+
export type ProjectWatchEvent = "add" | "addDir" | "change" | "unlink" | "unlinkDir";
|
|
123
|
+
|
|
124
|
+
/** Where a watcher delivers what it sees. Paths are absolute. */
|
|
125
|
+
export interface ProjectWatchSink {
|
|
126
|
+
event: (type: ProjectWatchEvent, path: string) => void;
|
|
127
|
+
/** Anything moved, before the watcher has decided what (chokidar's `raw`). */
|
|
128
|
+
activity: () => void;
|
|
129
|
+
/** The watcher can no longer promise it sees every change (§4.8). */
|
|
130
|
+
error: (error: Error) => void;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** How the host asks for a watcher. */
|
|
134
|
+
export interface ProjectWatchOptions {
|
|
135
|
+
/** Paths the watcher must not report (outside the index scope, and the host's own temp files). */
|
|
136
|
+
ignored: (path: string, stats?: Stats) => boolean;
|
|
137
|
+
/** The pairing bound for an atomic-rename save (§2.4). */
|
|
138
|
+
atomicSaveMs: number;
|
|
139
|
+
/** How long a file's size must hold still before its change is reported. */
|
|
140
|
+
stabilityMs: number;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export interface ProjectWatchHandle {
|
|
144
|
+
/** Settles once the watcher has scanned the root. */
|
|
145
|
+
ready: Promise<void>;
|
|
146
|
+
close: () => Promise<void>;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Start watching `root`. */
|
|
150
|
+
export type ProjectWatcherFactory = (
|
|
151
|
+
root: string,
|
|
152
|
+
sink: ProjectWatchSink,
|
|
153
|
+
options: ProjectWatchOptions,
|
|
154
|
+
) => ProjectWatchHandle;
|
|
155
|
+
|
|
156
|
+
const WATCH_EVENTS = new Set<string>(["add", "addDir", "change", "unlink", "unlinkDir"]);
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The default {@link ProjectWatcherFactory}: chokidar, reporting a write once it is whole
|
|
160
|
+
* (`awaitWriteFinish`), pairing an atomic-rename save itself (`atomic`), and following a symlink
|
|
161
|
+
* that stays inside the root.
|
|
162
|
+
*/
|
|
163
|
+
export const chokidarProjectWatcher: ProjectWatcherFactory = (root, sink, options) => {
|
|
164
|
+
const watcher = watch(root, {
|
|
165
|
+
atomic: options.atomicSaveMs,
|
|
166
|
+
awaitWriteFinish: { pollInterval: 10, stabilityThreshold: options.stabilityMs },
|
|
167
|
+
followSymlinks: true,
|
|
168
|
+
ignoreInitial: true,
|
|
169
|
+
ignorePermissionErrors: true,
|
|
170
|
+
ignored: options.ignored,
|
|
171
|
+
});
|
|
172
|
+
watcher.on("raw", () => sink.activity());
|
|
173
|
+
watcher.on("all", (type, path) => {
|
|
174
|
+
if (WATCH_EVENTS.has(type)) {
|
|
175
|
+
// SAFETY: narrowed by the set of the five names just checked.
|
|
176
|
+
sink.event(type as ProjectWatchEvent, path);
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
watcher.on("error", (cause) =>
|
|
180
|
+
sink.error(cause instanceof Error ? cause : new Error(String(cause))),
|
|
181
|
+
);
|
|
182
|
+
const ready = new Promise<void>((resolve) => {
|
|
183
|
+
watcher.once("ready", () => resolve());
|
|
184
|
+
});
|
|
185
|
+
return { close: () => watcher.close(), ready };
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
export interface ProjectStateHostOptions {
|
|
189
|
+
/** The absolute project root. */
|
|
190
|
+
root: string;
|
|
191
|
+
fs?: ProjectStateFs;
|
|
192
|
+
/** Defaults to {@link chokidarProjectWatcher}. */
|
|
193
|
+
watcher?: ProjectWatcherFactory;
|
|
194
|
+
/** Runs git in the root; `false` turns the git monitor off. Defaults to the git CLI. */
|
|
195
|
+
git?: GitRunner | false;
|
|
196
|
+
/** Watches the repository's `HEAD`, `index` and `refs`; defaults to chokidar. */
|
|
197
|
+
gitWatch?: GitWatchFactory;
|
|
198
|
+
/** The git monitor's debounce, in ms (§4.5). */
|
|
199
|
+
gitDebounceMs?: number;
|
|
200
|
+
/** Loads the configuration's extensions; defaults to {@link loadInstalledFormats}. */
|
|
201
|
+
extensions?: ExtensionLoader;
|
|
202
|
+
/** Runs an install; defaults to {@link installPackages}. */
|
|
203
|
+
installer?: Installer;
|
|
204
|
+
/** Whether the manifest's dependencies are installed; defaults to {@link dependenciesInstalled}. */
|
|
205
|
+
installed?: InstalledCheck;
|
|
206
|
+
/** Each content type's entry files; defaults to {@link sourceCollections}. */
|
|
207
|
+
collections?: CollectionResolver;
|
|
208
|
+
/** The pairing bound for an atomic-rename save, in ms (§2.4). Defaults to 100. */
|
|
209
|
+
atomicSaveMs?: number;
|
|
210
|
+
/** How long a file must hold still before the watcher reports it, in ms. Defaults to 50. */
|
|
211
|
+
stabilityMs?: number;
|
|
212
|
+
/**
|
|
213
|
+
* The largest file the host reads whole to classify it, in bytes; a larger one, and every media
|
|
214
|
+
* file or stylesheet, is hashed as a stream and never parsed (§2.2). Defaults to 64 MiB.
|
|
215
|
+
*/
|
|
216
|
+
readLimitBytes?: number;
|
|
217
|
+
/**
|
|
218
|
+
* The waits between attempts to rename a write's temporary file over its target when the rename
|
|
219
|
+
* fails as a file held open fails it on Windows (`EPERM`, `EACCES`, `EBUSY`), in ms. Defaults to
|
|
220
|
+
* a short backoff on Windows and to none elsewhere, where those failures are not transient.
|
|
221
|
+
*/
|
|
222
|
+
renameRetryMs?: readonly number[];
|
|
223
|
+
/** The replay window, in events (§2.3). */
|
|
224
|
+
logCapacity?: number;
|
|
225
|
+
/** Stay at `scaffolded` until {@link ProjectStateHost.release} (§3.1, §7). */
|
|
226
|
+
hold?: boolean;
|
|
227
|
+
/** Told of every failure the host survives: a watch error, a failed git run, a bad extension. */
|
|
228
|
+
onError?: (error: Error) => void;
|
|
229
|
+
/**
|
|
230
|
+
* Called before each step of a rename cascade runs (§9.1), counted from 0 in the order the host
|
|
231
|
+
* applies them, with the path the step changes; a throw fails that step and rolls back the ones
|
|
232
|
+
* before it. The conformance suite injects its failures here (§10.4).
|
|
233
|
+
*/
|
|
234
|
+
onRenameStep?: (step: number, path: string) => void | Promise<void>;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Where a subscription's events go. */
|
|
238
|
+
export interface ProjectStateSink {
|
|
239
|
+
/** Later events, in revision order, as the host appends them. */
|
|
240
|
+
events: (events: ProjectEvent[]) => void;
|
|
241
|
+
/** The host ended the subscription: a restart, a watcher recovery or close (§4.8). */
|
|
242
|
+
end?: () => void;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* What the host's graph knows about every document's references, for the usage query (§8, §12):
|
|
247
|
+
* each document's path and extracted references, and the asset mounts a rooted reference resolves
|
|
248
|
+
* through.
|
|
249
|
+
*/
|
|
250
|
+
export interface ProjectReferences {
|
|
251
|
+
documents: GraphDocument[];
|
|
252
|
+
mounts: readonly AssetMount[];
|
|
253
|
+
/** The file extensions the project's loaded formats parse, beside JSON and Jx Notation. */
|
|
254
|
+
extensions: readonly string[];
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** One open subscription. */
|
|
258
|
+
export interface ProjectStateSubscription {
|
|
259
|
+
response: SubscribeResponse;
|
|
260
|
+
close: () => void;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export interface ProjectStateHost {
|
|
264
|
+
readonly root: string;
|
|
265
|
+
/** The current epoch (§2.3). */
|
|
266
|
+
readonly epoch: string;
|
|
267
|
+
/** The newest revision. */
|
|
268
|
+
readonly rev: number;
|
|
269
|
+
readonly readiness: ReadinessState;
|
|
270
|
+
/** Answer a subscribe (§3.1) and stream every later event to `sink`. */
|
|
271
|
+
subscribe: (request: SubscribeRequest, sink: ProjectStateSink) => ProjectStateSubscription;
|
|
272
|
+
/** A conditional write (§5). */
|
|
273
|
+
write: (request: WriteRequest) => Promise<WriteResult>;
|
|
274
|
+
/** A conditional delete of a file or a directory (§5). */
|
|
275
|
+
delete: (request: DeleteRequest) => Promise<DeleteResult>;
|
|
276
|
+
/** Create a directory; its `fileAdded` carries `writeId` (§5). */
|
|
277
|
+
createDirectory: (path: string, writeId: string) => Promise<{ rev: number }>;
|
|
278
|
+
/**
|
|
279
|
+
* The rename cascade (§9): plan the move and every reference rewrite, then apply them from an
|
|
280
|
+
* outbox that rolls back on failure, answering what was done or why nothing was. Rejects only for
|
|
281
|
+
* a path that is not project-relative or leads outside the project.
|
|
282
|
+
*/
|
|
283
|
+
rename: (operation: RenameOperation) => Promise<RenameOperationResult>;
|
|
284
|
+
/** The whole state at the current revision (§3.1). */
|
|
285
|
+
snapshot: () => ProjectSnapshot;
|
|
286
|
+
/** The document id at `path` now, `null` when nothing indexed is there (§2.2). */
|
|
287
|
+
docIdAt: (path: string) => string | null;
|
|
288
|
+
/**
|
|
289
|
+
* The graph's documents and their references once the host is `indexed` (§7, §8), `null` before
|
|
290
|
+
* and while its watcher is degraded (§4.8): below `indexed` the graph is still being built, and a
|
|
291
|
+
* degraded watcher no longer follows the disk, so the usage query walks the tree instead.
|
|
292
|
+
*/
|
|
293
|
+
references: () => ProjectReferences | null;
|
|
294
|
+
/** Run an install; its writes carry its own write id and leave readiness where it was (§7). */
|
|
295
|
+
install: () => Promise<void>;
|
|
296
|
+
/** Let a host created with `hold` advance (§7). */
|
|
297
|
+
release: () => Promise<void>;
|
|
298
|
+
/** Start again over the same root: a new epoch, every subscription ended (§2.3, §4.8). */
|
|
299
|
+
restart: () => Promise<void>;
|
|
300
|
+
/**
|
|
301
|
+
* Resolve once the host has processed every change it has been told of and nothing has moved for
|
|
302
|
+
* `quietMs`: the watcher's reports, held removals, the git monitor's debounce.
|
|
303
|
+
*/
|
|
304
|
+
idle: (quietMs?: number) => Promise<void>;
|
|
305
|
+
close: () => Promise<void>;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// ─── Scope and classification (§2.2) ───────────────────────────────────────────────────────────
|
|
309
|
+
|
|
310
|
+
const IGNORED_SEGMENTS = new Set([
|
|
311
|
+
".git",
|
|
312
|
+
"node_modules",
|
|
313
|
+
"dist",
|
|
314
|
+
".jx",
|
|
315
|
+
".cache",
|
|
316
|
+
".devenv",
|
|
317
|
+
".direnv",
|
|
318
|
+
]);
|
|
319
|
+
const IGNORED_NAMES = new Set(["bun.lock", "bun.lockb"]);
|
|
320
|
+
/** The temporary file a write goes through (§5); never indexed, never reported. */
|
|
321
|
+
const TEMP_FILE = /\.jx-write-[\da-f-]{36}$/;
|
|
322
|
+
/** The lockfiles a fingerprint covers (§7); Bun's are outside the index scope. */
|
|
323
|
+
const LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "yarn.lock", "pnpm-lock.yaml"];
|
|
324
|
+
const MANIFEST = "package.json";
|
|
325
|
+
const FINGERPRINT_PATHS = new Set([MANIFEST, ...LOCKFILES]);
|
|
326
|
+
const MEDIA =
|
|
327
|
+
/\.(?:png|jpe?g|gif|svg|webp|avif|ico|bmp|tiff?|mp4|webm|ogg|mov|mp3|wav|flac|m4a|woff2?|ttf|otf|eot|pdf)$/i;
|
|
328
|
+
const KIND_BY_DIR = new Map<string, DocKind>([
|
|
329
|
+
["components", "component"],
|
|
330
|
+
["content", "content"],
|
|
331
|
+
["data", "data"],
|
|
332
|
+
["layouts", "layout"],
|
|
333
|
+
["pages", "page"],
|
|
334
|
+
]);
|
|
335
|
+
const UNRESOLVED_FORMATS = "unresolved";
|
|
336
|
+
/**
|
|
337
|
+
* The coarsest modification-time tick a project may sit on (FAT and exFAT keep two seconds). A size
|
|
338
|
+
* and time recorded within it of now can hold through a later edit, so they are not recorded
|
|
339
|
+
* (§2.4).
|
|
340
|
+
*/
|
|
341
|
+
const MTIME_TICK_MS = 2000;
|
|
342
|
+
const HASH_CHUNK_BYTES = 1024 * 1024;
|
|
343
|
+
const RENAME_RETRY_CODES = new Set(["EPERM", "EACCES", "EBUSY"]);
|
|
344
|
+
const WINDOWS_RENAME_RETRY_MS = [10, 50, 100, 250, 500];
|
|
345
|
+
|
|
346
|
+
/** A node error's `code`, when it has one. */
|
|
347
|
+
const errorCode = (error: Error): string | undefined =>
|
|
348
|
+
"code" in error && isString(error.code) ? error.code : undefined;
|
|
349
|
+
|
|
350
|
+
/** Whether a failed read or open means the path is gone, rather than that it cannot be read. */
|
|
351
|
+
const isMissing = (error: Error): boolean => {
|
|
352
|
+
const code = errorCode(error);
|
|
353
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
354
|
+
};
|
|
355
|
+
|
|
356
|
+
const CONFIG_PATHS: ReadonlySet<string> = new Set(PROJECT_FILE_NAMES);
|
|
357
|
+
const isConfigPath = (path: string): boolean => CONFIG_PATHS.has(path);
|
|
358
|
+
|
|
359
|
+
/** The ancestors of a project path, shallowest first. */
|
|
360
|
+
const parents = (path: string): string[] =>
|
|
361
|
+
path
|
|
362
|
+
.split("/")
|
|
363
|
+
.slice(0, -1)
|
|
364
|
+
.map((_, at, parts) => parts.slice(0, at + 1).join("/"));
|
|
365
|
+
|
|
366
|
+
/** The build output a configuration names, project-relative, `dist` when it names none (§2.2). */
|
|
367
|
+
function outDirOf(config: ProjectConfig | undefined): string {
|
|
368
|
+
const named = config?.build?.outDir;
|
|
369
|
+
if (!isString(named)) {
|
|
370
|
+
return "dist";
|
|
371
|
+
}
|
|
372
|
+
const out = named.replace(/^\.\//, "").replaceAll(/\/+$/g, "");
|
|
373
|
+
return out === "" || out === "." || out.startsWith("../") || out.startsWith("/") ? "dist" : out;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** The extension set a configuration names, as one comparable string (§7). */
|
|
377
|
+
function extensionSetOf(config: ProjectConfig | undefined): string {
|
|
378
|
+
const names = config?.extensions;
|
|
379
|
+
return JSON.stringify(names === undefined ? [] : [...new Set(names)].toSorted());
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** A root `tagName` naming a custom element: the tag a component definition declares. */
|
|
383
|
+
function componentTag(doc: JsonValue | undefined): string | null {
|
|
384
|
+
const tag = isJsonObject(doc) ? doc.tagName : undefined;
|
|
385
|
+
return isString(tag) && tag.includes("-") ? tag : null;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** A path's kind from its location alone (§2.2). */
|
|
389
|
+
function kindByLocation(path: string): DocKind {
|
|
390
|
+
const [top = ""] = path.split("/");
|
|
391
|
+
return path.includes("/") ? (KIND_BY_DIR.get(top) ?? "other") : "other";
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** What a document is and what it references, as far as the host can read it. */
|
|
395
|
+
interface Described {
|
|
396
|
+
kind: DocKind;
|
|
397
|
+
/** `null` when the host could not extract its references (§8.2). */
|
|
398
|
+
refs: DocumentRefs | null;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** A project path, checked: relative, forward slashes, no `.` or `..` segment. */
|
|
402
|
+
function checkPath(path: string): string {
|
|
403
|
+
const segments = path.split("/");
|
|
404
|
+
if (
|
|
405
|
+
path === "" ||
|
|
406
|
+
path.includes("\\") ||
|
|
407
|
+
segments.some((segment) => segment === "" || segment === "." || segment === "..")
|
|
408
|
+
) {
|
|
409
|
+
throw new TypeError(`Not a project-relative path: "${path}"`);
|
|
410
|
+
}
|
|
411
|
+
return path;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
const encoder = new TextEncoder();
|
|
415
|
+
const decoder = new TextDecoder();
|
|
416
|
+
const toBytes = (contents: string | Uint8Array): Uint8Array =>
|
|
417
|
+
contents instanceof Uint8Array ? contents : encoder.encode(contents);
|
|
418
|
+
|
|
419
|
+
// ─── The host ──────────────────────────────────────────────────────────────────────────────────
|
|
420
|
+
|
|
421
|
+
interface Entry {
|
|
422
|
+
docId: string;
|
|
423
|
+
isDir: boolean;
|
|
424
|
+
kind: DocKind;
|
|
425
|
+
hash?: ContentHash;
|
|
426
|
+
size?: number | undefined;
|
|
427
|
+
mtimeMs?: number | undefined;
|
|
428
|
+
indexed: boolean;
|
|
429
|
+
/** What the graph was given for this document; `undefined` before it was read. */
|
|
430
|
+
refs?: DocumentRefs | null;
|
|
431
|
+
/** The tag a component definition declares. */
|
|
432
|
+
defines: string | null;
|
|
433
|
+
/** Re-read at the next indexing: the format set changed under it. */
|
|
434
|
+
stale?: boolean;
|
|
435
|
+
/** An observed removal held for the pairing bound (§2.4). */
|
|
436
|
+
held?: ReturnType<typeof setTimeout> | undefined;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
interface Subscriber {
|
|
440
|
+
sink: ProjectStateSink;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Create a project state host over `options.root` and start it: the watcher is armed, the index
|
|
445
|
+
* scanned and the git summary read before this resolves, and the host then advances to `ready` on
|
|
446
|
+
* its own unless it was created with `hold`.
|
|
447
|
+
*/
|
|
448
|
+
export async function createProjectStateHost(
|
|
449
|
+
options: ProjectStateHostOptions,
|
|
450
|
+
): Promise<ProjectStateHost> {
|
|
451
|
+
const { root } = options;
|
|
452
|
+
const fs: ProjectStateFs = options.fs ?? nodeFs;
|
|
453
|
+
const watcherFactory = options.watcher ?? chokidarProjectWatcher;
|
|
454
|
+
const loadExtensions = options.extensions ?? loadInstalledFormats;
|
|
455
|
+
const installer = options.installer ?? installPackages;
|
|
456
|
+
const installedCheck = options.installed ?? dependenciesInstalled;
|
|
457
|
+
const resolveCollections = options.collections ?? sourceCollections;
|
|
458
|
+
const atomicSaveMs = options.atomicSaveMs ?? 100;
|
|
459
|
+
const stabilityMs = options.stabilityMs ?? 50;
|
|
460
|
+
const readLimit = options.readLimitBytes ?? 64 * 1024 * 1024;
|
|
461
|
+
const renameRetryMs =
|
|
462
|
+
options.renameRetryMs ?? (process.platform === "win32" ? WINDOWS_RENAME_RETRY_MS : []);
|
|
463
|
+
/* A removal is held from when the watcher reports it, and the add that pairs it is reported only
|
|
464
|
+
once the file holds still, so the bound is extended by that wait (§2.4). */
|
|
465
|
+
const holdMs = atomicSaveMs + stabilityMs + 50;
|
|
466
|
+
const report = (error: Error): void => {
|
|
467
|
+
if (options.onError) {
|
|
468
|
+
options.onError(error);
|
|
469
|
+
} else {
|
|
470
|
+
console.error(`[project-state] ${error.message}`);
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
|
|
474
|
+
/** A queued step's failure, which nothing awaits: reported, never thrown. */
|
|
475
|
+
const reportRejection = (error: Error): void => {
|
|
476
|
+
report(toError(error));
|
|
477
|
+
};
|
|
478
|
+
|
|
479
|
+
let log: ProjectEventLog = createMemoryEventLog({ epoch: randomUUID() });
|
|
480
|
+
let ledger: EchoLedger = createEchoLedger();
|
|
481
|
+
const index = new Map<string, Entry>();
|
|
482
|
+
const subscribers = new Set<Subscriber>();
|
|
483
|
+
const holds = new Set<string>();
|
|
484
|
+
let graph: DependencyGraph = createDependencyGraph();
|
|
485
|
+
let graphBuilt = false;
|
|
486
|
+
/** Each path's content types, as last given to the graph (`setEntryTypes`). */
|
|
487
|
+
let entryTypes = new Map<string, string>();
|
|
488
|
+
let readiness: ReadinessState = "scaffolded";
|
|
489
|
+
let held = options.hold === true;
|
|
490
|
+
let fingerprint: string | null = null;
|
|
491
|
+
let extensionSet: string | null = null;
|
|
492
|
+
let formats: ProjectFormats | null = null;
|
|
493
|
+
let formatsToken = UNRESOLVED_FORMATS;
|
|
494
|
+
let components: string[] = [];
|
|
495
|
+
let config: ProjectConfig | undefined;
|
|
496
|
+
let outDir = "dist";
|
|
497
|
+
let realRoot = root;
|
|
498
|
+
let watcher: ProjectWatchHandle | null = null;
|
|
499
|
+
let git: GitMonitor | null = null;
|
|
500
|
+
let degraded = false;
|
|
501
|
+
let installing: string | null = null;
|
|
502
|
+
let deferred: [ProjectWatchEvent, string][] = [];
|
|
503
|
+
let lastActivity = 0;
|
|
504
|
+
let closed = false;
|
|
505
|
+
let generation = 0;
|
|
506
|
+
|
|
507
|
+
// ── The queue ──
|
|
508
|
+
let chain: Promise<unknown> = Promise.resolve();
|
|
509
|
+
let queued = 0;
|
|
510
|
+
|
|
511
|
+
/** Run `task` after every earlier one, so each is atomic with respect to the rest (§5). */
|
|
512
|
+
const exclusive = <T>(task: () => Promise<T> | T): Promise<T> => {
|
|
513
|
+
queued += 1;
|
|
514
|
+
const run = chain.then(task);
|
|
515
|
+
chain = run.then(
|
|
516
|
+
() => {
|
|
517
|
+
queued -= 1;
|
|
518
|
+
},
|
|
519
|
+
() => {
|
|
520
|
+
queued -= 1;
|
|
521
|
+
},
|
|
522
|
+
);
|
|
523
|
+
return run;
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
// ── Paths ──
|
|
527
|
+
const toAbs = (path: string): string => join(root, ...path.split("/"));
|
|
528
|
+
const toRel = (path: string): string => relative(root, path).split(sep).join("/");
|
|
529
|
+
|
|
530
|
+
const inScope = (path: string): boolean => {
|
|
531
|
+
const segments = path.split("/");
|
|
532
|
+
const name = segments.at(-1)!;
|
|
533
|
+
return (
|
|
534
|
+
path !== "" &&
|
|
535
|
+
!segments.some((segment) => IGNORED_SEGMENTS.has(segment)) &&
|
|
536
|
+
!IGNORED_NAMES.has(name) &&
|
|
537
|
+
!TEMP_FILE.test(name) &&
|
|
538
|
+
path !== outDir &&
|
|
539
|
+
!path.startsWith(`${outDir}/`)
|
|
540
|
+
);
|
|
541
|
+
};
|
|
542
|
+
|
|
543
|
+
/** What the watcher skips: the index scope's exclusions, except the lockfiles (§7). */
|
|
544
|
+
const watchIgnored = (path: string): boolean => {
|
|
545
|
+
const rel = toRel(path);
|
|
546
|
+
if (rel === "" || rel.startsWith("..")) {
|
|
547
|
+
return false;
|
|
548
|
+
}
|
|
549
|
+
const segments = rel.split("/");
|
|
550
|
+
return (
|
|
551
|
+
segments.some((segment) => IGNORED_SEGMENTS.has(segment)) ||
|
|
552
|
+
TEMP_FILE.test(segments.at(-1)!) ||
|
|
553
|
+
rel === outDir ||
|
|
554
|
+
rel.startsWith(`${outDir}/`)
|
|
555
|
+
);
|
|
556
|
+
};
|
|
557
|
+
|
|
558
|
+
const statOrNull = async (path: string): Promise<Stats | null> => {
|
|
559
|
+
try {
|
|
560
|
+
return await fs.stat(toAbs(path));
|
|
561
|
+
} catch {
|
|
562
|
+
return null;
|
|
563
|
+
}
|
|
564
|
+
};
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* A request's path, checked to be project-relative and to stay inside the root through any link
|
|
568
|
+
* on the way: its nearest existing ancestor must resolve inside the root.
|
|
569
|
+
*/
|
|
570
|
+
const contained = async (requested: string): Promise<string> => {
|
|
571
|
+
const path = checkPath(requested);
|
|
572
|
+
for (const at of [path, ...parents(path).toReversed(), ""]) {
|
|
573
|
+
let real: string;
|
|
574
|
+
try {
|
|
575
|
+
real = await fs.realpath(at === "" ? root : toAbs(at));
|
|
576
|
+
} catch {
|
|
577
|
+
continue;
|
|
578
|
+
}
|
|
579
|
+
if (real !== realRoot && !real.startsWith(`${realRoot}${sep}`)) {
|
|
580
|
+
throw new TypeError(`"${path}" leads outside the project`);
|
|
581
|
+
}
|
|
582
|
+
break;
|
|
583
|
+
}
|
|
584
|
+
return path;
|
|
585
|
+
};
|
|
586
|
+
|
|
587
|
+
/** A path's stats, following a link only when it resolves inside the root (§2.2). */
|
|
588
|
+
const statInside = async (path: string): Promise<Stats | null> => {
|
|
589
|
+
try {
|
|
590
|
+
const real = await fs.realpath(toAbs(path));
|
|
591
|
+
if (real !== realRoot && !real.startsWith(`${realRoot}${sep}`)) {
|
|
592
|
+
return null;
|
|
593
|
+
}
|
|
594
|
+
return await fs.stat(toAbs(path));
|
|
595
|
+
} catch {
|
|
596
|
+
return null;
|
|
597
|
+
}
|
|
598
|
+
};
|
|
599
|
+
|
|
600
|
+
/** A file's bytes, `null` when it is gone; any other failure is the caller's (§5). */
|
|
601
|
+
const readOrNull = async (path: string): Promise<Uint8Array | null> => {
|
|
602
|
+
try {
|
|
603
|
+
return await fs.readFile(toAbs(path));
|
|
604
|
+
} catch (error) {
|
|
605
|
+
if (isMissing(toError(error))) {
|
|
606
|
+
return null;
|
|
607
|
+
}
|
|
608
|
+
throw error;
|
|
609
|
+
}
|
|
610
|
+
};
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* A file the host reads for itself (the configuration, readiness's inputs); a failure is
|
|
614
|
+
* reported.
|
|
615
|
+
*/
|
|
616
|
+
const readReported = async (path: string): Promise<Uint8Array | null> => {
|
|
617
|
+
try {
|
|
618
|
+
return await readOrNull(path);
|
|
619
|
+
} catch (error) {
|
|
620
|
+
report(toError(error));
|
|
621
|
+
return null;
|
|
622
|
+
}
|
|
623
|
+
};
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* A file's hash, read as a stream so no file is held whole whatever its size (§2.1); `null` when
|
|
627
|
+
* it is gone, and any other failure is the caller's.
|
|
628
|
+
*/
|
|
629
|
+
const hashOf = async (path: string): Promise<ContentHash | null> => {
|
|
630
|
+
let handle: FileHandle;
|
|
631
|
+
try {
|
|
632
|
+
handle = await fs.open(toAbs(path));
|
|
633
|
+
} catch (error) {
|
|
634
|
+
if (isMissing(toError(error))) {
|
|
635
|
+
return null;
|
|
636
|
+
}
|
|
637
|
+
throw error;
|
|
638
|
+
}
|
|
639
|
+
try {
|
|
640
|
+
const digest = createHash("sha256");
|
|
641
|
+
const chunk = new Uint8Array(HASH_CHUNK_BYTES);
|
|
642
|
+
for (;;) {
|
|
643
|
+
const { bytesRead } = await handle.read(chunk, 0, HASH_CHUNK_BYTES, null);
|
|
644
|
+
if (bytesRead === 0) {
|
|
645
|
+
return `sha256-${digest.digest("base64")}`;
|
|
646
|
+
}
|
|
647
|
+
digest.update(chunk.subarray(0, bytesRead));
|
|
648
|
+
}
|
|
649
|
+
} finally {
|
|
650
|
+
await handle.close();
|
|
651
|
+
}
|
|
652
|
+
};
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* A file's hash, with its bytes when classifying it reads them: a media file, a stylesheet and a
|
|
656
|
+
* file over the read limit are classified by name and only hashed (§2.2). `null` when it is
|
|
657
|
+
* gone.
|
|
658
|
+
*/
|
|
659
|
+
const load = async (
|
|
660
|
+
path: string,
|
|
661
|
+
size: number,
|
|
662
|
+
): Promise<{ bytes: Uint8Array | null; hash: ContentHash } | null> => {
|
|
663
|
+
if (MEDIA.test(path) || extname(path).toLowerCase() === ".css" || size > readLimit) {
|
|
664
|
+
const hash = await hashOf(path);
|
|
665
|
+
return hash === null ? null : { bytes: null, hash };
|
|
666
|
+
}
|
|
667
|
+
const bytes = await readOrNull(path);
|
|
668
|
+
return bytes === null ? null : { bytes, hash: await contentHash(bytes) };
|
|
669
|
+
};
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* The size and time to record with a hash, taken before the bytes were read: none when the time
|
|
673
|
+
* is within a tick of now, since an edit in the same tick could leave both unchanged (§2.4).
|
|
674
|
+
*/
|
|
675
|
+
const statFields = (stats: Stats | null): Pick<Entry, "mtimeMs" | "size"> =>
|
|
676
|
+
stats === null || stats.mtimeMs > Date.now() - MTIME_TICK_MS
|
|
677
|
+
? { mtimeMs: undefined, size: undefined }
|
|
678
|
+
: { mtimeMs: stats.mtimeMs, size: stats.size };
|
|
679
|
+
|
|
680
|
+
// ── Events ──
|
|
681
|
+
const emit = (init: ProjectEventInit): ProjectEvent => {
|
|
682
|
+
const event = log.append(init);
|
|
683
|
+
for (const sub of subscribers) {
|
|
684
|
+
try {
|
|
685
|
+
sub.sink.events([event]);
|
|
686
|
+
} catch (error) {
|
|
687
|
+
report(toError(error));
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
return event;
|
|
691
|
+
};
|
|
692
|
+
|
|
693
|
+
const setReadiness = (state: ReadinessState): void => {
|
|
694
|
+
if (state !== readiness) {
|
|
695
|
+
readiness = state;
|
|
696
|
+
emit({ origin: "external", state, type: "readiness" });
|
|
697
|
+
}
|
|
698
|
+
};
|
|
699
|
+
|
|
700
|
+
const emitInvalidations = (
|
|
701
|
+
cause: string,
|
|
702
|
+
invalidations: readonly Invalidation[],
|
|
703
|
+
origin: EventOrigin,
|
|
704
|
+
): void => {
|
|
705
|
+
for (const event of invalidationEvents(cause, invalidations, origin)) {
|
|
706
|
+
emit(event);
|
|
707
|
+
}
|
|
708
|
+
};
|
|
709
|
+
|
|
710
|
+
const updateComponents = (origin: EventOrigin): void => {
|
|
711
|
+
const tags = [
|
|
712
|
+
...new Set([...index.values()].flatMap((entry) => entry.defines ?? [])),
|
|
713
|
+
].toSorted();
|
|
714
|
+
if (JSON.stringify(tags) !== JSON.stringify(components)) {
|
|
715
|
+
components = tags;
|
|
716
|
+
emit({ origin, tags, type: "componentsChanged" });
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
|
|
720
|
+
// ── Reading documents ──
|
|
721
|
+
const readConfig = (path: string, bytes: Uint8Array | null): ProjectConfig | undefined => {
|
|
722
|
+
if (bytes === null) {
|
|
723
|
+
return undefined;
|
|
724
|
+
}
|
|
725
|
+
const read = parseProjectFile(path, decoder.decode(bytes));
|
|
726
|
+
return "config" in read ? read.config : undefined;
|
|
727
|
+
};
|
|
728
|
+
|
|
729
|
+
/** Classify a document and extract its references (§2.2, §8). */
|
|
730
|
+
const describe = async (path: string, bytes: Uint8Array | null): Promise<Described> => {
|
|
731
|
+
if (isConfigPath(path)) {
|
|
732
|
+
const read = readConfig(path, bytes);
|
|
733
|
+
/* Its references are extracted like any document's, so the usage query sees the layout and
|
|
734
|
+
the files it names; the graph takes the configuration's own edges through `configure`. */
|
|
735
|
+
return {
|
|
736
|
+
kind: "project-config",
|
|
737
|
+
// SAFETY: a parsed project file is a JSON object; `ProjectConfig` only names its members.
|
|
738
|
+
refs: read === undefined ? null : extractRefs(read as JsonValue, "project-config"),
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
const extension = extname(path).toLowerCase();
|
|
742
|
+
if (extension === ".css") {
|
|
743
|
+
return { kind: "style", refs: NO_REFS };
|
|
744
|
+
}
|
|
745
|
+
if (MEDIA.test(path)) {
|
|
746
|
+
return { kind: "media", refs: NO_REFS };
|
|
747
|
+
}
|
|
748
|
+
if (bytes === null) {
|
|
749
|
+
// Too large to read whole: listed and hashed, its references unread (§8.2).
|
|
750
|
+
return { kind: kindByLocation(path), refs: null };
|
|
751
|
+
}
|
|
752
|
+
const text = decoder.decode(bytes);
|
|
753
|
+
let doc: JsonValue;
|
|
754
|
+
try {
|
|
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;
|
|
758
|
+
} else if (extension === ".jxn") {
|
|
759
|
+
const document = parseJxn(text);
|
|
760
|
+
doc = isJsonObject(document) ? document : null;
|
|
761
|
+
} else if (formats === null) {
|
|
762
|
+
// A format an extension may register is classified only once they are loaded (§2.2).
|
|
763
|
+
return { kind: "other", refs: null };
|
|
764
|
+
} else if (formats.extensions.includes(extension)) {
|
|
765
|
+
doc = await formats.parse(extension, text);
|
|
766
|
+
} else {
|
|
767
|
+
return { kind: kindByLocation(path), refs: NO_REFS };
|
|
768
|
+
}
|
|
769
|
+
} catch {
|
|
770
|
+
return { kind: kindByLocation(path), refs: null };
|
|
771
|
+
}
|
|
772
|
+
const kind = componentTag(doc) === null ? kindByLocation(path) : "component";
|
|
773
|
+
return { kind, refs: extractRefs(doc, kind) };
|
|
774
|
+
};
|
|
775
|
+
|
|
776
|
+
/** What the graph reads from the configuration and the collection loader (§8). */
|
|
777
|
+
const graphConfig = (
|
|
778
|
+
collections: Readonly<Record<string, readonly string[]>>,
|
|
779
|
+
): DependencyGraphConfig => {
|
|
780
|
+
const layout = config?.defaults?.layout;
|
|
781
|
+
return {
|
|
782
|
+
collections,
|
|
783
|
+
defaultLayout: isString(layout) ? layout : null,
|
|
784
|
+
imports: config?.imports ?? {},
|
|
785
|
+
mounts: formats?.mounts ?? [],
|
|
786
|
+
};
|
|
787
|
+
};
|
|
788
|
+
|
|
789
|
+
const indexedFiles = (): string[] =>
|
|
790
|
+
[...index].flatMap(([path, entry]) => (entry.isDir ? [] : [path]));
|
|
791
|
+
|
|
792
|
+
const collectionsFor = async (
|
|
793
|
+
files: readonly string[],
|
|
794
|
+
with_: ProjectConfig | undefined,
|
|
795
|
+
): Promise<Readonly<Record<string, readonly string[]>>> => {
|
|
796
|
+
try {
|
|
797
|
+
return await resolveCollections({ config: with_, files, root });
|
|
798
|
+
} catch (error) {
|
|
799
|
+
report(toError(error));
|
|
800
|
+
return {};
|
|
801
|
+
}
|
|
802
|
+
};
|
|
803
|
+
|
|
804
|
+
/** Each path's content types, from the loader's lists. */
|
|
805
|
+
const typesByPath = (
|
|
806
|
+
collections: Readonly<Record<string, readonly string[]>>,
|
|
807
|
+
): Map<string, string> => {
|
|
808
|
+
const byPath = new Map<string, string[]>();
|
|
809
|
+
for (const [type, paths] of Object.entries(collections)) {
|
|
810
|
+
for (const path of paths) {
|
|
811
|
+
byPath.set(path, [...(byPath.get(path) ?? []), type]);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
return new Map([...byPath].map(([path, types]) => [path, JSON.stringify(types.toSorted())]));
|
|
815
|
+
};
|
|
816
|
+
|
|
817
|
+
/**
|
|
818
|
+
* Tell the graph every path whose collection membership moved, before the change's `update`,
|
|
819
|
+
* `remove` or `relabel` (§8).
|
|
820
|
+
*/
|
|
821
|
+
const applyEntryTypes = (collections: Readonly<Record<string, readonly string[]>>): void => {
|
|
822
|
+
const next = typesByPath(collections);
|
|
823
|
+
for (const path of new Set([...entryTypes.keys(), ...next.keys()])) {
|
|
824
|
+
const types = next.get(path) ?? "[]";
|
|
825
|
+
if (types !== (entryTypes.get(path) ?? "[]")) {
|
|
826
|
+
// SAFETY: written by typesByPath as a JSON array of strings.
|
|
827
|
+
graph.setEntryTypes(path, JSON.parse(types) as string[]);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
entryTypes = next;
|
|
831
|
+
};
|
|
832
|
+
|
|
833
|
+
// ── Changing the index (each step's mutations and events share one synchronous segment) ──
|
|
834
|
+
const mintDir = (path: string, origin: EventOrigin): void => {
|
|
835
|
+
const docId = randomUUID();
|
|
836
|
+
index.set(path, { defines: null, docId, indexed: true, isDir: true, kind: "other" });
|
|
837
|
+
emit({ docId, isDir: true, origin, path, type: "fileAdded" });
|
|
838
|
+
};
|
|
839
|
+
|
|
840
|
+
/** Add `path` and every ancestor the index does not hold yet. */
|
|
841
|
+
const ensureDirs = (path: string, origin: EventOrigin): void => {
|
|
842
|
+
for (const dir of [...parents(path), path]) {
|
|
843
|
+
if (inScope(dir) && !index.has(dir)) {
|
|
844
|
+
mintDir(dir, origin);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
};
|
|
848
|
+
|
|
849
|
+
const cancelHold = (path: string, entry: Entry): void => {
|
|
850
|
+
if (entry.held !== undefined) {
|
|
851
|
+
clearTimeout(entry.held);
|
|
852
|
+
entry.held = undefined;
|
|
853
|
+
holds.delete(path);
|
|
854
|
+
}
|
|
855
|
+
};
|
|
856
|
+
|
|
857
|
+
/**
|
|
858
|
+
* Put a file's new bytes into the index and append its events: the file event, its `docChanged`,
|
|
859
|
+
* the configuration's event, the invalidations, and the component set (§4).
|
|
860
|
+
*/
|
|
861
|
+
const applyFile = async (
|
|
862
|
+
path: string,
|
|
863
|
+
bytes: Uint8Array | null,
|
|
864
|
+
hash: ContentHash,
|
|
865
|
+
stats: Stats | null,
|
|
866
|
+
origin: EventOrigin,
|
|
867
|
+
): Promise<ProjectEvent> => {
|
|
868
|
+
const described = await describe(path, bytes);
|
|
869
|
+
const isConfig = isConfigPath(path);
|
|
870
|
+
const nextConfig = isConfig ? readConfig(path, bytes) : config;
|
|
871
|
+
const collections = graphBuilt
|
|
872
|
+
? await collectionsFor([...new Set([...indexedFiles(), path])], nextConfig)
|
|
873
|
+
: null;
|
|
874
|
+
// ── one synchronous segment from here ──
|
|
875
|
+
const existing = index.get(path);
|
|
876
|
+
let entry: Entry;
|
|
877
|
+
let event: ProjectEvent;
|
|
878
|
+
const fields = {
|
|
879
|
+
...statFields(stats),
|
|
880
|
+
defines: described.refs?.defines ?? null,
|
|
881
|
+
hash,
|
|
882
|
+
indexed: described.refs !== null,
|
|
883
|
+
kind: described.kind,
|
|
884
|
+
refs: described.refs,
|
|
885
|
+
stale: false,
|
|
886
|
+
};
|
|
887
|
+
if (existing !== undefined && !existing.isDir) {
|
|
888
|
+
entry = existing;
|
|
889
|
+
cancelHold(path, entry);
|
|
890
|
+
Object.assign(entry, fields);
|
|
891
|
+
event = emit({ docId: entry.docId, hash, origin, path, type: "fileChanged" });
|
|
892
|
+
} else {
|
|
893
|
+
ensureDirs(parents(path).at(-1) ?? "", origin);
|
|
894
|
+
entry = { ...fields, docId: randomUUID(), isDir: false };
|
|
895
|
+
index.set(path, entry);
|
|
896
|
+
event = emit({ docId: entry.docId, hash, isDir: false, origin, path, type: "fileAdded" });
|
|
897
|
+
}
|
|
898
|
+
const { docId } = entry;
|
|
899
|
+
emit({
|
|
900
|
+
docId,
|
|
901
|
+
hash,
|
|
902
|
+
indexed: entry.indexed,
|
|
903
|
+
kind: entry.kind,
|
|
904
|
+
origin,
|
|
905
|
+
path,
|
|
906
|
+
type: "docChanged",
|
|
907
|
+
});
|
|
908
|
+
if (isConfig) {
|
|
909
|
+
config = nextConfig;
|
|
910
|
+
emit({ hash, origin, path, type: "projectConfigChanged" });
|
|
911
|
+
}
|
|
912
|
+
if (graphBuilt && collections !== null) {
|
|
913
|
+
if (isConfig) {
|
|
914
|
+
graph.configure(graphConfig(collections));
|
|
915
|
+
entryTypes = typesByPath(collections);
|
|
916
|
+
} else {
|
|
917
|
+
applyEntryTypes(collections);
|
|
918
|
+
}
|
|
919
|
+
emitInvalidations(docId, graph.update(docId, path, described.refs), origin);
|
|
920
|
+
}
|
|
921
|
+
updateComponents(origin);
|
|
922
|
+
git?.schedule();
|
|
923
|
+
return event;
|
|
924
|
+
};
|
|
925
|
+
|
|
926
|
+
/** Drop the echo ledger's pending writes at `path` and beneath it: nothing there to echo. */
|
|
927
|
+
const forgetBeneath = (path: string): void => {
|
|
928
|
+
for (const key of ledger.pending()) {
|
|
929
|
+
if (key === path || key.startsWith(`${path}/`)) {
|
|
930
|
+
ledger.forget(key);
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
};
|
|
934
|
+
|
|
935
|
+
/** Remove `path`, and everything beneath it, as one `fileRemoved` (§4.2). */
|
|
936
|
+
const removePath = async (path: string, origin: EventOrigin): Promise<ProjectEvent | null> => {
|
|
937
|
+
const entry = index.get(path);
|
|
938
|
+
if (entry === undefined) {
|
|
939
|
+
return null;
|
|
940
|
+
}
|
|
941
|
+
const gone = [...index].filter(([key]) => key === path || key.startsWith(`${path}/`));
|
|
942
|
+
const goneSet = new Set(gone.map(([key]) => key));
|
|
943
|
+
const configGone = gone.some(([key]) => isConfigPath(key));
|
|
944
|
+
const collections = graphBuilt
|
|
945
|
+
? await collectionsFor(
|
|
946
|
+
indexedFiles().filter((file) => !goneSet.has(file)),
|
|
947
|
+
configGone ? undefined : config,
|
|
948
|
+
)
|
|
949
|
+
: null;
|
|
950
|
+
// ── one synchronous segment from here ──
|
|
951
|
+
for (const [key, removed] of gone) {
|
|
952
|
+
cancelHold(key, removed);
|
|
953
|
+
index.delete(key);
|
|
954
|
+
}
|
|
955
|
+
forgetBeneath(path);
|
|
956
|
+
const event = emit({
|
|
957
|
+
docId: entry.docId,
|
|
958
|
+
isDir: entry.isDir,
|
|
959
|
+
origin,
|
|
960
|
+
path,
|
|
961
|
+
type: "fileRemoved",
|
|
962
|
+
});
|
|
963
|
+
if (configGone) {
|
|
964
|
+
config = undefined;
|
|
965
|
+
}
|
|
966
|
+
if (graphBuilt && collections !== null) {
|
|
967
|
+
if (configGone) {
|
|
968
|
+
// The default layout and the import map went with it (§8).
|
|
969
|
+
graph.configure(graphConfig(collections));
|
|
970
|
+
entryTypes = typesByPath(collections);
|
|
971
|
+
} else {
|
|
972
|
+
applyEntryTypes(collections);
|
|
973
|
+
}
|
|
974
|
+
for (const [, removed] of gone) {
|
|
975
|
+
if (!removed.isDir) {
|
|
976
|
+
emitInvalidations(removed.docId, graph.remove(removed.docId), origin);
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
updateComponents(origin);
|
|
981
|
+
git?.schedule();
|
|
982
|
+
return event;
|
|
983
|
+
};
|
|
984
|
+
|
|
985
|
+
/** A held removal at `from` and an add at `to` with its bytes: one move (§4.2). */
|
|
986
|
+
const applyMove = async (
|
|
987
|
+
from: string,
|
|
988
|
+
to: string,
|
|
989
|
+
bytes: Uint8Array | null,
|
|
990
|
+
stats: Stats,
|
|
991
|
+
): Promise<void> => {
|
|
992
|
+
const entry = index.get(from)!;
|
|
993
|
+
const described = await describe(to, bytes);
|
|
994
|
+
const collections = graphBuilt
|
|
995
|
+
? await collectionsFor([...indexedFiles().filter((file) => file !== from), to], config)
|
|
996
|
+
: null;
|
|
997
|
+
// ── one synchronous segment from here ──
|
|
998
|
+
cancelHold(from, entry);
|
|
999
|
+
index.delete(from);
|
|
1000
|
+
ensureDirs(parents(to).at(-1) ?? "", "external");
|
|
1001
|
+
index.set(to, entry);
|
|
1002
|
+
Object.assign(entry, statFields(stats));
|
|
1003
|
+
const { docId } = entry;
|
|
1004
|
+
emit({ docId, from, isDir: false, origin: "external", to, type: "fileRenamed" });
|
|
1005
|
+
const reclassified = described.kind !== entry.kind;
|
|
1006
|
+
if (reclassified) {
|
|
1007
|
+
Object.assign(entry, {
|
|
1008
|
+
defines: described.refs?.defines ?? null,
|
|
1009
|
+
indexed: described.refs !== null,
|
|
1010
|
+
kind: described.kind,
|
|
1011
|
+
refs: described.refs,
|
|
1012
|
+
});
|
|
1013
|
+
emit({
|
|
1014
|
+
docId,
|
|
1015
|
+
hash: entry.hash!,
|
|
1016
|
+
indexed: entry.indexed,
|
|
1017
|
+
kind: entry.kind,
|
|
1018
|
+
origin: "external",
|
|
1019
|
+
path: to,
|
|
1020
|
+
type: "docChanged",
|
|
1021
|
+
});
|
|
1022
|
+
}
|
|
1023
|
+
if (graphBuilt && collections !== null) {
|
|
1024
|
+
applyEntryTypes(collections);
|
|
1025
|
+
emitInvalidations(
|
|
1026
|
+
docId,
|
|
1027
|
+
reclassified ? graph.update(docId, to, described.refs) : graph.relabel(docId, to),
|
|
1028
|
+
"external",
|
|
1029
|
+
);
|
|
1030
|
+
}
|
|
1031
|
+
updateComponents("external");
|
|
1032
|
+
git?.schedule();
|
|
1033
|
+
};
|
|
1034
|
+
|
|
1035
|
+
// ── Readiness (§7) ──
|
|
1036
|
+
const readManifest = async (): Promise<JsonObject | null> => {
|
|
1037
|
+
const bytes = await readReported(MANIFEST);
|
|
1038
|
+
if (bytes === null) {
|
|
1039
|
+
return null;
|
|
1040
|
+
}
|
|
1041
|
+
try {
|
|
1042
|
+
// SAFETY: JSON.parse without a reviver yields a JSON value; its `any` says no more.
|
|
1043
|
+
const value = JSON.parse(decoder.decode(bytes)) as JsonValue;
|
|
1044
|
+
return isJsonObject(value) ? value : null;
|
|
1045
|
+
} catch {
|
|
1046
|
+
return null;
|
|
1047
|
+
}
|
|
1048
|
+
};
|
|
1049
|
+
|
|
1050
|
+
/** The lockfiles' hashes and the manifest's dependency fields, as one string (§7). */
|
|
1051
|
+
const currentFingerprint = async (): Promise<string> => {
|
|
1052
|
+
const manifest = await readManifest();
|
|
1053
|
+
const locks: (ContentHash | null)[] = [];
|
|
1054
|
+
for (const path of LOCKFILES) {
|
|
1055
|
+
const bytes = await readReported(path);
|
|
1056
|
+
locks.push(bytes === null ? null : await contentHash(bytes));
|
|
1057
|
+
}
|
|
1058
|
+
return JSON.stringify({
|
|
1059
|
+
deps: DEPENDENCY_FIELDS.map((field) => manifest?.[field] ?? null),
|
|
1060
|
+
locks,
|
|
1061
|
+
});
|
|
1062
|
+
};
|
|
1063
|
+
|
|
1064
|
+
const schedulePrepare = (): void => {
|
|
1065
|
+
void exclusive(() => prepare()).catch(reportRejection);
|
|
1066
|
+
};
|
|
1067
|
+
|
|
1068
|
+
/** Move back to `scaffolded` when a dependency input's fingerprint changed (§7). */
|
|
1069
|
+
const checkFingerprint = async (path: string, origin: EventOrigin): Promise<void> => {
|
|
1070
|
+
if (!FINGERPRINT_PATHS.has(path) || (origin !== "external" && origin.writeId === installing)) {
|
|
1071
|
+
return;
|
|
1072
|
+
}
|
|
1073
|
+
const current = await currentFingerprint();
|
|
1074
|
+
if (fingerprint === null) {
|
|
1075
|
+
schedulePrepare();
|
|
1076
|
+
} else if (current !== fingerprint) {
|
|
1077
|
+
setReadiness("scaffolded");
|
|
1078
|
+
schedulePrepare();
|
|
1079
|
+
}
|
|
1080
|
+
};
|
|
1081
|
+
|
|
1082
|
+
/** What a configuration change can move beyond its own events: readiness and the scope. */
|
|
1083
|
+
const checkConfig = async (): Promise<void> => {
|
|
1084
|
+
const set = extensionSetOf(config);
|
|
1085
|
+
if (extensionSet !== null && set !== extensionSet) {
|
|
1086
|
+
extensionSet = set;
|
|
1087
|
+
if (readinessAtLeast(readiness, "extensions-resolved")) {
|
|
1088
|
+
setReadiness("installed");
|
|
1089
|
+
}
|
|
1090
|
+
schedulePrepare();
|
|
1091
|
+
}
|
|
1092
|
+
const nextOut = outDirOf(config);
|
|
1093
|
+
if (nextOut !== outDir) {
|
|
1094
|
+
outDir = nextOut;
|
|
1095
|
+
await reconcile();
|
|
1096
|
+
}
|
|
1097
|
+
};
|
|
1098
|
+
|
|
1099
|
+
/** Follow-up checks after a change at `path`, outside its synchronous segment. */
|
|
1100
|
+
const afterChange = async (path: string, origin: EventOrigin): Promise<void> => {
|
|
1101
|
+
if (isConfigPath(path)) {
|
|
1102
|
+
await checkConfig();
|
|
1103
|
+
}
|
|
1104
|
+
await checkFingerprint(path, origin);
|
|
1105
|
+
};
|
|
1106
|
+
|
|
1107
|
+
const formatsTokenOf = async (set: string, loaded: ProjectFormats): Promise<string> =>
|
|
1108
|
+
contentHash(JSON.stringify({ extensions: set, formats: [...loaded.extensions].toSorted() }));
|
|
1109
|
+
|
|
1110
|
+
/** Hash, classify and extract every file not yet indexed, then build the graph (§3.1, §8). */
|
|
1111
|
+
const indexAll = async (): Promise<void> => {
|
|
1112
|
+
// No file's bytes outlive its own iteration: only what was read from them is kept.
|
|
1113
|
+
const read: [string, Entry, Stats, ContentHash, Described][] = [];
|
|
1114
|
+
for (const [path, entry] of index) {
|
|
1115
|
+
if (entry.isDir || (entry.hash !== undefined && entry.indexed && entry.stale !== true)) {
|
|
1116
|
+
continue;
|
|
1117
|
+
}
|
|
1118
|
+
const stats = await statOrNull(path);
|
|
1119
|
+
let loaded: Awaited<ReturnType<typeof load>> = null;
|
|
1120
|
+
try {
|
|
1121
|
+
loaded = stats === null ? null : await load(path, stats.size);
|
|
1122
|
+
} catch (error) {
|
|
1123
|
+
// Listed but unreadable: it stays unhashed, and a write over it is refused (§5).
|
|
1124
|
+
report(toError(error));
|
|
1125
|
+
}
|
|
1126
|
+
if (stats === null || loaded === null) {
|
|
1127
|
+
// Gone since it was listed (the watcher's removal follows), or unreadable.
|
|
1128
|
+
entry.stale = false;
|
|
1129
|
+
continue;
|
|
1130
|
+
}
|
|
1131
|
+
read.push([path, entry, stats, loaded.hash, await describe(path, loaded.bytes)]);
|
|
1132
|
+
}
|
|
1133
|
+
const collections = await collectionsFor(indexedFiles(), config);
|
|
1134
|
+
// ── one synchronous segment from here ──
|
|
1135
|
+
for (const [path, entry, stats, hash, described] of read) {
|
|
1136
|
+
const indexed = described.refs !== null;
|
|
1137
|
+
const changed =
|
|
1138
|
+
entry.hash !== hash || entry.kind !== described.kind || entry.indexed !== indexed;
|
|
1139
|
+
Object.assign(entry, {
|
|
1140
|
+
...statFields(stats),
|
|
1141
|
+
defines: described.refs?.defines ?? null,
|
|
1142
|
+
hash,
|
|
1143
|
+
indexed,
|
|
1144
|
+
kind: described.kind,
|
|
1145
|
+
refs: described.refs,
|
|
1146
|
+
stale: false,
|
|
1147
|
+
});
|
|
1148
|
+
if (changed) {
|
|
1149
|
+
emit({
|
|
1150
|
+
docId: entry.docId,
|
|
1151
|
+
hash,
|
|
1152
|
+
indexed,
|
|
1153
|
+
kind: entry.kind,
|
|
1154
|
+
origin: "external",
|
|
1155
|
+
path,
|
|
1156
|
+
type: "docChanged",
|
|
1157
|
+
});
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
graph = createDependencyGraph();
|
|
1161
|
+
graph.configure(graphConfig(collections));
|
|
1162
|
+
entryTypes = typesByPath(collections);
|
|
1163
|
+
for (const [path, entry] of index) {
|
|
1164
|
+
if (!entry.isDir && entry.refs !== undefined) {
|
|
1165
|
+
graph.update(entry.docId, path, entry.refs);
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
graphBuilt = true;
|
|
1169
|
+
updateComponents("external");
|
|
1170
|
+
};
|
|
1171
|
+
|
|
1172
|
+
/** Advance from wherever the host is towards `ready`, one state at a time (§7). */
|
|
1173
|
+
const prepare = async (): Promise<void> => {
|
|
1174
|
+
if (held || closed) {
|
|
1175
|
+
return;
|
|
1176
|
+
}
|
|
1177
|
+
if (readiness === "scaffolded") {
|
|
1178
|
+
if (installing !== null || !(await installedCheck(root, await readManifest()))) {
|
|
1179
|
+
return;
|
|
1180
|
+
}
|
|
1181
|
+
fingerprint = await currentFingerprint();
|
|
1182
|
+
setReadiness("installed");
|
|
1183
|
+
}
|
|
1184
|
+
if (readiness === "installed") {
|
|
1185
|
+
let loaded: ProjectFormats;
|
|
1186
|
+
try {
|
|
1187
|
+
loaded = await loadExtensions(root, config);
|
|
1188
|
+
} catch (error) {
|
|
1189
|
+
report(toError(error));
|
|
1190
|
+
loaded = NO_FORMATS;
|
|
1191
|
+
}
|
|
1192
|
+
extensionSet = extensionSetOf(config);
|
|
1193
|
+
formats = loaded;
|
|
1194
|
+
for (const entry of index.values()) {
|
|
1195
|
+
entry.stale = !entry.isDir;
|
|
1196
|
+
}
|
|
1197
|
+
const token = await formatsTokenOf(extensionSet, loaded);
|
|
1198
|
+
if (token !== formatsToken) {
|
|
1199
|
+
formatsToken = token;
|
|
1200
|
+
emit({ formats: token, origin: "external", type: "formatsChanged" });
|
|
1201
|
+
}
|
|
1202
|
+
setReadiness("extensions-resolved");
|
|
1203
|
+
}
|
|
1204
|
+
if (readiness === "extensions-resolved") {
|
|
1205
|
+
await indexAll();
|
|
1206
|
+
setReadiness("indexed");
|
|
1207
|
+
}
|
|
1208
|
+
setReadiness("ready");
|
|
1209
|
+
};
|
|
1210
|
+
|
|
1211
|
+
// ── Observations (§2.4) ──
|
|
1212
|
+
/** A directory seen at `path`; a file indexed there, held or not, was replaced by it. */
|
|
1213
|
+
const observeDir = async (path: string): Promise<void> => {
|
|
1214
|
+
if (index.get(path)?.isDir === false) {
|
|
1215
|
+
await removePath(path, "external");
|
|
1216
|
+
await afterChange(path, "external");
|
|
1217
|
+
}
|
|
1218
|
+
if (!index.has(path)) {
|
|
1219
|
+
ensureDirs(path, "external");
|
|
1220
|
+
}
|
|
1221
|
+
};
|
|
1222
|
+
|
|
1223
|
+
/**
|
|
1224
|
+
* Whether a move to or from `path` may be paired into a `fileRenamed`: never the configuration or
|
|
1225
|
+
* a dependency input, whose arrival and departure move the configuration and readiness (§4.2,
|
|
1226
|
+
* §7).
|
|
1227
|
+
*/
|
|
1228
|
+
const pairable = (path: string): boolean => !isConfigPath(path) && !FINGERPRINT_PATHS.has(path);
|
|
1229
|
+
|
|
1230
|
+
/** Hold an observed removal for the pairing bound (§2.4). */
|
|
1231
|
+
const observeRemoval = async (path: string): Promise<void> => {
|
|
1232
|
+
ledger.attribute(path, null);
|
|
1233
|
+
const entry = index.get(path);
|
|
1234
|
+
if (entry === undefined || entry.held !== undefined) {
|
|
1235
|
+
return;
|
|
1236
|
+
}
|
|
1237
|
+
if (entry.isDir) {
|
|
1238
|
+
await removePath(path, "external");
|
|
1239
|
+
return;
|
|
1240
|
+
}
|
|
1241
|
+
holds.add(path);
|
|
1242
|
+
// A stop clears every hold's timer (`cancelHold`), so one that fires is this generation's.
|
|
1243
|
+
entry.held = setTimeout(() => {
|
|
1244
|
+
void exclusive(() => flushHold(path)).catch(reportRejection);
|
|
1245
|
+
}, holdMs);
|
|
1246
|
+
};
|
|
1247
|
+
|
|
1248
|
+
const observeFile = async (path: string): Promise<void> => {
|
|
1249
|
+
const stats = await statInside(path);
|
|
1250
|
+
if (stats === null) {
|
|
1251
|
+
return;
|
|
1252
|
+
}
|
|
1253
|
+
if (stats.isDirectory()) {
|
|
1254
|
+
await observeDir(path);
|
|
1255
|
+
return;
|
|
1256
|
+
}
|
|
1257
|
+
if (!stats.isFile()) {
|
|
1258
|
+
return;
|
|
1259
|
+
}
|
|
1260
|
+
const entry = index.get(path);
|
|
1261
|
+
if (
|
|
1262
|
+
entry !== undefined &&
|
|
1263
|
+
!entry.isDir &&
|
|
1264
|
+
entry.held === undefined &&
|
|
1265
|
+
entry.hash !== undefined &&
|
|
1266
|
+
entry.size === stats.size &&
|
|
1267
|
+
entry.mtimeMs === stats.mtimeMs
|
|
1268
|
+
) {
|
|
1269
|
+
// The bytes the index holds: no read, but the ledger still sees the observation (§2.4).
|
|
1270
|
+
ledger.attribute(path, entry.hash);
|
|
1271
|
+
return;
|
|
1272
|
+
}
|
|
1273
|
+
const loaded = await load(path, stats.size);
|
|
1274
|
+
if (loaded === null) {
|
|
1275
|
+
return;
|
|
1276
|
+
}
|
|
1277
|
+
const { bytes, hash } = loaded;
|
|
1278
|
+
const origin = ledger.attribute(path, hash);
|
|
1279
|
+
if (origin !== "external" && entry !== undefined && !entry.isDir) {
|
|
1280
|
+
/* The echo of an own write, whose event is already in the log. A path the index does not
|
|
1281
|
+
hold has no such event, so a match there is indexed like any add. */
|
|
1282
|
+
if (entry.hash === hash) {
|
|
1283
|
+
Object.assign(entry, statFields(stats));
|
|
1284
|
+
}
|
|
1285
|
+
return;
|
|
1286
|
+
}
|
|
1287
|
+
if (entry !== undefined && !entry.isDir) {
|
|
1288
|
+
cancelHold(path, entry);
|
|
1289
|
+
if (entry.hash === hash) {
|
|
1290
|
+
Object.assign(entry, statFields(stats));
|
|
1291
|
+
return;
|
|
1292
|
+
}
|
|
1293
|
+
await applyFile(path, bytes, hash, stats, "external");
|
|
1294
|
+
await afterChange(path, "external");
|
|
1295
|
+
return;
|
|
1296
|
+
}
|
|
1297
|
+
if (entry?.isDir) {
|
|
1298
|
+
await removePath(path, "external");
|
|
1299
|
+
}
|
|
1300
|
+
const moved = pairable(path) ? await movedFrom(hash) : null;
|
|
1301
|
+
if (moved !== null) {
|
|
1302
|
+
await applyMove(moved, path, bytes, stats);
|
|
1303
|
+
return;
|
|
1304
|
+
}
|
|
1305
|
+
await applyFile(path, bytes, hash, stats, "external");
|
|
1306
|
+
await afterChange(path, "external");
|
|
1307
|
+
};
|
|
1308
|
+
|
|
1309
|
+
/**
|
|
1310
|
+
* The indexed file an add with `hash` moved from, if one is gone: a held removal, or one whose
|
|
1311
|
+
* removal the watcher has not reported yet, since it may report the add of a move first (§4.2).
|
|
1312
|
+
*/
|
|
1313
|
+
const movedFrom = async (hash: ContentHash): Promise<string | null> => {
|
|
1314
|
+
const candidates = [...index].filter(
|
|
1315
|
+
([path, other]) => !other.isDir && other.hash === hash && pairable(path),
|
|
1316
|
+
);
|
|
1317
|
+
const pending = candidates.find(([, other]) => other.held !== undefined);
|
|
1318
|
+
if (pending !== undefined) {
|
|
1319
|
+
return pending[0];
|
|
1320
|
+
}
|
|
1321
|
+
for (const [path] of candidates) {
|
|
1322
|
+
if ((await statInside(path)) === null) {
|
|
1323
|
+
return path;
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
return null;
|
|
1327
|
+
};
|
|
1328
|
+
|
|
1329
|
+
/** A held removal outlived the bound: report it, as its directory's when that went too. */
|
|
1330
|
+
const flushHold = async (path: string): Promise<void> => {
|
|
1331
|
+
const entry = index.get(path);
|
|
1332
|
+
if (entry?.held === undefined) {
|
|
1333
|
+
return;
|
|
1334
|
+
}
|
|
1335
|
+
cancelHold(path, entry);
|
|
1336
|
+
const back = await statInside(path);
|
|
1337
|
+
if (back?.isFile() === true) {
|
|
1338
|
+
// Back on disk with no add reported: compare it as a change.
|
|
1339
|
+
await observeFile(path);
|
|
1340
|
+
return;
|
|
1341
|
+
}
|
|
1342
|
+
let top = path;
|
|
1343
|
+
for (const dir of parents(path)) {
|
|
1344
|
+
if (index.get(dir)?.isDir === true && (await statOrNull(dir)) === null) {
|
|
1345
|
+
top = dir;
|
|
1346
|
+
break;
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
await removePath(top, "external");
|
|
1350
|
+
await afterChange(path, "external");
|
|
1351
|
+
};
|
|
1352
|
+
|
|
1353
|
+
const processObservation = async (type: ProjectWatchEvent, path: string): Promise<void> => {
|
|
1354
|
+
if (closed) {
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
1357
|
+
if (installing !== null && FINGERPRINT_PATHS.has(path)) {
|
|
1358
|
+
deferred.push([type, path]);
|
|
1359
|
+
return;
|
|
1360
|
+
}
|
|
1361
|
+
if (!inScope(path)) {
|
|
1362
|
+
if (FINGERPRINT_PATHS.has(path)) {
|
|
1363
|
+
// A lockfile outside the scope emits nothing, but still feeds readiness (§2.2, §7).
|
|
1364
|
+
const bytes = await readOrNull(path);
|
|
1365
|
+
const hash = bytes === null ? null : await contentHash(bytes);
|
|
1366
|
+
if (ledger.attribute(path, hash) === "external") {
|
|
1367
|
+
await checkFingerprint(path, "external");
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
return;
|
|
1371
|
+
}
|
|
1372
|
+
if (type === "unlink" || type === "unlinkDir") {
|
|
1373
|
+
await observeRemoval(path);
|
|
1374
|
+
} else if (type === "addDir") {
|
|
1375
|
+
const stats = await statInside(path);
|
|
1376
|
+
if (stats?.isDirectory() === true) {
|
|
1377
|
+
await observeDir(path);
|
|
1378
|
+
}
|
|
1379
|
+
} else {
|
|
1380
|
+
await observeFile(path);
|
|
1381
|
+
}
|
|
1382
|
+
};
|
|
1383
|
+
|
|
1384
|
+
/** Bring the index in line with the disk after the scope moved (`build.outDir`, §2.2). */
|
|
1385
|
+
const reconcile = async (): Promise<void> => {
|
|
1386
|
+
for (const path of index.keys()) {
|
|
1387
|
+
if (index.has(path) && !inScope(path)) {
|
|
1388
|
+
await removePath(path, "external");
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
const disk = await scan();
|
|
1392
|
+
for (const [path, isDir] of disk) {
|
|
1393
|
+
if (index.has(path)) {
|
|
1394
|
+
continue;
|
|
1395
|
+
}
|
|
1396
|
+
if (isDir) {
|
|
1397
|
+
ensureDirs(path, "external");
|
|
1398
|
+
} else {
|
|
1399
|
+
await observeFile(path);
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
};
|
|
1403
|
+
|
|
1404
|
+
/** Every path in the index scope on disk, with whether it is a directory. */
|
|
1405
|
+
const scan = async (): Promise<Map<string, boolean>> => {
|
|
1406
|
+
const out = new Map<string, boolean>();
|
|
1407
|
+
const seen = new Set<string>();
|
|
1408
|
+
const walk = async (dir: string): Promise<void> => {
|
|
1409
|
+
let real: string;
|
|
1410
|
+
let names: string[];
|
|
1411
|
+
try {
|
|
1412
|
+
real = await fs.realpath(dir === "" ? root : toAbs(dir));
|
|
1413
|
+
names = await fs.readdir(dir === "" ? root : toAbs(dir));
|
|
1414
|
+
} catch {
|
|
1415
|
+
return;
|
|
1416
|
+
}
|
|
1417
|
+
if (seen.has(real)) {
|
|
1418
|
+
return;
|
|
1419
|
+
}
|
|
1420
|
+
seen.add(real);
|
|
1421
|
+
for (const name of names.toSorted()) {
|
|
1422
|
+
const path = dir === "" ? name : `${dir}/${name}`;
|
|
1423
|
+
if (!inScope(path)) {
|
|
1424
|
+
continue;
|
|
1425
|
+
}
|
|
1426
|
+
const stats = await statInside(path);
|
|
1427
|
+
if (stats?.isDirectory() === true) {
|
|
1428
|
+
out.set(path, true);
|
|
1429
|
+
await walk(path);
|
|
1430
|
+
} else if (stats?.isFile() === true) {
|
|
1431
|
+
out.set(path, false);
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
};
|
|
1435
|
+
await walk("");
|
|
1436
|
+
return out;
|
|
1437
|
+
};
|
|
1438
|
+
|
|
1439
|
+
// ── Lifecycle ──
|
|
1440
|
+
/**
|
|
1441
|
+
* End every open subscription. The set is emptied first, so a sink whose `end` subscribes again
|
|
1442
|
+
* keeps its new subscription, answered from the state that is current by then.
|
|
1443
|
+
*/
|
|
1444
|
+
const endSubscriptions = (): void => {
|
|
1445
|
+
const ending = [...subscribers];
|
|
1446
|
+
subscribers.clear();
|
|
1447
|
+
for (const sub of ending) {
|
|
1448
|
+
try {
|
|
1449
|
+
sub.sink.end?.();
|
|
1450
|
+
} catch (error) {
|
|
1451
|
+
report(toError(error));
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
};
|
|
1455
|
+
|
|
1456
|
+
/**
|
|
1457
|
+
* Stop observing: nothing the old watcher or a held removal reports is processed after this. The
|
|
1458
|
+
* old state stays served, and its subscriptions open, until a start replaces it or close ends
|
|
1459
|
+
* them.
|
|
1460
|
+
*/
|
|
1461
|
+
const stop = async (): Promise<void> => {
|
|
1462
|
+
generation += 1;
|
|
1463
|
+
for (const [path, entry] of index) {
|
|
1464
|
+
cancelHold(path, entry);
|
|
1465
|
+
}
|
|
1466
|
+
const [closingWatcher, closingGit] = [watcher, git];
|
|
1467
|
+
watcher = null;
|
|
1468
|
+
await Promise.all([closingWatcher?.close(), closingGit?.close()]);
|
|
1469
|
+
};
|
|
1470
|
+
|
|
1471
|
+
const readConfigFromDisk = async (): Promise<ProjectConfig | undefined> => {
|
|
1472
|
+
for (const name of PROJECT_FILE_NAMES) {
|
|
1473
|
+
const bytes = await readReported(name);
|
|
1474
|
+
if (bytes !== null) {
|
|
1475
|
+
return readConfig(name, bytes);
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
return undefined;
|
|
1479
|
+
};
|
|
1480
|
+
|
|
1481
|
+
/**
|
|
1482
|
+
* Start, or start again: a new epoch, a scan, readiness from `scaffolded` (§2.3, §7). The new
|
|
1483
|
+
* state is built aside and replaces the old one in one synchronous step, which also ends every
|
|
1484
|
+
* subscription to the old one, so a subscribe at any point is answered from one whole state: the
|
|
1485
|
+
* old epoch's, and then ended, or the new one's, already scanned (§3.1).
|
|
1486
|
+
*/
|
|
1487
|
+
const start = async (): Promise<void> => {
|
|
1488
|
+
const at = generation;
|
|
1489
|
+
let live = false;
|
|
1490
|
+
/** A failure the new watcher reported before the swap, reported in the new epoch. */
|
|
1491
|
+
const degradedBy: string[] = [];
|
|
1492
|
+
try {
|
|
1493
|
+
realRoot = await fs.realpath(root);
|
|
1494
|
+
} catch {
|
|
1495
|
+
realRoot = root;
|
|
1496
|
+
}
|
|
1497
|
+
config = await readConfigFromDisk();
|
|
1498
|
+
outDir = outDirOf(config);
|
|
1499
|
+
const degrade = (reason: string): void => {
|
|
1500
|
+
degraded = true;
|
|
1501
|
+
emit({ origin: "external", reason, type: "watcherDegraded" });
|
|
1502
|
+
};
|
|
1503
|
+
const handle = watcherFactory(
|
|
1504
|
+
root,
|
|
1505
|
+
{
|
|
1506
|
+
activity: () => {
|
|
1507
|
+
lastActivity = Date.now();
|
|
1508
|
+
},
|
|
1509
|
+
error: (error) => {
|
|
1510
|
+
report(error);
|
|
1511
|
+
if (at !== generation || closed) {
|
|
1512
|
+
return;
|
|
1513
|
+
}
|
|
1514
|
+
if (!live) {
|
|
1515
|
+
degradedBy.push(error.message);
|
|
1516
|
+
} else if (!degraded) {
|
|
1517
|
+
degrade(error.message);
|
|
1518
|
+
}
|
|
1519
|
+
},
|
|
1520
|
+
event: (type, path) => {
|
|
1521
|
+
lastActivity = Date.now();
|
|
1522
|
+
const rel = toRel(path);
|
|
1523
|
+
if (rel !== "" && !rel.startsWith("..")) {
|
|
1524
|
+
// Queued behind this start, so it is processed against the state it builds.
|
|
1525
|
+
void exclusive(() =>
|
|
1526
|
+
at === generation ? processObservation(type, rel) : undefined,
|
|
1527
|
+
).catch(reportRejection);
|
|
1528
|
+
}
|
|
1529
|
+
},
|
|
1530
|
+
},
|
|
1531
|
+
{ atomicSaveMs, ignored: createWatchIgnore(root, watchIgnored), stabilityMs },
|
|
1532
|
+
);
|
|
1533
|
+
watcher = handle;
|
|
1534
|
+
await handle.ready;
|
|
1535
|
+
const scanned = await scan();
|
|
1536
|
+
let monitor: GitMonitor | null = null;
|
|
1537
|
+
if (options.git !== false) {
|
|
1538
|
+
const monitorOptions: GitMonitorOptions = {
|
|
1539
|
+
onActivity: () => {
|
|
1540
|
+
lastActivity = Date.now();
|
|
1541
|
+
},
|
|
1542
|
+
onChange: (status) => {
|
|
1543
|
+
// Before the swap the monitor's summary is read by the new state's snapshot instead.
|
|
1544
|
+
if (live && at === generation && !closed) {
|
|
1545
|
+
emit({ origin: "external", status, type: "gitChanged" });
|
|
1546
|
+
}
|
|
1547
|
+
},
|
|
1548
|
+
onError: report,
|
|
1549
|
+
root,
|
|
1550
|
+
};
|
|
1551
|
+
if (options.git !== undefined) {
|
|
1552
|
+
monitorOptions.run = options.git;
|
|
1553
|
+
}
|
|
1554
|
+
if (options.gitWatch !== undefined) {
|
|
1555
|
+
monitorOptions.watch = options.gitWatch;
|
|
1556
|
+
}
|
|
1557
|
+
if (options.gitDebounceMs !== undefined) {
|
|
1558
|
+
monitorOptions.debounceMs = options.gitDebounceMs;
|
|
1559
|
+
}
|
|
1560
|
+
monitor = await createGitMonitor(monitorOptions);
|
|
1561
|
+
}
|
|
1562
|
+
// ── one synchronous segment from here: the old state is replaced whole ──
|
|
1563
|
+
log = createMemoryEventLog({
|
|
1564
|
+
capacity: options.logCapacity ?? EVENT_LOG_CAPACITY,
|
|
1565
|
+
epoch: randomUUID(),
|
|
1566
|
+
});
|
|
1567
|
+
ledger = createEchoLedger();
|
|
1568
|
+
index.clear();
|
|
1569
|
+
for (const [path, isDir] of scanned) {
|
|
1570
|
+
index.set(path, {
|
|
1571
|
+
defines: null,
|
|
1572
|
+
docId: randomUUID(),
|
|
1573
|
+
indexed: isDir,
|
|
1574
|
+
isDir,
|
|
1575
|
+
// Provisional until indexed: the locations that need no read (§3.1).
|
|
1576
|
+
kind: isDir ? "other" : isConfigPath(path) ? "project-config" : "other",
|
|
1577
|
+
});
|
|
1578
|
+
}
|
|
1579
|
+
graph = createDependencyGraph();
|
|
1580
|
+
graphBuilt = false;
|
|
1581
|
+
entryTypes = new Map();
|
|
1582
|
+
readiness = "scaffolded";
|
|
1583
|
+
fingerprint = null;
|
|
1584
|
+
extensionSet = null;
|
|
1585
|
+
formats = null;
|
|
1586
|
+
formatsToken = UNRESOLVED_FORMATS;
|
|
1587
|
+
components = [];
|
|
1588
|
+
degraded = false;
|
|
1589
|
+
deferred = [];
|
|
1590
|
+
git = monitor;
|
|
1591
|
+
live = true;
|
|
1592
|
+
endSubscriptions();
|
|
1593
|
+
const [firstFailure] = degradedBy;
|
|
1594
|
+
if (firstFailure !== undefined) {
|
|
1595
|
+
degrade(firstFailure);
|
|
1596
|
+
}
|
|
1597
|
+
schedulePrepare();
|
|
1598
|
+
};
|
|
1599
|
+
|
|
1600
|
+
await exclusive(() => start());
|
|
1601
|
+
|
|
1602
|
+
const snapshot = (): ProjectSnapshot => {
|
|
1603
|
+
const files: IndexedFile[] = [...index]
|
|
1604
|
+
.toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
1605
|
+
.map(([path, entry]) => {
|
|
1606
|
+
const file: IndexedFile = {
|
|
1607
|
+
docId: entry.docId,
|
|
1608
|
+
indexed: entry.indexed,
|
|
1609
|
+
isDir: entry.isDir,
|
|
1610
|
+
kind: entry.kind,
|
|
1611
|
+
path,
|
|
1612
|
+
};
|
|
1613
|
+
if (entry.hash !== undefined) {
|
|
1614
|
+
file.hash = entry.hash;
|
|
1615
|
+
}
|
|
1616
|
+
return file;
|
|
1617
|
+
});
|
|
1618
|
+
const out: ProjectSnapshot = {
|
|
1619
|
+
components: [...components],
|
|
1620
|
+
files,
|
|
1621
|
+
formats: formatsToken,
|
|
1622
|
+
readiness,
|
|
1623
|
+
};
|
|
1624
|
+
const summary = git?.summary;
|
|
1625
|
+
if (summary !== undefined) {
|
|
1626
|
+
out.git = summary;
|
|
1627
|
+
}
|
|
1628
|
+
return out;
|
|
1629
|
+
};
|
|
1630
|
+
|
|
1631
|
+
const writeOrigin = (writeId: string, writeHash: ContentHash | null): WriteOrigin => ({
|
|
1632
|
+
writeHash,
|
|
1633
|
+
writeId,
|
|
1634
|
+
});
|
|
1635
|
+
|
|
1636
|
+
/** Every file beneath a directory in the index scope, relative to it, with its hash (§5). */
|
|
1637
|
+
const filesBeneath = async (dir: string): Promise<Record<string, ContentHash>> => {
|
|
1638
|
+
const out: Record<string, ContentHash> = {};
|
|
1639
|
+
for (const [path, isDir] of await scan()) {
|
|
1640
|
+
if (!isDir && path.startsWith(`${dir}/`)) {
|
|
1641
|
+
const hash = await hashOf(path);
|
|
1642
|
+
if (hash !== null) {
|
|
1643
|
+
out[path.slice(dir.length + 1)] = hash;
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
return out;
|
|
1648
|
+
};
|
|
1649
|
+
|
|
1650
|
+
/**
|
|
1651
|
+
* Rename a write's temporary file over its target, again after each of `renameRetryMs` when the
|
|
1652
|
+
* failure is one a reader holding the target open causes on Windows.
|
|
1653
|
+
*/
|
|
1654
|
+
const renameOver = async (temp: string, target: string): Promise<void> => {
|
|
1655
|
+
for (const wait of renameRetryMs) {
|
|
1656
|
+
try {
|
|
1657
|
+
await fs.rename(temp, target);
|
|
1658
|
+
return;
|
|
1659
|
+
} catch (error) {
|
|
1660
|
+
if (!RENAME_RETRY_CODES.has(errorCode(toError(error)) ?? "")) {
|
|
1661
|
+
throw error;
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
await new Promise((resolve) => {
|
|
1665
|
+
setTimeout(resolve, wait);
|
|
1666
|
+
});
|
|
1667
|
+
}
|
|
1668
|
+
await fs.rename(temp, target);
|
|
1669
|
+
};
|
|
1670
|
+
|
|
1671
|
+
/** A conditional write (§5), run by a caller that holds the queue. */
|
|
1672
|
+
const writeNow = async (request: WriteRequest): Promise<WriteResult> => {
|
|
1673
|
+
const path = await contained(request.path);
|
|
1674
|
+
const stats = await statOrNull(path);
|
|
1675
|
+
if (stats?.isDirectory() === true) {
|
|
1676
|
+
throw new TypeError(`"${path}" is a directory`);
|
|
1677
|
+
}
|
|
1678
|
+
// A file that exists but cannot be read rejects here: it is never taken for an absent one.
|
|
1679
|
+
const diskHash = stats === null ? null : await hashOf(path);
|
|
1680
|
+
const entry = index.get(path);
|
|
1681
|
+
const docId = entry !== undefined && !entry.isDir ? entry.docId : null;
|
|
1682
|
+
const refused = checkWritePrecondition(request, { docId, hash: diskHash });
|
|
1683
|
+
if (refused !== null && !refused.ok) {
|
|
1684
|
+
emit(conflictEvent(request, refused.conflict));
|
|
1685
|
+
return refused;
|
|
1686
|
+
}
|
|
1687
|
+
const bytes = toBytes(request.contents);
|
|
1688
|
+
const hash = await contentHash(bytes);
|
|
1689
|
+
if (hash === diskHash) {
|
|
1690
|
+
return { hash, ok: true, rev: log.rev };
|
|
1691
|
+
}
|
|
1692
|
+
/* Through a link that stays inside the root (`contained`), the link's target is written and
|
|
1693
|
+
the link kept, and an existing file keeps its permissions. */
|
|
1694
|
+
const target = stats === null ? toAbs(path) : await fs.realpath(toAbs(path));
|
|
1695
|
+
await fs.mkdir(dirname(target), { recursive: true });
|
|
1696
|
+
// Through a temporary file and a re-hash of the target, so the window is one rename (§5).
|
|
1697
|
+
const temp = join(dirname(target), `.${basename(target)}.jx-write-${randomUUID()}`);
|
|
1698
|
+
try {
|
|
1699
|
+
await fs.writeFile(temp, bytes);
|
|
1700
|
+
if (stats !== null) {
|
|
1701
|
+
// The permission bits alone: the mode's higher bits are the file's type.
|
|
1702
|
+
await fs.chmod(temp, stats.mode % 4096);
|
|
1703
|
+
}
|
|
1704
|
+
const nowHash = await hashOf(path);
|
|
1705
|
+
if (nowHash !== diskHash) {
|
|
1706
|
+
await fs.rm(temp, { force: true });
|
|
1707
|
+
const conflict = { diskHash: nowHash, docId, path };
|
|
1708
|
+
emit(conflictEvent(request, conflict));
|
|
1709
|
+
return { conflict, ok: false };
|
|
1710
|
+
}
|
|
1711
|
+
await renameOver(temp, target);
|
|
1712
|
+
} catch (error) {
|
|
1713
|
+
// Nothing was written: the temporary file goes, and nothing waits for an echo.
|
|
1714
|
+
await fs.rm(temp, { force: true });
|
|
1715
|
+
throw error;
|
|
1716
|
+
}
|
|
1717
|
+
/* Noted once the rename has landed and before any observation is compared, since those are
|
|
1718
|
+
processed in the queue this write holds (§2.4). An out-of-scope path is noted only when it
|
|
1719
|
+
is a dependency input, the one kind whose observations are still attributed (§7). */
|
|
1720
|
+
const origin = writeOrigin(request.writeId, hash);
|
|
1721
|
+
if (!inScope(path)) {
|
|
1722
|
+
if (FINGERPRINT_PATHS.has(path)) {
|
|
1723
|
+
ledger.note(path, hash, request.writeId);
|
|
1724
|
+
}
|
|
1725
|
+
await checkFingerprint(path, origin);
|
|
1726
|
+
return { hash, ok: true, rev: log.rev };
|
|
1727
|
+
}
|
|
1728
|
+
ledger.note(path, hash, request.writeId);
|
|
1729
|
+
// No size or time is recorded, so the first observation of the path reads it (§2.4, §5).
|
|
1730
|
+
const event = await applyFile(path, bytes, hash, null, origin);
|
|
1731
|
+
await afterChange(path, origin);
|
|
1732
|
+
return { hash, ok: true, rev: event.rev };
|
|
1733
|
+
};
|
|
1734
|
+
|
|
1735
|
+
const write = (request: WriteRequest): Promise<WriteResult> => exclusive(() => writeNow(request));
|
|
1736
|
+
|
|
1737
|
+
/**
|
|
1738
|
+
* Move `from`, a file or a directory, to `to` as the write `writeId`, run by a caller that holds
|
|
1739
|
+
* the queue (§9.1): the disk first, then in one synchronous segment the index re-keyed with every
|
|
1740
|
+
* document keeping its id, one `fileRenamed`, a `docChanged` for each file the move reclassified,
|
|
1741
|
+
* and the invalidations of both paths (§4.2, §8). Each moved file is noted in the echo ledger at
|
|
1742
|
+
* its new path, so the watcher's report of the move is recognised as this write. Answers the
|
|
1743
|
+
* directories it created for `to`, outermost first, for an undo to remove.
|
|
1744
|
+
*/
|
|
1745
|
+
const moveNow = async (from: string, to: string, writeId: string): Promise<string[]> => {
|
|
1746
|
+
if (await takenBy(from, to)) {
|
|
1747
|
+
throw new Error(`"${to}" already exists`);
|
|
1748
|
+
}
|
|
1749
|
+
const created: string[] = [];
|
|
1750
|
+
for (const dir of parents(to)) {
|
|
1751
|
+
if ((await statOrNull(dir)) === null) {
|
|
1752
|
+
created.push(dir);
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
await fs.mkdir(dirname(toAbs(to)), { recursive: true });
|
|
1756
|
+
await fs.rename(toAbs(from), toAbs(to));
|
|
1757
|
+
const moved = [...index].filter(([key]) => key === from || key.startsWith(`${from}/`));
|
|
1758
|
+
const nextOf = (key: string): string => to + key.slice(from.length);
|
|
1759
|
+
const described = new Map<string, Described>();
|
|
1760
|
+
for (const [key, entry] of moved) {
|
|
1761
|
+
if (!entry.isDir) {
|
|
1762
|
+
const next = nextOf(key);
|
|
1763
|
+
const stats = await statOrNull(next);
|
|
1764
|
+
let loaded: Awaited<ReturnType<typeof load>> = null;
|
|
1765
|
+
try {
|
|
1766
|
+
loaded = stats === null ? null : await load(next, stats.size);
|
|
1767
|
+
} catch (error) {
|
|
1768
|
+
report(toError(error));
|
|
1769
|
+
}
|
|
1770
|
+
described.set(key, await describe(next, loaded?.bytes ?? null));
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
const movedFiles = new Set(moved.flatMap(([key, entry]) => (entry.isDir ? [] : [key])));
|
|
1774
|
+
const collections = graphBuilt
|
|
1775
|
+
? await collectionsFor(
|
|
1776
|
+
[
|
|
1777
|
+
...indexedFiles().filter((file) => !movedFiles.has(file)),
|
|
1778
|
+
...[...movedFiles].map((file) => nextOf(file)),
|
|
1779
|
+
],
|
|
1780
|
+
config,
|
|
1781
|
+
)
|
|
1782
|
+
: null;
|
|
1783
|
+
// ── one synchronous segment from here ──
|
|
1784
|
+
const top = index.get(from)!;
|
|
1785
|
+
for (const [key, entry] of moved) {
|
|
1786
|
+
cancelHold(key, entry);
|
|
1787
|
+
index.delete(key);
|
|
1788
|
+
}
|
|
1789
|
+
forgetBeneath(from);
|
|
1790
|
+
const origin = writeOrigin(writeId, top.isDir ? null : (top.hash ?? null));
|
|
1791
|
+
ensureDirs(parents(to).at(-1) ?? "", origin);
|
|
1792
|
+
for (const [key, entry] of moved) {
|
|
1793
|
+
const next = nextOf(key);
|
|
1794
|
+
index.set(next, entry);
|
|
1795
|
+
Object.assign(entry, { mtimeMs: undefined, size: undefined });
|
|
1796
|
+
if (!entry.isDir && entry.hash !== undefined) {
|
|
1797
|
+
ledger.note(next, entry.hash, writeId);
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
emit({ docId: top.docId, from, isDir: top.isDir, origin, to, type: "fileRenamed" });
|
|
1801
|
+
if (graphBuilt && collections !== null) {
|
|
1802
|
+
applyEntryTypes(collections);
|
|
1803
|
+
}
|
|
1804
|
+
for (const [key, entry] of moved) {
|
|
1805
|
+
const fresh = described.get(key);
|
|
1806
|
+
if (fresh === undefined) {
|
|
1807
|
+
continue;
|
|
1808
|
+
}
|
|
1809
|
+
const next = nextOf(key);
|
|
1810
|
+
const reclassified = fresh.kind !== entry.kind;
|
|
1811
|
+
if (reclassified) {
|
|
1812
|
+
Object.assign(entry, {
|
|
1813
|
+
defines: fresh.refs?.defines ?? null,
|
|
1814
|
+
indexed: fresh.refs !== null,
|
|
1815
|
+
kind: fresh.kind,
|
|
1816
|
+
refs: fresh.refs,
|
|
1817
|
+
});
|
|
1818
|
+
emit({
|
|
1819
|
+
docId: entry.docId,
|
|
1820
|
+
hash: entry.hash!,
|
|
1821
|
+
indexed: entry.indexed,
|
|
1822
|
+
kind: entry.kind,
|
|
1823
|
+
origin,
|
|
1824
|
+
path: next,
|
|
1825
|
+
type: "docChanged",
|
|
1826
|
+
});
|
|
1827
|
+
}
|
|
1828
|
+
if (graphBuilt && collections !== null) {
|
|
1829
|
+
emitInvalidations(
|
|
1830
|
+
entry.docId,
|
|
1831
|
+
reclassified
|
|
1832
|
+
? graph.update(entry.docId, next, fresh.refs)
|
|
1833
|
+
: graph.relabel(entry.docId, next),
|
|
1834
|
+
origin,
|
|
1835
|
+
);
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
updateComponents(origin);
|
|
1839
|
+
git?.schedule();
|
|
1840
|
+
return created;
|
|
1841
|
+
};
|
|
1842
|
+
|
|
1843
|
+
/**
|
|
1844
|
+
* Whether something other than `from` is at `to` on disk. On a case-insensitive filesystem (the
|
|
1845
|
+
* desktop's macOS and Windows), `from` in another case stats as `from` itself, and a rename to it
|
|
1846
|
+
* changes only its case (`studio.md` §9.1.1).
|
|
1847
|
+
*/
|
|
1848
|
+
const takenBy = async (from: string, to: string): Promise<boolean> => {
|
|
1849
|
+
const there = await statOrNull(to);
|
|
1850
|
+
if (there === null) {
|
|
1851
|
+
return false;
|
|
1852
|
+
}
|
|
1853
|
+
if (from.toLowerCase() !== to.toLowerCase()) {
|
|
1854
|
+
return true;
|
|
1855
|
+
}
|
|
1856
|
+
const self = await statOrNull(from);
|
|
1857
|
+
return self === null || self.ino !== there.ino || self.dev !== there.dev;
|
|
1858
|
+
};
|
|
1859
|
+
|
|
1860
|
+
/** Remove each of `dirs` still empty, innermost first, as the write `writeId` (§9.1). */
|
|
1861
|
+
const removeDirs = async (dirs: readonly string[], writeId: string): Promise<void> => {
|
|
1862
|
+
for (const dir of dirs.toReversed()) {
|
|
1863
|
+
const inside = await fs.readdir(toAbs(dir));
|
|
1864
|
+
if (inside.length > 0) {
|
|
1865
|
+
return;
|
|
1866
|
+
}
|
|
1867
|
+
await fs.rm(toAbs(dir), { recursive: true });
|
|
1868
|
+
await removePath(dir, writeOrigin(writeId, null));
|
|
1869
|
+
}
|
|
1870
|
+
};
|
|
1871
|
+
|
|
1872
|
+
/** The rename cascade (§9), with this host's index, graph and writes lent for one operation. */
|
|
1873
|
+
const rename = (operation: RenameOperation): Promise<RenameOperationResult> =>
|
|
1874
|
+
exclusive(async () => {
|
|
1875
|
+
const from = await contained(operation.from);
|
|
1876
|
+
const to = await contained(operation.to);
|
|
1877
|
+
for (const path of [from, to]) {
|
|
1878
|
+
if (!inScope(path)) {
|
|
1879
|
+
throw new TypeError(`"${path}" is outside the index scope`);
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
// Plan with the project's parsers: load them first if the host has not yet (§7, §9.1).
|
|
1883
|
+
if (formats === null) {
|
|
1884
|
+
await prepare();
|
|
1885
|
+
}
|
|
1886
|
+
try {
|
|
1887
|
+
return await runRenameCascade(
|
|
1888
|
+
{
|
|
1889
|
+
applied: (opId, files) =>
|
|
1890
|
+
emit({ files, opId, origin: writeOrigin(opId, null), type: "operationApplied" }).rev,
|
|
1891
|
+
entries: () =>
|
|
1892
|
+
[...index].map(([path, entry]) => ({
|
|
1893
|
+
indexed: entry.indexed,
|
|
1894
|
+
isDir: entry.isDir,
|
|
1895
|
+
path,
|
|
1896
|
+
})),
|
|
1897
|
+
exists: (path) => takenBy(from, path),
|
|
1898
|
+
/* Held, the host will load the parsers once released, so the graph is partial until
|
|
1899
|
+
then. Otherwise its dependencies are not installed, and no format is registered: a
|
|
1900
|
+
file in none is not a document (§2.2). */
|
|
1901
|
+
formats: () => formats ?? (held ? null : NO_FORMATS),
|
|
1902
|
+
move: moveNow,
|
|
1903
|
+
read: readOrNull,
|
|
1904
|
+
removeDirs,
|
|
1905
|
+
referrersOf: (paths) => {
|
|
1906
|
+
if (!graphBuilt || degraded) {
|
|
1907
|
+
return null;
|
|
1908
|
+
}
|
|
1909
|
+
const byId = new Map([...index].map(([path, entry]) => [entry.docId, path]));
|
|
1910
|
+
const out = new Set<string>();
|
|
1911
|
+
for (const path of paths) {
|
|
1912
|
+
const entry = index.get(path);
|
|
1913
|
+
const dependents =
|
|
1914
|
+
entry === undefined ? graph.dependentsAt(path) : graph.dependentsOf(entry.docId);
|
|
1915
|
+
for (const ids of dependents.values()) {
|
|
1916
|
+
for (const id of ids) {
|
|
1917
|
+
const at = byId.get(id);
|
|
1918
|
+
if (at !== undefined) {
|
|
1919
|
+
out.add(at);
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
}
|
|
1923
|
+
}
|
|
1924
|
+
return [...out];
|
|
1925
|
+
},
|
|
1926
|
+
root,
|
|
1927
|
+
write: writeNow,
|
|
1928
|
+
...(options.onRenameStep !== undefined && { beforeStep: options.onRenameStep }),
|
|
1929
|
+
},
|
|
1930
|
+
{ ...operation, from, to },
|
|
1931
|
+
(path) => !pairable(path),
|
|
1932
|
+
);
|
|
1933
|
+
} finally {
|
|
1934
|
+
/* The usage query's cache (`findReferences`) is otherwise dropped by a watcher that reports
|
|
1935
|
+
the move after this answer, and never under a path it ignores; the caller's next
|
|
1936
|
+
question is who uses the new name (§12). */
|
|
1937
|
+
invalidateReferenceCache(root);
|
|
1938
|
+
}
|
|
1939
|
+
});
|
|
1940
|
+
|
|
1941
|
+
const remove = (request: DeleteRequest): Promise<DeleteResult> =>
|
|
1942
|
+
exclusive(async () => {
|
|
1943
|
+
const path = await contained(request.path);
|
|
1944
|
+
const stats = await statOrNull(path);
|
|
1945
|
+
let current: DeleteBase | null = null;
|
|
1946
|
+
if (stats?.isFile() === true) {
|
|
1947
|
+
// A file that cannot be read rejects here, and one gone since its stat is absent.
|
|
1948
|
+
const hash = await hashOf(path);
|
|
1949
|
+
current = hash === null ? null : { hash };
|
|
1950
|
+
} else if (stats?.isDirectory() === true) {
|
|
1951
|
+
current = { files: await filesBeneath(path) };
|
|
1952
|
+
}
|
|
1953
|
+
const entry = index.get(path);
|
|
1954
|
+
const refused = checkDeletePrecondition(request, current, entry?.docId ?? null);
|
|
1955
|
+
if (refused !== null && !refused.ok) {
|
|
1956
|
+
emit(conflictEvent(request, refused.conflict));
|
|
1957
|
+
return refused;
|
|
1958
|
+
}
|
|
1959
|
+
await fs.rm(toAbs(path), { force: true, recursive: true });
|
|
1960
|
+
forgetBeneath(path);
|
|
1961
|
+
const origin = writeOrigin(request.writeId, null);
|
|
1962
|
+
const event = inScope(path) ? await removePath(path, origin) : null;
|
|
1963
|
+
await afterChange(path, origin);
|
|
1964
|
+
return { ok: true, rev: event?.rev ?? log.rev };
|
|
1965
|
+
});
|
|
1966
|
+
|
|
1967
|
+
const install = async (): Promise<void> => {
|
|
1968
|
+
const writeId = `install-${randomUUID()}`;
|
|
1969
|
+
await exclusive(() => {
|
|
1970
|
+
installing = writeId;
|
|
1971
|
+
deferred = [];
|
|
1972
|
+
});
|
|
1973
|
+
let failure: Error | null = null;
|
|
1974
|
+
try {
|
|
1975
|
+
await installer(root);
|
|
1976
|
+
} catch (error) {
|
|
1977
|
+
failure = toError(error);
|
|
1978
|
+
}
|
|
1979
|
+
await exclusive(async () => {
|
|
1980
|
+
// The install's own writes, recorded with its write id before the watcher reports them (§7).
|
|
1981
|
+
for (const path of FINGERPRINT_PATHS) {
|
|
1982
|
+
if (!inScope(path)) {
|
|
1983
|
+
continue;
|
|
1984
|
+
}
|
|
1985
|
+
const bytes = await readReported(path);
|
|
1986
|
+
const entry = index.get(path);
|
|
1987
|
+
if (bytes === null) {
|
|
1988
|
+
if (entry !== undefined) {
|
|
1989
|
+
await removePath(path, failure === null ? writeOrigin(writeId, null) : "external");
|
|
1990
|
+
}
|
|
1991
|
+
continue;
|
|
1992
|
+
}
|
|
1993
|
+
const hash = await contentHash(bytes);
|
|
1994
|
+
if (entry?.hash !== hash) {
|
|
1995
|
+
await applyFile(
|
|
1996
|
+
path,
|
|
1997
|
+
bytes,
|
|
1998
|
+
hash,
|
|
1999
|
+
await statOrNull(path),
|
|
2000
|
+
failure === null ? writeOrigin(writeId, hash) : "external",
|
|
2001
|
+
);
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
if (failure === null) {
|
|
2005
|
+
fingerprint = await currentFingerprint();
|
|
2006
|
+
}
|
|
2007
|
+
const pending = deferred;
|
|
2008
|
+
deferred = [];
|
|
2009
|
+
for (const [type, path] of pending) {
|
|
2010
|
+
await processObservation(type, path);
|
|
2011
|
+
}
|
|
2012
|
+
if (failure === null && readiness === "scaffolded" && !held) {
|
|
2013
|
+
setReadiness("installed");
|
|
2014
|
+
}
|
|
2015
|
+
installing = null;
|
|
2016
|
+
await (failure === null ? prepare() : checkFingerprint(MANIFEST, "external"));
|
|
2017
|
+
});
|
|
2018
|
+
if (failure !== null) {
|
|
2019
|
+
throw failure;
|
|
2020
|
+
}
|
|
2021
|
+
};
|
|
2022
|
+
|
|
2023
|
+
const idle = async (quietMs = 300): Promise<void> => {
|
|
2024
|
+
const started = Date.now();
|
|
2025
|
+
for (;;) {
|
|
2026
|
+
await chain;
|
|
2027
|
+
const quiet = Date.now() - Math.max(started, lastActivity) >= quietMs;
|
|
2028
|
+
if (
|
|
2029
|
+
quiet &&
|
|
2030
|
+
queued === 0 &&
|
|
2031
|
+
holds.size === 0 &&
|
|
2032
|
+
installing === null &&
|
|
2033
|
+
(git?.idle() ?? true)
|
|
2034
|
+
) {
|
|
2035
|
+
return;
|
|
2036
|
+
}
|
|
2037
|
+
await new Promise((resolve) => {
|
|
2038
|
+
setTimeout(resolve, 20);
|
|
2039
|
+
});
|
|
2040
|
+
}
|
|
2041
|
+
};
|
|
2042
|
+
|
|
2043
|
+
return {
|
|
2044
|
+
close: async () => {
|
|
2045
|
+
if (closed) {
|
|
2046
|
+
return;
|
|
2047
|
+
}
|
|
2048
|
+
closed = true;
|
|
2049
|
+
await exclusive(async () => {
|
|
2050
|
+
await stop();
|
|
2051
|
+
endSubscriptions();
|
|
2052
|
+
});
|
|
2053
|
+
},
|
|
2054
|
+
createDirectory: (path, writeId) =>
|
|
2055
|
+
exclusive(async () => {
|
|
2056
|
+
const dir = await contained(path);
|
|
2057
|
+
await fs.mkdir(toAbs(dir), { recursive: true });
|
|
2058
|
+
ensureDirs(dir, writeOrigin(writeId, null));
|
|
2059
|
+
return { rev: log.rev };
|
|
2060
|
+
}),
|
|
2061
|
+
delete: remove,
|
|
2062
|
+
docIdAt: (path) => {
|
|
2063
|
+
const entry = index.get(path);
|
|
2064
|
+
return entry === undefined ? null : entry.docId;
|
|
2065
|
+
},
|
|
2066
|
+
get epoch() {
|
|
2067
|
+
return log.epoch;
|
|
2068
|
+
},
|
|
2069
|
+
idle,
|
|
2070
|
+
install,
|
|
2071
|
+
get readiness() {
|
|
2072
|
+
return readiness;
|
|
2073
|
+
},
|
|
2074
|
+
release: () =>
|
|
2075
|
+
exclusive(async () => {
|
|
2076
|
+
held = false;
|
|
2077
|
+
await prepare();
|
|
2078
|
+
}),
|
|
2079
|
+
rename,
|
|
2080
|
+
restart: () =>
|
|
2081
|
+
exclusive(async () => {
|
|
2082
|
+
await stop();
|
|
2083
|
+
await start();
|
|
2084
|
+
}),
|
|
2085
|
+
get rev() {
|
|
2086
|
+
return log.rev;
|
|
2087
|
+
},
|
|
2088
|
+
references: () =>
|
|
2089
|
+
readinessAtLeast(readiness, "indexed") && !degraded
|
|
2090
|
+
? {
|
|
2091
|
+
documents: graph.documents(),
|
|
2092
|
+
extensions: formats?.extensions ?? [],
|
|
2093
|
+
mounts: formats?.mounts ?? [],
|
|
2094
|
+
}
|
|
2095
|
+
: null,
|
|
2096
|
+
root,
|
|
2097
|
+
snapshot,
|
|
2098
|
+
subscribe(request, sink) {
|
|
2099
|
+
const response = answerSubscribe(log, request, snapshot);
|
|
2100
|
+
const sub: Subscriber = { sink };
|
|
2101
|
+
if (!closed) {
|
|
2102
|
+
subscribers.add(sub);
|
|
2103
|
+
}
|
|
2104
|
+
return {
|
|
2105
|
+
close() {
|
|
2106
|
+
subscribers.delete(sub);
|
|
2107
|
+
},
|
|
2108
|
+
response,
|
|
2109
|
+
};
|
|
2110
|
+
},
|
|
2111
|
+
write,
|
|
2112
|
+
};
|
|
2113
|
+
}
|