@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,673 @@
1
+ import { Internal } from '@valbuild/core';
2
+ import { STAGED_SCHEMA_PREFIX } from '@valbuild/shared/internal';
3
+ import path from 'path';
4
+
5
+ /**
6
+ * The modules whose staged code the build serving the address was NOT made
7
+ * of, each with its schema version (`staged:<inputs>`): every module the
8
+ * overlay names as staged, except those whose version names the very inputs
9
+ * the build was made of. Those the build evaluated: they are served as any
10
+ * other module.
11
+ *
12
+ * A module staged after the build has a schema this server does not have.
13
+ * Its Source is read from its staged text ({@link ValProposal.files}), its
14
+ * version is the staging's, so no reader takes it for the build's, and a save
15
+ * applies to that text (`docs/plans/one-content-model.md`, "Phase 9 without
16
+ * phases 6 and 7"; valbuild/home `docs/proposals.md`, "Staged schemas").
17
+ *
18
+ * Whole-staging inputs, not one per module, and that is what makes this
19
+ * sound: a module's schema can move with a file it imports, so "its own file
20
+ * is unchanged" never says its code is in the build.
21
+ */
22
+ function stagedAfterBuild(proposal, build) {
23
+ const inBuild = proposal.buildInputs === null || proposal.buildInputs === undefined ? null : `${STAGED_SCHEMA_PREFIX}${proposal.buildInputs}`;
24
+ const after = {};
25
+ for (const [path, version] of Object.entries(proposal.staged ?? {})) {
26
+ if (version === inBuild) continue;
27
+ after[path] = version;
28
+ }
29
+ if (build === undefined || proposal.files === undefined) return after;
30
+ /*
31
+ * Through what a module imports. The overlay names only staged MODULE
32
+ * files, and a module's schema moves with any file it imports, so a module
33
+ * whose own file is not staged can still be of code the build was not made
34
+ * of. What changed since the build is read from text: a file the proposal
35
+ * holds that is code (not a module file, not an entry's `*.val.json` --
36
+ * saves write those, stagings write code) and whose text is not what the
37
+ * build was made of; and every module file staged after the build. A
38
+ * module that depends on one of those, as the build resolved its imports,
39
+ * is staged after the build as well.
40
+ */
41
+ const changed = new Set(Object.keys(after).map(path => path.replace(/^\/+/, "")));
42
+ const changedCode = [];
43
+ for (const [path, text] of Object.entries(proposal.files)) {
44
+ if (isModuleOrEntryFile(path)) continue;
45
+ if (build.source[path] === text) continue;
46
+ changed.add(path);
47
+ changedCode.push([path, text]);
48
+ }
49
+ if (changed.size === 0) return after;
50
+ /*
51
+ * Named after the staging where the overlay names it (every staged
52
+ * module's version is the same `staged:<inputs>`); where it names none --
53
+ * only code that is not a module was staged -- after the code that
54
+ * changed, which is as distinct per staging and is never a build's.
55
+ */
56
+ const named = Object.values(proposal.staged ?? {})[0] ?? `${STAGED_SCHEMA_PREFIX}${hashOfFiles(changedCode)}`;
57
+ for (const [modulePath, dependencies] of Object.entries(build.moduleDependencies)) {
58
+ const moduleFilePath = `/${modulePath.replace(/^\/+/, "")}`;
59
+ if (after[moduleFilePath] !== undefined) continue;
60
+ if (dependencies.some(dependency => changed.has(dependency))) {
61
+ after[moduleFilePath] = named;
62
+ }
63
+ }
64
+ return after;
65
+ }
66
+
67
+ /**
68
+ * What the build serving the address was made of, as the platform builds it
69
+ * and embeds it: its own source (`platform:project-source`) and, for each
70
+ * module file, every project file it depends on as the build resolved its
71
+ * imports (`moduleDependencies`, by path with no leading slash, transitive).
72
+ * For {@link stagedAfterBuild}.
73
+ */
74
+
75
+ /** The {@link ServingBuild} a host handed over, or `undefined` when not both. */
76
+ function servingBuildOf(http) {
77
+ return http.projectSource !== undefined && http.moduleDependencies !== undefined ? {
78
+ source: http.projectSource,
79
+ moduleDependencies: http.moduleDependencies
80
+ } : undefined;
81
+ }
82
+ function isModuleOrEntryFile(path) {
83
+ return /\.val\.(ts|js|json)$/.test(path);
84
+ }
85
+
86
+ /** A 64-hex name for code that changed: its paths and text, in order. */
87
+ function hashOfFiles(files) {
88
+ const sorted = [...files].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
89
+ return Internal.getSHA256Hash(new TextEncoder().encode(JSON.stringify(sorted)));
90
+ }
91
+
92
+ /**
93
+ * The proposal a platform describes in its runtime env, or `undefined` when
94
+ * this is not a proposal's address.
95
+ *
96
+ * `VAL_PROPOSAL` and `VAL_BRANCH` name it; `VAL_OVERLAY` is the snapshot as
97
+ * JSON (`{ commit, modules, files, staged }`); `VAL_BUILD_INPUTS` says which
98
+ * staging the build was made of. Throws on a snapshot that does not parse
99
+ * rather than serving the base build as though it were the proposal: a
100
+ * reviewer would be looking at the wrong content and nothing would say so.
101
+ */
102
+ function proposalFromEnv(env) {
103
+ const name = env.VAL_PROPOSAL;
104
+ const branch = env.VAL_BRANCH;
105
+ if (!name || !branch) {
106
+ return undefined;
107
+ }
108
+ let parsed = {};
109
+ if (env.VAL_OVERLAY) {
110
+ try {
111
+ parsed = JSON.parse(env.VAL_OVERLAY);
112
+ } catch (err) {
113
+ throw new Error(`Val: proposal ${name}: VAL_OVERLAY is not JSON (${err instanceof Error ? err.message : String(err)})`, {
114
+ cause: err
115
+ });
116
+ }
117
+ }
118
+ if (!isObject(parsed)) {
119
+ throw new Error(`Val: proposal ${name}: VAL_OVERLAY is not an object`);
120
+ }
121
+ const modulesIn = parsed["modules"] ?? {};
122
+ const filesIn = parsed["files"] ?? {};
123
+ const commit = parsed["commit"] ?? null;
124
+ if (!isObject(modulesIn) || !isObject(filesIn)) {
125
+ throw new Error(`Val: proposal ${name}: VAL_OVERLAY's modules and files must be objects`);
126
+ }
127
+ if (commit !== null && typeof commit !== "string") {
128
+ throw new Error(`Val: proposal ${name}: VAL_OVERLAY's commit must be a string or null`);
129
+ }
130
+ const files = {};
131
+ for (const [path, text] of Object.entries(filesIn)) {
132
+ if (typeof text === "string") {
133
+ files[path] = text;
134
+ }
135
+ }
136
+ return {
137
+ name,
138
+ branch,
139
+ commit,
140
+ modules: modulesIn,
141
+ files,
142
+ staged: stagedOf(name, parsed["staged"]),
143
+ buildInputs: buildInputsOf(name, env.VAL_BUILD_INPUTS)
144
+ };
145
+ }
146
+
147
+ /**
148
+ * The overlay's `staged`, checked: `{}` when it does not say (an overlay
149
+ * written before it). One that says something else than module paths with
150
+ * `staged:` versions is thrown: read as "none staged", a save would apply to
151
+ * a staged module as a build that never evaluated it.
152
+ */
153
+ function stagedOf(name, staged) {
154
+ if (staged === undefined || staged === null) return {};
155
+ if (!isObject(staged)) {
156
+ throw new Error(`Val: proposal ${name}: VAL_OVERLAY's staged must be an object`);
157
+ }
158
+ const out = {};
159
+ for (const [path, version] of Object.entries(staged)) {
160
+ if (!path.startsWith("/") || typeof version !== "string" || !version.startsWith(STAGED_SCHEMA_PREFIX)) {
161
+ throw new Error(`Val: proposal ${name}: VAL_OVERLAY's staged must name module files with staged:<inputs> versions (${JSON.stringify(path)})`);
162
+ }
163
+ out[path] = version;
164
+ }
165
+ return out;
166
+ }
167
+
168
+ /**
169
+ * `VAL_BUILD_INPUTS`: 64 hex, or nothing. Anything else is thrown, for the
170
+ * same reason as {@link stagedOf}, in the other direction: read as "the
171
+ * build has it", a save would apply to staged code as though it were built.
172
+ */
173
+ function buildInputsOf(name, inputs) {
174
+ if (inputs === undefined || inputs === "") return null;
175
+ if (!/^[0-9a-f]{64}$/.test(inputs)) {
176
+ throw new Error(`Val: proposal ${name}: VAL_BUILD_INPUTS is not a build's staged inputs (64 hex)`);
177
+ }
178
+ return inputs;
179
+ }
180
+
181
+ /**
182
+ * A content version: the site's content, served by a build that bundles an
183
+ * older one. valbuild/home `docs/hosted-publishing.md`, step 2.
184
+ *
185
+ * The platform hands over only what differs from the bundle -- the modules
186
+ * whose Source changed and the Val files whose text did -- the way it hands a
187
+ * proposal's address its saved content, and it is read the same way: the
188
+ * snapshot source provider, over the bundle. What differs is the position: a
189
+ * version names the publish that made it (`job`, or its `commit`), and that is
190
+ * where this server says it sits, never at the build it runs in.
191
+ */
192
+
193
+ /**
194
+ * The content version a platform hands over in its runtime env
195
+ * (`VAL_CONTENT`), or `undefined` when it hands over none.
196
+ *
197
+ * Throws on one it cannot read rather than serving the bundle as though it
198
+ * were the version: the site would show content older than what was
199
+ * published, and nothing would say so.
200
+ *
201
+ * A version too large for one variable names others under `refs`: a module's
202
+ * Source (JSON) or a file's text, each in a variable of its own --
203
+ * `{ "refs": { "modules": { "/a.val.ts": "env://VAL_CONTENT_1" } } }`. Flat:
204
+ * a referenced variable holds the value itself and is never read for further
205
+ * references. Only `refs` is resolved, never a string inside Source, and only
206
+ * `VAL_CONTENT_<n>` is ever read: Source is text editors write, and a
207
+ * reference resolved in there would read any variable the isolate holds,
208
+ * `VAL_SECRET` included, into a page. The scheme leaves room for another
209
+ * place to read from; one this does not know is refused, not skipped.
210
+ */
211
+ function contentFromEnv(env) {
212
+ if (!env.VAL_CONTENT) {
213
+ return undefined;
214
+ }
215
+ let parsed;
216
+ try {
217
+ parsed = JSON.parse(env.VAL_CONTENT);
218
+ } catch (err) {
219
+ throw new Error(`Val: VAL_CONTENT is not JSON (${err instanceof Error ? err.message : String(err)})`, {
220
+ cause: err
221
+ });
222
+ }
223
+ if (!isObject(parsed) || Array.isArray(parsed)) {
224
+ throw new Error("Val: VAL_CONTENT is not an object");
225
+ }
226
+ const id = parsed["id"];
227
+ if (typeof id !== "string" || id === "") {
228
+ throw new Error("Val: VAL_CONTENT has no id");
229
+ }
230
+ const job = parsed["job"] ?? null;
231
+ const commit = parsed["commit"] ?? null;
232
+ if (job !== null && typeof job !== "string") {
233
+ throw new Error(`Val: content version ${id}: job must be a string or null`);
234
+ }
235
+ if (commit !== null && typeof commit !== "string") {
236
+ throw new Error(`Val: content version ${id}: commit must be a string or null`);
237
+ }
238
+ const modulesIn = parsed["modules"] ?? {};
239
+ const filesIn = parsed["files"] ?? {};
240
+ if (!isObject(modulesIn) || Array.isArray(modulesIn) || !isObject(filesIn) || Array.isArray(filesIn)) {
241
+ throw new Error(`Val: content version ${id}: modules and files must be objects`);
242
+ }
243
+ const files = {};
244
+ for (const [path, text] of Object.entries(filesIn)) {
245
+ if (typeof text === "string") {
246
+ files[path] = text;
247
+ }
248
+ }
249
+ const modules = {
250
+ ...modulesIn
251
+ };
252
+ const refs = parsed["refs"] ?? {};
253
+ if (!isObject(refs) || Array.isArray(refs)) {
254
+ throw new Error(`Val: content version ${id}: refs must be an object`);
255
+ }
256
+ const read = (kind, path, ref) => {
257
+ const where = `Val: content version ${id}: refs.${kind}["${path}"]`;
258
+ if (typeof ref !== "string") {
259
+ throw new Error(`${where} must be a string`);
260
+ }
261
+ if (!ref.startsWith(ENV_REF)) {
262
+ throw new Error(`${where} is ${ref}: only ${ENV_REF}VAL_CONTENT_<n> is read`);
263
+ }
264
+ const name = ref.slice(ENV_REF.length);
265
+ if (!CONTENT_VARIABLE.test(name)) {
266
+ throw new Error(`${where} names ${name}: only VAL_CONTENT_<n> is read`);
267
+ }
268
+ const value = env[name];
269
+ if (value === undefined) {
270
+ throw new Error(`${where} names ${name}, which is not set`);
271
+ }
272
+ return {
273
+ where,
274
+ name,
275
+ value
276
+ };
277
+ };
278
+ const refModules = refs["modules"] ?? {};
279
+ const refFiles = refs["files"] ?? {};
280
+ if (!isObject(refModules) || Array.isArray(refModules) || !isObject(refFiles) || Array.isArray(refFiles)) {
281
+ throw new Error(`Val: content version ${id}: refs.modules and refs.files must be objects`);
282
+ }
283
+ for (const [path, ref] of Object.entries(refModules)) {
284
+ const {
285
+ where,
286
+ name,
287
+ value
288
+ } = read("modules", path, ref);
289
+ if (Object.prototype.hasOwnProperty.call(modules, path)) {
290
+ throw new Error(`${where}: ${path} is also in modules`);
291
+ }
292
+ try {
293
+ modules[path] = JSON.parse(value);
294
+ } catch (err) {
295
+ throw new Error(`${where}: ${name} is not JSON (${err instanceof Error ? err.message : String(err)})`, {
296
+ cause: err
297
+ });
298
+ }
299
+ }
300
+ for (const [path, ref] of Object.entries(refFiles)) {
301
+ const {
302
+ where,
303
+ value
304
+ } = read("files", path, ref);
305
+ // The handed object, not `files`: an inline value that is not text was
306
+ // dropped from `files`, and is still a second naming of the path.
307
+ if (Object.prototype.hasOwnProperty.call(filesIn, path)) {
308
+ throw new Error(`${where}: ${path} is also in files`);
309
+ }
310
+ files[path] = value;
311
+ }
312
+ if (job === null && commit === null) {
313
+ // Placed nowhere, Val would place it at the build it runs in -- the one
314
+ // position a version must never take: its own changes would be replayed
315
+ // over a snapshot that already holds them.
316
+ throw new Error(`Val: content version ${id} must name a job or a commit, or it would be placed at the build it runs in`);
317
+ }
318
+ return {
319
+ id,
320
+ job,
321
+ commit,
322
+ modules,
323
+ files
324
+ };
325
+ }
326
+
327
+ /** The one scheme a content version's `refs` may use, for now. */
328
+ const ENV_REF = "env://";
329
+ /** The only variables a reference may name. */
330
+ const CONTENT_VARIABLE = /^VAL_CONTENT_[0-9]+$/;
331
+
332
+ /**
333
+ * What a server or reader renders over the bundle: a proposal's saves over the
334
+ * content version the site serves, either alone, or nothing.
335
+ *
336
+ * Layered rather than chosen. At a proposal's address the platform hands both
337
+ * when the base the proposal was opened from serves content its build does not
338
+ * bundle (a content-only publish), and the proposal saves only the modules it
339
+ * changed: choosing the proposal alone would show every other module as the
340
+ * build bundles it -- older than the site it was opened from.
341
+ */
342
+ function layeredSnapshot(proposal, contentVersion) {
343
+ if (proposal === undefined) return contentVersion;
344
+ if (contentVersion === undefined) return proposal;
345
+ return {
346
+ modules: {
347
+ ...contentVersion.modules,
348
+ ...proposal.modules
349
+ },
350
+ files: {
351
+ ...contentVersion.files,
352
+ ...proposal.files
353
+ }
354
+ };
355
+ }
356
+
357
+ /**
358
+ * The proposal as a reader whose code is the serving build reads it: without
359
+ * the Source of a module staged after that build ({@link stagedAfterBuild}),
360
+ * which was made for code the reader has not got. Left out, such a module
361
+ * reads as the site or the build has it -- content of the code that reads it
362
+ * -- until a build of the staging serves the address. The same rule as
363
+ * `layered`'s, for the one source that carries no version.
364
+ */
365
+ function proposalAsBuilt(proposal, build) {
366
+ const after = stagedAfterBuild(proposal, build);
367
+ if (Object.keys(after).length === 0) return proposal;
368
+ const modules = {};
369
+ for (const [path, source] of Object.entries(proposal.modules)) {
370
+ if (after[path] === undefined) modules[path] = source;
371
+ }
372
+ return {
373
+ ...proposal,
374
+ modules
375
+ };
376
+ }
377
+
378
+ /**
379
+ * The proposal's saved Source, as Source: every module whose value is JSON.
380
+ * One place, so the server and the readers that render without it agree on
381
+ * what the snapshot holds.
382
+ */
383
+ function proposalSnapshot(proposal) {
384
+ const snapshot = {};
385
+ for (const [path, source] of Object.entries(proposal.modules)) {
386
+ if (isJsonValue(source)) {
387
+ snapshot[path] = source;
388
+ }
389
+ }
390
+ return snapshot;
391
+ }
392
+
393
+ /**
394
+ * `proposalSnapshotForReaders`, loading the compiler only when the snapshot
395
+ * needs it: what the server-side readers render over the bundle.
396
+ *
397
+ * A saved `.jsonValues()` entry is found through its module's `.val.ts`, which
398
+ * takes TypeScript to read (`./proposalJsonEntries`). Without one -- every
399
+ * site serving published content, and a proposal or content version that saved
400
+ * no entry -- the snapshot is {@link proposalSnapshot} and nothing is loaded:
401
+ * the readers are on every page's path, and a cold isolate pays for every
402
+ * module it evaluates.
403
+ */
404
+ async function readerSnapshot(proposal, projectSource) {
405
+ // The same test `proposalJsonEntries` starts with: no saved entry file, no
406
+ // entry to put in place of a marker.
407
+ if (!Object.keys(proposal.files).some(path => path.endsWith(".val.json"))) {
408
+ return proposalSnapshot(proposal);
409
+ }
410
+ const {
411
+ proposalSnapshotForReaders
412
+ } = await import('./proposalJsonEntries-0669f027.esm.js').then(function (n) { return n.l; });
413
+ return proposalSnapshotForReaders(proposal, projectSource);
414
+ }
415
+
416
+ /** A plain object: not `null`, not an array. */
417
+ function isObject(value) {
418
+ return typeof value === "object" && value !== null && !Array.isArray(value);
419
+ }
420
+
421
+ /** What `JSON.parse` can produce, checked rather than assumed. */
422
+ function isJsonValue(value) {
423
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
424
+ return true;
425
+ }
426
+ if (Array.isArray(value)) {
427
+ return value.every(isJsonValue);
428
+ }
429
+ return isObject(value) && Object.values(value).every(isJsonValue);
430
+ }
431
+
432
+ /*
433
+ * Which mode a server's options and environment select, apart from
434
+ * `initHandlerOptions` (in `./valServerConfig`), which builds the rest of the
435
+ * config and imports the data layer to do it. A framework binding asks this
436
+ * BEFORE it loads the server: in `fs` and `memory` mode the newest server
437
+ * built in a process is the build the patches are relative to
438
+ * (`ValOps.chainBaseSha`), so it is built when the app starts; in `http`
439
+ * mode the content service says which build is live, so the server can wait for
440
+ * the first request -- which keeps it off a cold isolate's first page.
441
+ *
442
+ * Nothing here may import more than types: it is on every page's path.
443
+ */
444
+
445
+ /**
446
+ * The value of `VAL_ENV` that means "this is the Val app".
447
+ *
448
+ * The Val app builds a project in a browser and runs it in a Worker isolate.
449
+ * There is no disk there and there never will be, so `fs` mode is never the
450
+ * right fall-through -- and the content is Val's own, reached over HTTP at a
451
+ * commit, exactly as it is for any other deployed app. So this names `http`.
452
+ *
453
+ * What makes the app unusual is not where its content comes from but what
454
+ * publishing means: the browser rebuilds the site and the new build is served
455
+ * immediately, instead of a host noticing a commit and redeploying. That is a
456
+ * difference in what happens AFTER the commit, and `publishOverride` is where
457
+ * a host says so -- not a difference in where patches, files or sources live.
458
+ *
459
+ * A host says WHERE it runs, which is a fact it knows. Which Val mode that
460
+ * implies is Val's to derive, and that is the whole reason this exists next to
461
+ * `VAL_MODE` rather than the platform naming a mode itself: one is a
462
+ * description of an environment, the other an assertion about Val's internals,
463
+ * and only the first stays true when the internals move. They have already
464
+ * moved once -- this meant `memory` while the app kept its own patch store --
465
+ * and no platform had to be changed to follow.
466
+ */
467
+ const VAL_APP_ENV = "app";
468
+
469
+ /** Which mode the environment SAYS this is, and which variable said so. */
470
+
471
+ /**
472
+ * `null` is "the environment did not say", which is the normal case.
473
+ *
474
+ * The two variables differ in what can be DONE with an answer, and the
475
+ * difference is whether the environment holds everything the mode needs.
476
+ * `http` does -- an api key, a secret, a project, a commit and a branch are all
477
+ * env vars -- so `VAL_ENV=app` SELECTS it, and the checks in
478
+ * {@link initHandlerOptions} name whichever one is missing. `memory` does not:
479
+ * it needs the host's own source files, which nothing in an environment can
480
+ * supply, so `VAL_MODE=memory` can only ever turn a fall-through into an error.
481
+ */
482
+ function namedMode() {
483
+ const declared = process.env.VAL_MODE;
484
+ /*
485
+ * An empty value counts as unset, which is what `VAL_MODE=` in a shell or a
486
+ * CI settings page means. An explicit `VAL_MODE` otherwise wins over
487
+ * `VAL_ENV`: naming a mode outright says something more specific than naming
488
+ * an environment does, including when what it names is wrong and has to be
489
+ * refused.
490
+ */
491
+ if (declared !== undefined && declared !== "") {
492
+ return {
493
+ mode: declared,
494
+ from: "VAL_MODE"
495
+ };
496
+ }
497
+ if (process.env.VAL_ENV === VAL_APP_ENV) {
498
+ return {
499
+ mode: "http",
500
+ from: "VAL_ENV"
501
+ };
502
+ }
503
+ return null;
504
+ }
505
+
506
+ /**
507
+ * Whether these options select `http` mode, as `initHandlerOptions` decides
508
+ * it: a mode of "proxy", the Val app's environment, or a credential with no
509
+ * mode given. `sourceFiles` (memory mode) is decided before this is asked,
510
+ * and the environment's refusals are `initHandlerOptions`'s to throw.
511
+ */
512
+ function selectsHttpMode(opts, declared = namedMode()) {
513
+ const maybeApiKey = opts.apiKey || process.env.VAL_API_KEY;
514
+ const maybeValSecret = opts.valSecret || process.env.VAL_SECRET;
515
+ return opts.mode === "proxy" || (declared === null || declared === void 0 ? void 0 : declared.from) === "VAL_ENV" || opts.mode === undefined && !!(maybeApiKey || maybeValSecret);
516
+ }
517
+
518
+ /**
519
+ * Whether a server with these options can be built at its first request
520
+ * rather than when the app starts: only in `http` mode, for the reason at
521
+ * the top of this file. Memory mode is selected by `sourceFiles` alone.
522
+ */
523
+ function serverCanStartLazily(opts) {
524
+ return opts.sourceFiles === undefined && selectsHttpMode(opts);
525
+ }
526
+
527
+ /**
528
+ * What Val calls to format a file it has just written.
529
+ *
530
+ * The same shape `initValServer`, `initValMcp` and `ValOps` take as their
531
+ * `formatter` option. The path is the file's path INSIDE the project — a
532
+ * `ModuleFilePath` such as `/content/page.val.ts`, or a `*.val.json` entry
533
+ * beside it — never an absolute path on disk, because the writers that call it
534
+ * (`ValOps.prepare`, the CLI's `--fix`) only ever know a module by that path.
535
+ */
536
+
537
+ /**
538
+ * Prettier's options, as far as this file is concerned.
539
+ *
540
+ * Deliberately opaque: this file never reads an option, it only carries the
541
+ * bag from `resolveConfig` to `format`. Naming the real `Options` here would
542
+ * make it a compile error to build `@valbuild/server` in a project that has no
543
+ * prettier installed, which is most of them — prettier is a dependency the app
544
+ * opts into, so it is passed IN rather than imported.
545
+ */
546
+
547
+ /**
548
+ * `prettier`, as this file wants it.
549
+ *
550
+ * Structural for the same reason `SharpLike` in `@valbuild/mcp` is: a type-only
551
+ * import of a package that is not installed is still a compile error, and this
552
+ * package has to typecheck without prettier. `createPrettierFormatter.test.ts`
553
+ * asserts the real library against this type so the structural description
554
+ * cannot drift away from it unnoticed.
555
+ *
556
+ * Every result is `T | Promise<T>` so that `@prettier/sync` — the same API with
557
+ * the awaits taken out — satisfies it too. Everything here is awaited either
558
+ * way, and a formatter is allowed to be synchronous: `ValFormatter` says so.
559
+ */
560
+
561
+ /**
562
+ * `prettier`, loaded when the first file is formatted: `() => import("prettier")`.
563
+ *
564
+ * What an app's `val.server.ts` should pass. That module is imported by every
565
+ * page (it holds the readers too), so a static `import prettier from
566
+ * "prettier"` there makes every cold start of the site evaluate prettier --
567
+ * for a formatter that only runs when an editor saves. The loader is called at
568
+ * most once.
569
+ */
570
+
571
+ /**
572
+ * Resolve a path Val handed us against the project.
573
+ *
574
+ * Val's writers pass a project-relative path (`/content/page.val.ts`), and
575
+ * prettier needs a real one — both to find the `.prettierrc` that governs the
576
+ * file and to match it against `.prettierignore`. An absolute path that is
577
+ * already inside the project is taken as it comes, so a caller that happens to
578
+ * hold a real path is not mangled into `<root>/<root>/...`.
579
+ */
580
+ function resolveAgainstProject(projectRoot, filePath) {
581
+ if (path.isAbsolute(filePath)) {
582
+ const relative = path.relative(projectRoot, filePath);
583
+ if (relative && !relative.startsWith("..") && !path.isAbsolute(relative)) {
584
+ return filePath;
585
+ }
586
+ }
587
+ return path.join(projectRoot, filePath);
588
+ }
589
+
590
+ /**
591
+ * A {@link ValFormatter} that formats the way the project itself does.
592
+ *
593
+ * ONE implementation, for every writer of source files Val has: the Studio and
594
+ * the dev server (`initValServer`), an agent (`initValMcp`) and
595
+ * `val validate --fix`. They used to disagree — the CLI called
596
+ * `prettier.format(code, { filepath })` on its own behalf, and `format` does
597
+ * not read `.prettierrc`; only `resolveConfig`, `getFileInfo` and the prettier
598
+ * CLI do. `filepath` there selects the PARSER and nothing else, so the output
599
+ * was valid TypeScript in prettier's default style rather than the project's:
600
+ * a two-line content fix arriving as a whole-file rewrite, and a red `format`
601
+ * job in any repo that checks formatting in CI.
602
+ *
603
+ * ```ts
604
+ * import { createPrettierFormatter } from "@valbuild/next/server";
605
+ *
606
+ * initValServer(valModules, config, {
607
+ * draftMode,
608
+ * formatter: createPrettierFormatter(() => import("prettier"), {
609
+ * projectRoot: process.cwd(),
610
+ * }),
611
+ * });
612
+ * ```
613
+ *
614
+ * `prettier` itself is accepted too (`createPrettierFormatter(prettier, …)`),
615
+ * for a caller that has it loaded anyway, like the CLI; a server should pass
616
+ * the loader ({@link PrettierLoader}).
617
+ *
618
+ * `projectRoot` is what a project-relative path is resolved against, and is
619
+ * therefore also where `.prettierignore` is looked for. Prettier's own config
620
+ * search walks UP from the resolved file, so a monorepo package with its own
621
+ * `.prettierrc` is found without being named here.
622
+ *
623
+ * Two decisions worth knowing:
624
+ *
625
+ * - **`.prettierignore` is honoured; `.gitignore` is not.** The prettier CLI
626
+ * consults both, but only one of them is a statement about formatting — a
627
+ * file is gitignored for reasons that have nothing to do with style, and the
628
+ * only files reaching this function are ones Val itself just wrote.
629
+ * - **No config found is not an error.** `resolveConfig` returns `null` and
630
+ * the file is formatted with prettier's defaults, which is what a project
631
+ * without a config has asked for.
632
+ */
633
+ function createPrettierFormatter(prettierOrLoader, options) {
634
+ let loaded = null;
635
+ const loadPrettier = () => {
636
+ if (typeof prettierOrLoader !== "function") {
637
+ return Promise.resolve(prettierOrLoader);
638
+ }
639
+ // Forgotten when it fails, so the next save tries again rather than
640
+ // failing on the same rejected promise for the life of the process.
641
+ loaded ??= prettierOrLoader().catch(err => {
642
+ loaded = null;
643
+ throw err;
644
+ });
645
+ return loaded;
646
+ };
647
+ const projectRoot = path.resolve(options.projectRoot);
648
+ // One array, built once: prettier reads and caches the ignore file itself, so
649
+ // this is only here to avoid rebuilding the path per file.
650
+ const ignorePath = [path.join(projectRoot, ".prettierignore")];
651
+ return async (code, filePath) => {
652
+ const absoluteFilePath = resolveAgainstProject(projectRoot, filePath);
653
+ const prettier = await loadPrettier();
654
+ const {
655
+ ignored
656
+ } = await prettier.getFileInfo(absoluteFilePath, {
657
+ ignorePath
658
+ });
659
+ if (ignored) {
660
+ return code;
661
+ }
662
+ // `resolveConfig` applies the `overrides` that match this file and caches
663
+ // per directory, so calling it per file is cheap even on a project-wide
664
+ // `--fix`. `filepath` is still required: it is what picks the parser.
665
+ const config = await prettier.resolveConfig(absoluteFilePath);
666
+ return prettier.format(code, {
667
+ ...config,
668
+ filepath: absoluteFilePath
669
+ });
670
+ };
671
+ }
672
+
673
+ export { proposalSnapshot as a, createPrettierFormatter as b, contentFromEnv as c, isJsonValue as d, servingBuildOf as e, selectsHttpMode as f, proposalAsBuilt as g, serverCanStartLazily as h, isObject as i, layeredSnapshot as l, namedMode as n, proposalFromEnv as p, readerSnapshot as r, stagedAfterBuild as s };