@valbuild/server 0.154.1 → 0.154.3

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.
Files changed (58) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/browser/dist/valbuild-server-browser.cjs.dev.js +6 -3
  3. package/browser/dist/valbuild-server-browser.cjs.prod.js +6 -3
  4. package/browser/dist/valbuild-server-browser.esm.js +6 -3
  5. package/dist/{ValRouterCore-cfb35067.cjs.prod.js → ValOpsMemory-18337353.cjs.prod.js} +23 -2013
  6. package/dist/{ValRouterCore-361673dc.cjs.dev.js → ValOpsMemory-45ba05ad.cjs.dev.js} +23 -2013
  7. package/dist/{ValRouterCore-be314bc7.esm.js → ValOpsMemory-972616ae.esm.js} +14 -1992
  8. package/dist/ValPatchStore-2f92eced.cjs.prod.js +1128 -0
  9. package/dist/ValPatchStore-df8cdbe7.cjs.dev.js +1128 -0
  10. package/dist/ValPatchStore-e23070df.esm.js +1119 -0
  11. package/dist/ValRouterCore-5b747abb.cjs.prod.js +612 -0
  12. package/dist/ValRouterCore-73eb843d.esm.js +608 -0
  13. package/dist/ValRouterCore-86757d56.cjs.dev.js +612 -0
  14. package/dist/createPrettierFormatter-05ad7480.cjs.prod.js +692 -0
  15. package/dist/createPrettierFormatter-1edca494.esm.js +673 -0
  16. package/dist/createPrettierFormatter-851fcf99.cjs.dev.js +692 -0
  17. package/dist/createValRuntime-472df6e8.cjs.prod.js +47 -0
  18. package/dist/createValRuntime-5cebf459.cjs.dev.js +47 -0
  19. package/dist/createValRuntime-c77ee010.esm.js +45 -0
  20. package/dist/declarations/src/ValOpsMemory.d.ts +3 -73
  21. package/dist/declarations/src/ValPatchStore.d.ts +92 -0
  22. package/dist/declarations/src/ValRouter.d.ts +1 -11
  23. package/dist/declarations/src/createPrettierFormatter.d.ts +18 -3
  24. package/dist/declarations/src/createValRuntime.d.ts +12 -0
  25. package/dist/declarations/src/draftReads.d.ts +11 -3
  26. package/dist/declarations/src/index.d.ts +4 -2
  27. package/dist/declarations/src/internal/index.d.ts +28 -6
  28. package/dist/declarations/src/proposal.d.ts +13 -25
  29. package/dist/declarations/src/proposalJsonEntries.d.ts +30 -0
  30. package/dist/declarations/src/serverMode.d.ts +31 -0
  31. package/dist/{draftReads-0dcddf72.cjs.prod.js → draftReads-3f7dcda5.cjs.prod.js} +10 -2
  32. package/dist/{draftReads-df44e629.cjs.dev.js → draftReads-a300a02f.cjs.dev.js} +10 -2
  33. package/dist/{draftReads-1f29aedd.esm.js → draftReads-bca0d49c.esm.js} +10 -2
  34. package/dist/{inTabFetch-7c8a5628.esm.js → inTabFetch-0c997998.esm.js} +2 -1
  35. package/dist/{inTabFetch-56226d62.cjs.prod.js → inTabFetch-c2efa1bd.cjs.prod.js} +5 -4
  36. package/dist/{inTabFetch-5d0314a3.cjs.dev.js → inTabFetch-db6d6425.cjs.dev.js} +5 -4
  37. package/dist/jsonValuesPatch-13acc674.esm.js +276 -0
  38. package/dist/jsonValuesPatch-88bc661d.cjs.dev.js +281 -0
  39. package/dist/jsonValuesPatch-92798812.cjs.prod.js +281 -0
  40. package/dist/proposalJsonEntries-0669f027.esm.js +480 -0
  41. package/dist/proposalJsonEntries-26f397bd.cjs.dev.js +500 -0
  42. package/dist/proposalJsonEntries-9e537244.cjs.prod.js +500 -0
  43. package/dist/{publishKit-707230bc.cjs.prod.js → publishKit-38d46a51.cjs.dev.js} +20 -22
  44. package/dist/{publishKit-5a8c9a0d.cjs.dev.js → publishKit-7aca03bb.cjs.prod.js} +20 -22
  45. package/dist/{publishKit-b850045b.esm.js → publishKit-ac0af189.esm.js} +8 -9
  46. package/dist/{ValRouter-9505c550.cjs.dev.js → valRuntime-2a3cc887.cjs.prod.js} +158 -6038
  47. package/dist/{ValRouter-31f89baf.cjs.prod.js → valRuntime-70ee2dc2.cjs.dev.js} +158 -6038
  48. package/dist/{ValRouter-b7dc784d.esm.js → valRuntime-e4d26702.esm.js} +107 -5937
  49. package/dist/valbuild-server.cjs.dev.js +5146 -352
  50. package/dist/valbuild-server.cjs.prod.js +5146 -352
  51. package/dist/valbuild-server.esm.js +4902 -132
  52. package/internal/browser/dist/valbuild-server-internal-browser.cjs.dev.js +7 -4
  53. package/internal/browser/dist/valbuild-server-internal-browser.cjs.prod.js +7 -4
  54. package/internal/browser/dist/valbuild-server-internal-browser.esm.js +7 -4
  55. package/internal/dist/valbuild-server-internal.cjs.dev.js +47 -31
  56. package/internal/dist/valbuild-server-internal.cjs.prod.js +47 -31
  57. package/internal/dist/valbuild-server-internal.esm.js +38 -22
  58. package/package.json +4 -4
