@valbuild/server 0.154.1 → 0.154.2

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