@@ -0,0 +1,1119 @@
1
+ import { Internal } from '@valbuild/core';
2
+ import { memoryTier, tiered, bundleTier, moduleKey, EMPTY_CHAIN, baseModuleContent, applyPatchRecord, extendChain, entryState, engineWork, resolveEntry, parseModuleKey } from '@valbuild/shared/internal';
3
+
4
+ /**
5
+ * The patches a json entry render should apply, out of the whole chain:
6
+ *
7
+ * 1. this module's, since the chain is branch-wide;
8
+ * 2. a patch published after this build is kept: this build does not have it.
9
+ * One already in the build is dropped. `draftOverlay` decides which is
10
+ * which, from `commits`.
11
+ */
12
+
13
+ /**
14
+ * The patches a DRAFT applies on top of this build's own source: the pending
15
+ * ones, and the ones published AFTER this build, in chain order -- with
16
+ * `appliedAt` cleared on the latter, because this build has none of them.
17
+ *
18
+ * Content places every caller at its own build (`getApplicablePatchesAndCommits`
19
+ * in valbuild/home: "the earliest the caller has not seen") and returns the
20
+ * commits after it as `commits`. A patch applied at one of those was
21
+ * published after this build and is not in it, so a draft has to apply it --
22
+ * skipping it showed the build's old value from the publish until the next
23
+ * build went live. `/sources/~` already applies them (`getSources` walks every
24
+ * patch it is given); the `.jsonValues()` entry path skipped them.
25
+ *
26
+ * A patch applied at a commit NOT in that list is already in this build --
27
+ * content returns one only because it was asked for by id -- and is dropped:
28
+ * applying it again would apply it twice. Without `commits` (a store that
29
+ * does not report them) every applied patch is dropped, as before. Only
30
+ * `ValOpsHttp` ever reports `appliedAt`; `fs` and memory stores report `null`.
31
+ *
32
+ * Chain order, not published-first, because that is the order the Studio
33
+ * applies them in, and a draft page starts from the server's answer and is
34
+ * then kept up to date by the Studio's: the two must agree.
35
+ *
36
+ * For the reads that render a draft only. What to COMMIT still keys on
37
+ * `appliedAt`: a published patch must never be published again.
38
+ */
39
+ function draftOverlay(patches, commits) {
40
+ const afterThisBuild = new Set((commits ?? []).map(commit => commit.commitSha));
41
+ const overlay = [];
42
+ for (const patch of patches) {
43
+ if (patch.appliedAt === null) {
44
+ overlay.push(patch);
45
+ } else if (afterThisBuild.has(patch.appliedAt.commitSha)) {
46
+ overlay.push({
47
+ ...patch,
48
+ appliedAt: null
49
+ });
50
+ }
51
+ }
52
+ return overlay;
53
+ }
54
+
55
+ /*
56
+ * THE HEAD: the content at the newest chain, in the module store. See
57
+ * `docs/plans/one-content-model.md`, "One runtime per process, and the head".
58
+ *
59
+ * One per data layer (`ValOps`), and so one per process for a project
60
+ * (`valRuntime`): the API route, the draft readers and MCP read through the
61
+ * same one, so a save moves every reader, and one head serves every editor --
62
+ * draft content is not per user; the session only decides who may see it.
63
+ *
64
+ * In a 128 MB isolate it grows only with what was edited:
65
+ *
66
+ * 1. An unpatched module costs nothing: the bundle tier answers with the
67
+ * bundle's own object, which the process holds for every visitor anyway.
68
+ * 2. A module is materialized when it is read and has patches, never all at
69
+ * once, and the next version of its chain is EXTENDED from the one before
70
+ * by the new patches alone.
71
+ * 3. A discard replays one module from its base through its own patches.
72
+ * 4. The memory tier's byte budget ({@link HEAD_BUDGET_BYTES}) lets go of the
73
+ * least recently read module, which is made again on its next read; and
74
+ * it keeps the last {@link HEAD_VERSIONS_PER_MODULE} versions of each.
75
+ * 5. No validation and no previews on the read path. They are their own
76
+ * requests (`/validate`, the Studio's own previews).
77
+ *
78
+ * "Has the chain moved?" is `seq` alone (`ValOps.chainSeq`): a counter in fs
79
+ * and memory mode, one small read of the content service in http mode. The
80
+ * chain is fetched only when it moved.
81
+ */
82
+
83
+ /**
84
+ * What the head may hold beyond what the build holds anyway: 16 MB, about
85
+ * where a deployed isolate beside 64 MB of other heap stopped outliving a
86
+ * validated whole-tree draft read (`scenarios/measure/results.md`, "The
87
+ * deployed isolate").
88
+ */
89
+ const HEAD_BUDGET_BYTES = 16 * 1024 * 1024;
90
+
91
+ /** The current version of each module and the one before it. */
92
+ const HEAD_VERSIONS_PER_MODULE = 2;
93
+
94
+ /**
95
+ * Counted work, in this process, for every head: never reset, so two readers
96
+ * of it cannot disturb each other. A test takes it before and after.
97
+ */
98
+ const counted = {
99
+ /** "Has the chain moved?" asked. */
100
+ seqReads: 0,
101
+ /** The chain fetched, because it had. */
102
+ chainReads: 0,
103
+ /** Modules made from a base or an older version. */
104
+ materialized: 0,
105
+ /** Of those, made by extending the version before by the new patches alone. */
106
+ extended: 0,
107
+ /**
108
+ * A record's whole key list walked: once per record object (a base, a
109
+ * version), never per request -- see {@link recordKeysOf}.
110
+ */
111
+ recordScans: 0,
112
+ /** `.jsonValues()` entries resolved: once per entry and version. */
113
+ entriesResolved: 0
114
+ };
115
+ const recordKeys = new WeakMap();
116
+
117
+ /**
118
+ * A record's keys, in order: walked once per record OBJECT and kept beside
119
+ * it. A record is immutable (a base, or a version the engine made), so the
120
+ * same object has the same keys for good -- and an entry request, which only
121
+ * needs the count (`total`) or a window of them, costs what it asks for,
122
+ * not the size of the record. Before, every `GET /json` walked the whole
123
+ * record (`Object.keys`), so reading 10,000 entries one request at a time
124
+ * was 10,000 x 10,000 (phase 10's baseline).
125
+ */
126
+ function recordKeysOf(record) {
127
+ let keys = recordKeys.get(record);
128
+ if (keys === undefined) {
129
+ counted.recordScans++;
130
+ keys = Object.keys(record);
131
+ recordKeys.set(record, keys);
132
+ }
133
+ return keys;
134
+ }
135
+
136
+ /** See {@link counted}. */
137
+ function headWork() {
138
+ return {
139
+ ...counted
140
+ };
141
+ }
142
+
143
+ /** The chain, as the head last read it. */
144
+
145
+ /** What the head knows about a module it made, beside its content. */
146
+
147
+ /** A module as the head answers it. */
148
+
149
+ /**
150
+ * What a draft reader is given for a module: the bundle's own (read the
151
+ * bundle), or the head's source in its wire shape -- `.jsonValues()` markers
152
+ * without their `import()`, and the entries the draft changes in place of
153
+ * theirs.
154
+ */
155
+
156
+ /** One entry, as `/json` and the draft readers answer it. */
157
+
158
+ class ValHead {
159
+ memory;
160
+ store;
161
+ facts = new WeakMap();
162
+ chain = null;
163
+ fetching = null;
164
+ serialized = null;
165
+ wholeTree = null;
166
+ constructor(ops, opts = {}) {
167
+ this.ops = ops;
168
+ this.memory = memoryTier({
169
+ budgetBytes: opts.budgetBytes ?? HEAD_BUDGET_BYTES,
170
+ lastPerModule: opts.lastPerModule ?? HEAD_VERSIONS_PER_MODULE
171
+ });
172
+ this.store = tiered([this.memory, bundleTier(path => this.ops.bundleModule(path)),
173
+ // What the build serves where it is not the bundle: a content version,
174
+ // a proposal's saves, a publish adopted in this process.
175
+ bundleTier(path => this.ops.baseModule(path), "base")]);
176
+ }
177
+
178
+ /** What the head holds now. */
179
+ stats() {
180
+ return this.memory.stats();
181
+ }
182
+
183
+ // #region the chain
184
+
185
+ /**
186
+ * The chain, re-read only when `seq` moved (or the base did: a publish
187
+ * adopted). A read that finds a fetch already under way at the `seq` it
188
+ * saw joins it: that fetch reads at that `seq` or later.
189
+ *
190
+ * Asks "has the chain moved?" once per call -- in http mode one request to
191
+ * the content service. A caller that reads several modules for ONE answer
192
+ * (a draft page's request) syncs once and passes the chain it got to
193
+ * {@link draft}, {@link entries} and {@link changed}, so a page of thirty
194
+ * modules asks once, not thirty times, and reads all of them at one chain.
195
+ */
196
+ async sync() {
197
+ counted.seqReads++;
198
+ const [position, base] = await Promise.all([this.ops.chainPosition(), this.ops.getSourcesSha()]);
199
+ const held = this.chain;
200
+ if (held !== null && position !== null && held.seq === position.seq && held.epoch === position.epoch && held.base === base) {
201
+ return {
202
+ ok: held
203
+ };
204
+ }
205
+ const fetching = this.fetching;
206
+ if (position !== null && fetching !== null && fetching.seq === position.seq && fetching.epoch === position.epoch) {
207
+ return fetching.promise;
208
+ }
209
+ const promise = this.fetchChain(position, base);
210
+ if (position !== null) {
211
+ const started = {
212
+ ...position,
213
+ promise
214
+ };
215
+ this.fetching = started;
216
+ // Cleared however it ends. `finally` would hand on a rejection to a
217
+ // promise nobody holds: an unhandled rejection, which ends a Node
218
+ // process. The caller is handed `promise` itself, and sees it.
219
+ const done = () => {
220
+ if (this.fetching === started) this.fetching = null;
221
+ };
222
+ promise.then(done, done);
223
+ }
224
+ return promise;
225
+ }
226
+
227
+ /** The chain a read is answered at: the one given, or the newest. */
228
+ at(chain) {
229
+ return chain !== undefined ? Promise.resolve({
230
+ ok: chain
231
+ }) : this.sync();
232
+ }
233
+ async fetchChain(position, base) {
234
+ counted.chainReads++;
235
+ const before = await this.ops.projectVersion();
236
+ const fetched = await this.ops.fetchPatches({
237
+ excludePatchOps: false
238
+ });
239
+ if (fetched.error) {
240
+ return {
241
+ error: {
242
+ message: fetched.error.message,
243
+ ...(fetched.unauthorized ? {
244
+ unauthorized: true
245
+ } : {}),
246
+ ...(fetched.networkError ? {
247
+ networkError: true
248
+ } : {})
249
+ }
250
+ };
251
+ }
252
+ const overlay = draftOverlay(fetched.patches, fetched.commits);
253
+ const byModule = new Map();
254
+ for (const patch of overlay) {
255
+ const records = byModule.get(patch.path);
256
+ if (records === undefined) byModule.set(patch.path, [patch]);else records.push(patch);
257
+ }
258
+ const versions = await this.ops.moduleVersions(overlay);
259
+ const project = fetched.headVersion !== undefined ? {
260
+ build: before.build,
261
+ seq: fetched.headVersion
262
+ } : before;
263
+ const chain = {
264
+ seq: fetched.headVersion ?? (position === null || position === void 0 ? void 0 : position.seq) ?? null,
265
+ epoch: (position === null || position === void 0 ? void 0 : position.epoch) ?? "",
266
+ base,
267
+ project,
268
+ fetched,
269
+ overlay,
270
+ byModule,
271
+ versions,
272
+ analysis: this.ops.analyzePatches(overlay)
273
+ };
274
+ // Never put back an older chain over a newer one read meanwhile. A
275
+ // counter that started again (another epoch) orders nothing against
276
+ // the one before it: the chain read last is the newest.
277
+ if (this.chain === null || this.chain.base !== base || this.chain.epoch !== chain.epoch || this.chain.project.seq <= project.seq) {
278
+ this.chain = chain;
279
+ }
280
+ return {
281
+ ok: chain
282
+ };
283
+ }
284
+
285
+ /**
286
+ * Every module's serialized schema, serialized once per data layer (a new
287
+ * build is a new one): what the engine reads `.jsonValues()` records from,
288
+ * and MCP's tools their schemas.
289
+ */
290
+ serializedSchemas() {
291
+ this.serialized ??= this.ops.getSchemas().then(schemas => {
292
+ const serialized = {};
293
+ for (const [path, schema] of Object.entries(schemas)) {
294
+ try {
295
+ serialized[path] = schema["executeSerialize"]();
296
+ } catch {
297
+ // Reported elsewhere; read as "no schema", as the engine does.
298
+ serialized[path] = undefined;
299
+ }
300
+ }
301
+ return serialized;
302
+ });
303
+ return this.serialized;
304
+ }
305
+
306
+ // #region modules
307
+
308
+ /**
309
+ * A module at the newest chain (or at `chain`, from {@link sync}), or
310
+ * `null` when there is no such module.
311
+ */
312
+ async module(path, chain) {
313
+ const synced = await this.at(chain);
314
+ if ("error" in synced) return synced;
315
+ return {
316
+ ok: await this.moduleIn(synced.ok, path)
317
+ };
318
+ }
319
+ async moduleIn(chain, path) {
320
+ const asked = versionIn(chain, path);
321
+ if (asked === undefined) return null;
322
+ const records = chain.byModule.get(path) ?? [];
323
+ const key = moduleKey(path, asked);
324
+ const found = await this.store.get(key);
325
+ if (found !== null) {
326
+ const facts = this.factsOf(found);
327
+ return {
328
+ module: found,
329
+ asked,
330
+ failed: facts.failed,
331
+ applied: facts.applied,
332
+ records
333
+ };
334
+ }
335
+ const made = await this.make(path, asked, records);
336
+ this.memory.put(key, made, made.bytes);
337
+ const facts = this.factsOf(made);
338
+ return {
339
+ module: made,
340
+ asked,
341
+ failed: facts.failed,
342
+ applied: facts.applied,
343
+ records
344
+ };
345
+ }
346
+
347
+ /**
348
+ * A module at `asked`, from the newest version held of the same base when
349
+ * its chain is a start of this one (a keystroke: the new patch alone), and
350
+ * from its base otherwise (a discard, a publish, an eviction).
351
+ */
352
+ async make(path, asked, records) {
353
+ var _await$this$ops$baseM;
354
+ counted.materialized++;
355
+ const schema = (await this.serializedSchemas())[path];
356
+ const isRecord = (schema === null || schema === void 0 ? void 0 : schema.type) === "record" && schema.jsonValues === true;
357
+ let start = null;
358
+ const latest = this.memory.latest(path);
359
+ if (latest !== null && latest.version.schema === asked.schema && latest.version.base === asked.base && this.factsOf(latest).failed === null && latest.patches.length <= records.length && latest.patches.every((id, i) => {
360
+ var _records$i;
361
+ return ((_records$i = records[i]) === null || _records$i === void 0 ? void 0 : _records$i.patchId) === id;
362
+ })) {
363
+ start = latest;
364
+ counted.extended++;
365
+ }
366
+ if (start === null) {
367
+ start = await this.store.get(moduleKey(path, {
368
+ ...asked,
369
+ chain: EMPTY_CHAIN
370
+ }));
371
+ }
372
+ if (start === null) {
373
+ // No base for this version: the module as the build serves it.
374
+ const base = await this.ops.baseModule(path);
375
+ start = {
376
+ path,
377
+ version: {
378
+ ...asked,
379
+ chain: EMPTY_CHAIN
380
+ },
381
+ content: baseModuleContent((base === null || base === void 0 ? void 0 : base.source) ?? null),
382
+ patches: [],
383
+ bytes: 0
384
+ };
385
+ }
386
+ const startFacts = this.factsOf(start);
387
+ let content = start.content;
388
+ const ids = [...start.patches];
389
+ let failed = null;
390
+ let entryChains = startFacts.entryChains;
391
+ let wholeChain = startFacts.wholeChain;
392
+ for (const record of records.slice(start.patches.length)) {
393
+ const res = applyPatchRecord(content, record, schema);
394
+ if (res.status === "failed") {
395
+ failed = {
396
+ patchId: res.patchId,
397
+ message: res.message
398
+ };
399
+ break;
400
+ }
401
+ if (isRecord) {
402
+ const touched = touchedEntries(content, res.module);
403
+ if (touched === "all") {
404
+ wholeChain = extendChain(wholeChain, record.patchId);
405
+ entryChains = new Map();
406
+ } else if (touched.length > 0) {
407
+ const next = new Map(entryChains);
408
+ for (const key of touched) {
409
+ next.set(key, extendChain(entryChains.get(key) ?? wholeChain, record.patchId));
410
+ }
411
+ entryChains = next;
412
+ }
413
+ }
414
+ content = res.module;
415
+ ids.push(record.patchId);
416
+ }
417
+ const base = start.patches.length === 0 ? start.content.source : ((_await$this$ops$baseM = await this.ops.baseModule(path)) === null || _await$this$ops$baseM === void 0 ? void 0 : _await$this$ops$baseM.source) ?? null;
418
+ const bytes = heldBeyond(base, content.source) + entriesBytes(content);
419
+ const version = failed === null ? asked : {
420
+ ...asked,
421
+ chain: this.ops.chainAt(path, ids.length)
422
+ };
423
+ const made = {
424
+ path,
425
+ version,
426
+ content,
427
+ patches: ids,
428
+ bytes
429
+ };
430
+ this.facts.set(made, {
431
+ failed,
432
+ applied: ids.length,
433
+ entryChains,
434
+ wholeChain,
435
+ resolved: new Map(),
436
+ draft: null
437
+ });
438
+ return made;
439
+ }
440
+ factsOf(module) {
441
+ let facts = this.facts.get(module);
442
+ if (facts === undefined) {
443
+ facts = {
444
+ failed: null,
445
+ applied: module.patches.length,
446
+ entryChains: new Map(),
447
+ wholeChain: EMPTY_CHAIN,
448
+ resolved: new Map(),
449
+ draft: null
450
+ };
451
+ this.facts.set(module, facts);
452
+ }
453
+ return facts;
454
+ }
455
+
456
+ // #region entries
457
+
458
+ /**
459
+ * `.jsonValues()` entries at the newest chain (or at `chain`, from
460
+ * {@link sync}), by key: what the module's chain made of each, and for an
461
+ * entry it holds edits for but nobody has loaded, those edits on the base
462
+ * entry. Made once per entry and version.
463
+ */
464
+ async entries(path, keys, chain) {
465
+ const synced = await this.at(chain);
466
+ if ("error" in synced) {
467
+ return {
468
+ status: "error",
469
+ message: synced.error.message
470
+ };
471
+ }
472
+ return this.entriesIn(synced.ok, path, keys);
473
+ }
474
+ async entriesIn(chain, path, keys) {
475
+ if (chain.fetched.errors && chain.fetched.errors.length > 0) {
476
+ return {
477
+ status: "error",
478
+ message: `Could not fetch patches: ${JSON.stringify(chain.fetched.errors)}`
479
+ };
480
+ }
481
+ const base = await this.ops.baseModule(path);
482
+ if (base === null || base.source === null || typeof base.source !== "object" || Array.isArray(base.source)) {
483
+ return {
484
+ status: "not-found",
485
+ message: base === null || base.source === null ? `Module not found: ${path}` : `Module is not a record: ${path}`
486
+ };
487
+ }
488
+ const held = await this.moduleIn(chain, path);
489
+ if (held === null) {
490
+ return {
491
+ status: "not-found",
492
+ message: `Module not found: ${path}`
493
+ };
494
+ }
495
+ const record = base.source;
496
+ const facts = this.factsOf(held.module);
497
+ const value = {
498
+ entries: [],
499
+ missing: [],
500
+ errors: [],
501
+ total: recordKeysOf(record).length,
502
+ version: held.module.version,
503
+ entryVersions: {}
504
+ };
505
+ const reads = new Map();
506
+ await Promise.all(keys.map(async key => {
507
+ reads.set(key, await this.resolved(path, record, held.module, key));
508
+ }));
509
+ for (const key of keys) {
510
+ const marker = record[key];
511
+ if (marker !== undefined && !Internal.isJson(marker)) {
512
+ // Not a jsonValues entry: the value inlined in the module, as is.
513
+ value.entries.push({
514
+ key,
515
+ content: marker
516
+ });
517
+ continue;
518
+ }
519
+ const read = reads.get(key);
520
+ if (read === undefined || read.kind === "missing") {
521
+ value.missing.push(key);
522
+ } else if (read.kind === "error") {
523
+ value.errors.push({
524
+ key,
525
+ message: read.message
526
+ });
527
+ } else {
528
+ value.entries.push({
529
+ key,
530
+ content: read.content
531
+ });
532
+ value.entryVersions[key] = {
533
+ ...held.module.version,
534
+ key,
535
+ chain: facts.entryChains.get(key) ?? facts.wholeChain
536
+ };
537
+ }
538
+ }
539
+ return {
540
+ status: "success",
541
+ value
542
+ };
543
+ }
544
+
545
+ /**
546
+ * An entry on `module`, resolved once and kept on it -- unless it could
547
+ * not be read (`transient`): that is tried again on the next read rather
548
+ * than kept for the version's life.
549
+ */
550
+ async resolved(path, baseRecord, module, key) {
551
+ const facts = this.factsOf(module);
552
+ const kept = facts.resolved.get(key);
553
+ if (kept !== undefined) return kept;
554
+ const read = await this.resolve(path, baseRecord, module, key);
555
+ if (!(read.kind === "error" && read.transient === true)) {
556
+ facts.resolved.set(key, read);
557
+ }
558
+ return read;
559
+ }
560
+ async resolve(path, baseRecord, module, key) {
561
+ counted.entriesResolved++;
562
+ const state = entryState(module.content, key);
563
+ let from = {
564
+ content: undefined
565
+ };
566
+ if ((state === null || state === void 0 ? void 0 : state.kind) === "waiting") {
567
+ from = await this.ops.baseJsonEntry(path, baseRecord, state.from);
568
+ if ("message" in from) {
569
+ return {
570
+ kind: "error",
571
+ message: from.message,
572
+ transient: true
573
+ };
574
+ }
575
+ }
576
+ const copiedBefore = engineWork().cloneBytes;
577
+ const read = resolveEntry(key, state, () => "content" in from ? from.content : undefined);
578
+ if (read.kind === "content" && (state === null || state === void 0 ? void 0 : state.kind) === "waiting" && state.ops) {
579
+ // Held edits made a new entry: the head holds it now.
580
+ this.memory.charge(moduleKey(path, module.version), engineWork().cloneBytes - copiedBefore);
581
+ }
582
+ return read;
583
+ }
584
+
585
+ // #region drafts
586
+
587
+ /**
588
+ * A module as a draft reader is given it ({@link Draft}): `bundle` when the
589
+ * newest version is the bundle's own -- the reader's bundle answers, and
590
+ * nothing is read -- and otherwise the head's, made once per version.
591
+ */
592
+ async draft(path, chain) {
593
+ const synced = await this.at(chain);
594
+ if ("error" in synced) return synced;
595
+ const asked = versionIn(synced.ok, path);
596
+ if (asked === undefined) return {
597
+ ok: null
598
+ };
599
+ const bundle = await this.ops.bundleModule(path);
600
+ if (bundle !== null && asked.chain === EMPTY_CHAIN && bundle.version.schema === asked.schema && bundle.version.base === asked.base) {
601
+ return {
602
+ ok: {
603
+ kind: "bundle",
604
+ version: asked
605
+ }
606
+ };
607
+ }
608
+ const held = await this.moduleIn(synced.ok, path);
609
+ if (held === null) return {
610
+ ok: null
611
+ };
612
+ const facts = this.factsOf(held.module);
613
+ if (facts.draft !== null) return {
614
+ ok: facts.draft
615
+ };
616
+ const made = await this.makeDraft(synced.ok, path, held);
617
+ // Kept for the version, unless its entries could not be read: the next
618
+ // read tries them again rather than serving markers for the version's
619
+ // life.
620
+ if (made.kind !== "draft" || !made.entriesFailed) facts.draft = made;
621
+ return {
622
+ ok: made
623
+ };
624
+ }
625
+
626
+ /**
627
+ * The draft of `held`, its entries read at `chain` -- the chain `held` was
628
+ * made at, so the entries are the same version's even when the chain has
629
+ * moved since.
630
+ */
631
+ async makeDraft(chain, path, held) {
632
+ const source = held.module.content.source;
633
+ const version = held.module.version;
634
+ if (!isRecordOfMarkers(source)) {
635
+ return {
636
+ kind: "draft",
637
+ version,
638
+ source,
639
+ changed: held.records.length > 0,
640
+ entriesFailed: false
641
+ };
642
+ }
643
+ // The entries a draft changes: the ones the chain touched, and the ones
644
+ // a publish wrote that the bundle has not got (a marker with a
645
+ // `patch_id`). Every other one is the bundle's, behind its marker.
646
+ const wire = {};
647
+ const fill = [];
648
+ const touched = held.module.content.entries;
649
+ let fromServer = false;
650
+ for (const [key, value] of Object.entries(source)) {
651
+ if (Internal.isJson(value)) {
652
+ wire[key] = transportMarker(value);
653
+ const published = Internal.isJsonFromServer(value);
654
+ fromServer ||= published;
655
+ if (published || touched.has(key)) fill.push(key);
656
+ } else {
657
+ wire[key] = value;
658
+ }
659
+ }
660
+ let entriesFailed = false;
661
+ if (fill.length > 0) {
662
+ const read = await this.entriesIn(chain, path, fill);
663
+ if (read.status !== "success" || read.value.errors.length > 0 || read.value.missing.length > 0) {
664
+ entriesFailed = true;
665
+ } else {
666
+ for (const {
667
+ key,
668
+ content
669
+ } of read.value.entries) {
670
+ wire[key] = content;
671
+ }
672
+ }
673
+ }
674
+ return {
675
+ kind: "draft",
676
+ version,
677
+ source: entriesFailed ? stripped(source) : wire,
678
+ changed: held.records.length > 0 || fromServer,
679
+ entriesFailed
680
+ };
681
+ }
682
+
683
+ /**
684
+ * The modules a draft changes: a patch in their chain, or an entry a
685
+ * publish wrote that the bundle has not got. What `fetchValDraft` sends.
686
+ */
687
+ async changed(at) {
688
+ var _made;
689
+ const synced = await this.at(at);
690
+ if ("error" in synced) return synced;
691
+ const chain = synced.ok;
692
+ let made = this.changedIn;
693
+ if (((_made = made) === null || _made === void 0 ? void 0 : _made.chain) !== chain) {
694
+ made = {
695
+ chain,
696
+ paths: this.changedOf(chain)
697
+ };
698
+ this.changedIn = made;
699
+ }
700
+ return {
701
+ ok: [...(await made.paths)]
702
+ };
703
+ }
704
+
705
+ /** {@link changed}, made once per chain: it looks at every record's markers. */
706
+ changedIn = null;
707
+ async changedOf(chain) {
708
+ const changed = new Set(chain.byModule.keys());
709
+ for (const path of Object.keys(chain.versions)) {
710
+ if (changed.has(path)) continue;
711
+ const base = await this.ops.baseModule(path);
712
+ if (base !== null && hasMarkersFromServer(base.source)) changed.add(path);
713
+ }
714
+ return [...changed];
715
+ }
716
+
717
+ // #region the whole tree
718
+
719
+ /**
720
+ * Every module at the newest chain: the patched ones made (once per
721
+ * version), the rest the base's own objects. What `PUT /sources/~` and
722
+ * MCP read; made once per chain.
723
+ */
724
+ async tree() {
725
+ var _this$wholeTree;
726
+ const synced = await this.sync();
727
+ if ("error" in synced) return synced;
728
+ const chain = synced.ok;
729
+ if (((_this$wholeTree = this.wholeTree) === null || _this$wholeTree === void 0 ? void 0 : _this$wholeTree.chain) !== chain) {
730
+ this.wholeTree = {
731
+ chain,
732
+ promise: this.makeTree(chain)
733
+ };
734
+ }
735
+ return this.wholeTree.promise;
736
+ }
737
+ async makeTree(chain) {
738
+ const base = await this.ops.getBaseSources();
739
+ const sources = {
740
+ ...base
741
+ };
742
+ const errors = {};
743
+ const stopped = {};
744
+ const versions = {
745
+ ...chain.versions
746
+ };
747
+ for (const patch of chain.overlay) {
748
+ if (base[patch.path] === undefined && errors[patch.path] === undefined) {
749
+ errors[patch.path] = [];
750
+ }
751
+ }
752
+ for (const [path, records] of chain.byModule) {
753
+ if (base[path] === undefined) {
754
+ Internal.log.error("Module not found", path);
755
+ errors[path] = records.map(record => ({
756
+ patchId: record.patchId,
757
+ skipped: true,
758
+ error: {
759
+ message: "Module not found"
760
+ }
761
+ }));
762
+ continue;
763
+ }
764
+ const held = await this.moduleIn(chain, path);
765
+ if (held === null) continue;
766
+ sources[path] = held.module.content.source;
767
+ versions[path] = held.module.version;
768
+ if (held.failed !== null) {
769
+ Internal.log.error("Could not apply patch", {
770
+ path,
771
+ patchId: held.failed.patchId,
772
+ error: held.failed.message
773
+ });
774
+ stopped[path] = held.applied;
775
+ errors[path] = [{
776
+ patchId: held.failed.patchId,
777
+ skipped: false,
778
+ error: {
779
+ message: held.failed.message
780
+ }
781
+ }, ...records.slice(held.applied + 1).map(record => ({
782
+ patchId: record.patchId,
783
+ skipped: true,
784
+ error: {
785
+ message: "Cannot apply patch: previous errors exists"
786
+ }
787
+ }))];
788
+ }
789
+ }
790
+ for (const [path, list] of Object.entries(errors)) {
791
+ if (list.length === 0) delete errors[path];
792
+ }
793
+ return {
794
+ ok: {
795
+ chain,
796
+ sources,
797
+ errors,
798
+ stopped,
799
+ versions
800
+ }
801
+ };
802
+ }
803
+
804
+ // #region the module endpoint
805
+
806
+ /**
807
+ * `GET /modules`: one module at a version. `v` the version wanted (by
808
+ * default the newest); `have` the version the caller holds, from which the
809
+ * answer is a delta -- the patches from it -- when the caller's chain is a
810
+ * start of this one under the same schema and base.
811
+ */
812
+ async answer(path, opts) {
813
+ const synced = await this.sync();
814
+ if ("error" in synced) return synced;
815
+ const chain = synced.ok;
816
+ const current = await this.moduleIn(chain, path);
817
+ if (current === null) return {
818
+ ok: null
819
+ };
820
+ let target = current.module;
821
+ let isCurrent = true;
822
+ if (opts.v !== undefined) {
823
+ const wanted = parseModuleKey(opts.v);
824
+ if (wanted === null || wanted.path !== path) {
825
+ return {
826
+ ok: {
827
+ kind: "not-held",
828
+ current: current.module.version
829
+ }
830
+ };
831
+ }
832
+ const currentKeys = [moduleKey(path, current.module.version), moduleKey(path, current.asked)];
833
+ if (!currentKeys.includes(opts.v)) {
834
+ const held = await this.store.get(opts.v);
835
+ if (held === null) {
836
+ return {
837
+ ok: {
838
+ kind: "not-held",
839
+ current: current.module.version
840
+ }
841
+ };
842
+ }
843
+ target = held;
844
+ isCurrent = false;
845
+ }
846
+ }
847
+ const have = opts.have !== undefined ? parseModuleKey(opts.have) : null;
848
+ if (isCurrent && have !== null && have.path === path && have.version.schema === target.version.schema && have.version.base === target.version.base) {
849
+ const facts = this.factsOf(target);
850
+ for (let n = facts.applied; n >= 0; n--) {
851
+ if (this.ops.chainAt(path, n) === have.version.chain) {
852
+ return {
853
+ ok: {
854
+ kind: "delta",
855
+ from: have.version,
856
+ to: target.version,
857
+ patches: current.records.slice(n, facts.applied).map(({
858
+ patchId,
859
+ patch
860
+ }) => ({
861
+ patchId,
862
+ patch
863
+ }))
864
+ }
865
+ };
866
+ }
867
+ }
868
+ }
869
+ const facts = this.factsOf(target);
870
+ const source = target.content.source;
871
+ const entries = {};
872
+ if (isRecordOfMarkers(source)) {
873
+ const baseModule = await this.ops.baseModule(path);
874
+ const baseRecord = baseModule !== null && typeof baseModule.source === "object" && baseModule.source !== null && !Array.isArray(baseModule.source) ? baseModule.source : {};
875
+ for (const key of target.content.entries.keys()) {
876
+ const read = await this.resolved(path, baseRecord, target, key);
877
+ const version = {
878
+ ...target.version,
879
+ key,
880
+ chain: facts.entryChains.get(key) ?? facts.wholeChain
881
+ };
882
+ entries[key] = read.kind === "content" ? {
883
+ content: read.content,
884
+ version
885
+ } : read.kind === "missing" ? {
886
+ deleted: true,
887
+ version
888
+ } : {
889
+ error: read.message,
890
+ ...(read.patchId !== undefined ? {
891
+ patchId: read.patchId
892
+ } : {}),
893
+ version
894
+ };
895
+ }
896
+ }
897
+ return {
898
+ ok: {
899
+ kind: "module",
900
+ version: target.version,
901
+ source: isRecordOfMarkers(source) ? stripped(source) : source,
902
+ entries,
903
+ patches: [...target.patches],
904
+ ...(facts.failed !== null ? {
905
+ failed: facts.failed
906
+ } : {})
907
+ }
908
+ };
909
+ }
910
+ }
911
+
912
+ /** What {@link ValHead.entries} answers. */
913
+
914
+ /**
915
+ * A module's version at `chain`. `versions` is keyed by module path, and a
916
+ * path comes from a request: `~constructor` is not a module.
917
+ */
918
+ function versionIn(chain, path) {
919
+ return Object.hasOwn(chain.versions, path) ? chain.versions[path] : undefined;
920
+ }
921
+
922
+ /**
923
+ * Whether an answer of {@link ValHead.answer} is the same for good, so an
924
+ * answer for an asked version may be cached as immutable: not when an
925
+ * entry's content could not be READ (it carries no `patchId`; its base's
926
+ * `import()` failed, and the next read may succeed). An entry a patch could
927
+ * not be applied to names that patch, and is the version's for good.
928
+ */
929
+ function isLastingAnswer(answer) {
930
+ if (answer.kind !== "module") return true;
931
+ return Object.values(answer.entries).every(entry => !("error" in entry) || entry.patchId !== undefined);
932
+ }
933
+
934
+ /** What {@link ValHead.tree} answers. */
935
+
936
+ /** What `GET /modules` answers: see `ModuleAnswer` in the plan. */
937
+
938
+ /**
939
+ * The entries a patch touched: the ones whose state it replaced, or `all`
940
+ * when it replaced the record (every entry went, or the map was reset).
941
+ */
942
+ function touchedEntries(before, after) {
943
+ if (after.entries === before.entries) return [];
944
+ if (after.entries.size < before.entries.size) return "all";
945
+ const touched = [];
946
+ for (const [key, state] of after.entries) {
947
+ if (before.entries.get(key) !== state) touched.push(key);
948
+ }
949
+ return touched;
950
+ }
951
+
952
+ /**
953
+ * What `next` holds that `base` does not: every container copy-on-write made
954
+ * (8 bytes a slot, as the engine counts them) and every string a patch
955
+ * brought, walking only where the two differ -- a subtree the patches did not
956
+ * touch is the base's own object, which the build holds anyway. A child that
957
+ * is one of the base container's own children (moved, or shifted by an
958
+ * insert) costs nothing. What the head's byte budget is measured in.
959
+ */
960
+ function heldBeyond(base, next) {
961
+ if (base === next) return 0;
962
+ if (typeof next === "string") return next.length;
963
+ if (typeof next !== "object" || next === null) return 8;
964
+ const shared = new Set(typeof base === "object" && base !== null ? Object.values(base) : []);
965
+ let bytes = 0;
966
+ if (Array.isArray(next)) {
967
+ bytes += 8 * next.length;
968
+ for (const [index, child] of next.entries()) {
969
+ if (shared.has(child)) continue;
970
+ bytes += heldBeyond(Array.isArray(base) ? base[index] : undefined, child);
971
+ }
972
+ return bytes;
973
+ }
974
+ const record = base;
975
+ for (const [key, child] of Object.entries(next)) {
976
+ bytes += 8;
977
+ if (shared.has(child)) continue;
978
+ bytes += heldBeyond(typeof record === "object" && record !== null && !Array.isArray(record) ? record[key] : undefined, child);
979
+ }
980
+ return bytes;
981
+ }
982
+
983
+ /** What the entries a chain wrote hold: their content, which patches brought. */
984
+ function entriesBytes(content) {
985
+ let bytes = 8 * content.entries.size;
986
+ for (const state of content.entries.values()) {
987
+ if (state.kind === "content") bytes += heldBeyond(undefined, state.content);
988
+ }
989
+ return bytes;
990
+ }
991
+ function isRecordOfMarkers(source) {
992
+ return typeof source === "object" && source !== null && !Array.isArray(source) && Object.values(source).some(value => Internal.isJson(value));
993
+ }
994
+ function hasMarkersFromServer(source) {
995
+ return isRecordOfMarkers(source) && Object.values(source).some(value => Internal.isJsonFromServer(value));
996
+ }
997
+
998
+ /** A marker as it travels: without the `import()` only this process can run. */
999
+ function transportMarker(marker) {
1000
+ if (typeof marker !== "object" || marker === null || Array.isArray(marker)) {
1001
+ return marker;
1002
+ }
1003
+ const copy = {};
1004
+ for (const [key, value] of Object.entries(marker)) {
1005
+ if (typeof value !== "function") copy[key] = value;
1006
+ }
1007
+ return copy;
1008
+ }
1009
+
1010
+ /** A record of markers, as it travels. */
1011
+ function stripped(source) {
1012
+ const wire = {};
1013
+ for (const [key, value] of Object.entries(source)) {
1014
+ wire[key] = Internal.isJson(value) ? transportMarker(value) : value;
1015
+ }
1016
+ return wire;
1017
+ }
1018
+
1019
+ /*
1020
+ * Where memory mode keeps pending patches, apart from `ValOpsMemory` itself:
1021
+ * a host constructs an `InMemoryPatchStore` at module scope (to hand the
1022
+ * SAME store to `initValServer` and `initValContent`), and that must not
1023
+ * evaluate the data layer -- TypeScript, sucrase, the Studio -- on a site
1024
+ * that only ever serves published pages.
1025
+ */
1026
+ /**
1027
+ * One stored patch. Everything the ordered chain needs and nothing else.
1028
+ */
1029
+
1030
+ /**
1031
+ * One pending binary file: an upload that has not been published yet.
1032
+ *
1033
+ * Keyed by the patch that carries it, exactly as `fs` mode keys the directory
1034
+ * it writes to. The patch's own `file` op holds a hash, not the bytes, so these
1035
+ * arrive on their own request and are joined up by `(patchId, filePath)`.
1036
+ */
1037
+
1038
+ /**
1039
+ * Where pending patches live.
1040
+ *
1041
+ * The point of the interface: `ValOpsMemory` is not tied to memory. The default
1042
+ * implementation below is explicitly NOT durable -- it dies with the process,
1043
+ * or in a Worker with the isolate -- and a durable one (a Durable Object, whose
1044
+ * single-threaded execution is the lock Val's fs store builds out of a file)
1045
+ * is a swap rather than a rewrite.
1046
+ *
1047
+ * ORDER IS THE CONTRACT. `list()` returns patch ids in the order they were
1048
+ * written, and that order is the chain: entry i's parent is entry i-1. This is
1049
+ * the same decision `ValOpsFS` makes with `patches.log` -- the server decides
1050
+ * where a patch goes, and it goes last -- and it exists for the same reason: an
1051
+ * order held in the patches themselves lets a client working from a stale view
1052
+ * strand every patch behind a parent that never landed.
1053
+ */
1054
+
1055
+ /** The default store. Not durable, deliberately and visibly. */
1056
+ class InMemoryPatchStore {
1057
+ order = [];
1058
+ byId = new Map();
1059
+ async list() {
1060
+ return [...this.order];
1061
+ }
1062
+ async get(patchId) {
1063
+ return this.byId.get(patchId) ?? null;
1064
+ }
1065
+ async append(patch) {
1066
+ if (!this.byId.has(patch.patchId)) {
1067
+ this.order.push(patch.patchId);
1068
+ }
1069
+ this.byId.set(patch.patchId, patch);
1070
+ }
1071
+ async delete(patchIds) {
1072
+ for (const patchId of patchIds) {
1073
+ const at = this.order.indexOf(patchId);
1074
+ if (at !== -1) {
1075
+ this.order.splice(at, 1);
1076
+ }
1077
+ this.byId.delete(patchId);
1078
+ // The bytes go with the patch. They are only reachable through it, so
1079
+ // keeping them would be a leak with no reader -- and these are images.
1080
+ for (const key of this.files.keys()) {
1081
+ if (key.startsWith(`${patchId}\u0000`)) {
1082
+ this.files.delete(key);
1083
+ }
1084
+ }
1085
+ }
1086
+ }
1087
+
1088
+ /*
1089
+ * `\u0000` cannot occur in a patch id or a path, so the two halves of the key
1090
+ * can never run together into a different pair.
1091
+ *
1092
+ * The PATH is normalised for the same reason `sourceFiles` is, and it is not
1093
+ * cosmetic: an upload arrives as `/public/val/x.png`, and the publish step
1094
+ * looks the same file up as `public/val/x.png` because that is what
1095
+ * `splitRemoteRef` yields from a remote ref. `ValOpsFS` never noticed --
1096
+ * `path.join` collapses the difference -- so this is another thing a
1097
+ * filesystem was doing for free. Without it a remote image uploads fine,
1098
+ * patches fine, and fails at publish with "No bytes held", naming a ref whose
1099
+ * bytes are sitting right there under the other spelling.
1100
+ */
1101
+ static fileKey(patchId, filePath) {
1102
+ return `${patchId}\u0000${filePath.replace(/^\//, "")}`;
1103
+ }
1104
+ files = new Map();
1105
+ async putFile(file) {
1106
+ this.files.set(InMemoryPatchStore.fileKey(file.patchId, file.filePath), file);
1107
+ }
1108
+ async getFile(patchId, filePath) {
1109
+ return this.files.get(InMemoryPatchStore.fileKey(patchId, filePath)) ?? null;
1110
+ }
1111
+ async deleteFile(patchId, filePath) {
1112
+ this.files.delete(InMemoryPatchStore.fileKey(patchId, filePath));
1113
+ }
1114
+ async filesOf(patchId) {
1115
+ return [...this.files.values()].filter(file => file.patchId === patchId);
1116
+ }
1117
+ }
1118
+
1119
+ export { HEAD_BUDGET_BYTES as H, InMemoryPatchStore as I, ValHead as V, HEAD_VERSIONS_PER_MODULE as a, draftOverlay as d, headWork as h, isLastingAnswer as i, recordKeysOf as r };