@valbuild/server 0.150.20 → 0.150.22

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 (23) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/browser/dist/valbuild-server-browser.cjs.dev.js +1 -1
  3. package/browser/dist/valbuild-server-browser.cjs.prod.js +1 -1
  4. package/browser/dist/valbuild-server-browser.esm.js +1 -1
  5. package/dist/{ValRouterCore-94671fe0.cjs.dev.js → ValRouterCore-3431ce5f.cjs.dev.js} +3 -3
  6. package/dist/{ValRouterCore-69585ccd.esm.js → ValRouterCore-c5f6885a.esm.js} +3 -3
  7. package/dist/{ValRouterCore-e59bbc75.cjs.prod.js → ValRouterCore-df3f99c6.cjs.prod.js} +3 -3
  8. package/dist/{getJsonEntryAtCommit-cd0b317b.cjs.dev.js → getJsonEntryAtCommit-21a4bbfa.cjs.dev.js} +2 -2
  9. package/dist/{getJsonEntryAtCommit-47003e4a.esm.js → getJsonEntryAtCommit-93f9aba9.esm.js} +2 -2
  10. package/dist/{getJsonEntryAtCommit-bc6d4f82.cjs.prod.js → getJsonEntryAtCommit-b52171b1.cjs.prod.js} +2 -2
  11. package/dist/{jsonValuesModule-8ae503a8.cjs.dev.js → jsonValuesModule-235bd751.cjs.dev.js} +38 -0
  12. package/dist/{jsonValuesModule-427d68c8.esm.js → jsonValuesModule-23eb6f53.esm.js} +38 -1
  13. package/dist/{jsonValuesModule-d1bb8d8f.cjs.prod.js → jsonValuesModule-625ebae8.cjs.prod.js} +38 -0
  14. package/dist/{ops-b15239ac.cjs.prod.js → ops-0e54b388.cjs.prod.js} +1 -1
  15. package/dist/{ops-f37d18c6.cjs.dev.js → ops-9ca2ef2a.cjs.dev.js} +1 -1
  16. package/dist/{ops-0d05feaf.esm.js → ops-b904007e.esm.js} +1 -1
  17. package/dist/{publishKit-5865095c.cjs.dev.js → publishKit-34f71e50.cjs.dev.js} +3 -2
  18. package/dist/{publishKit-580f558a.cjs.prod.js → publishKit-65e9e564.cjs.prod.js} +3 -2
  19. package/dist/{publishKit-bc8df53d.esm.js → publishKit-7441c0fd.esm.js} +4 -4
  20. package/dist/valbuild-server.cjs.dev.js +223 -15
  21. package/dist/valbuild-server.cjs.prod.js +223 -15
  22. package/dist/valbuild-server.esm.js +225 -17
  23. package/package.json +3 -3
@@ -1,7 +1,7 @@
1
- import { a as analyzeValModule, f as flatMapErrors, b as formatSyntaxError, c as analyzeJsonValuesEntries } from './jsonValuesModule-427d68c8.esm.js';
2
- export { a as analyzeValModule, d as formatSyntaxErrorTree } from './jsonValuesModule-427d68c8.esm.js';
1
+ import { a as analyzeValModule, f as flatMapErrors, b as formatSyntaxError, c as analyzeJsonValuesEntries } from './jsonValuesModule-23eb6f53.esm.js';
2
+ export { a as analyzeValModule, d as formatSyntaxErrorTree } from './jsonValuesModule-23eb6f53.esm.js';
3
3
  import { applyPatch, PatchError, JSONOps, deepClone, deepEqual, sourceToPatchPath, isNotRoot } from '@valbuild/core/patch';
4
- import { T as TSOps, r as removeValJsonEntry, i as insertValJsonEntry } from './ops-0d05feaf.esm.js';
4
+ import { T as TSOps, r as removeValJsonEntry, i as insertValJsonEntry } from './ops-b904007e.esm.js';
5
5
  import { pipe, result } from '@valbuild/core/fp';
6
6
  import { derefPatch, Internal, extractValModules, deserializeSchema, DEFAULT_CONTENT_HOST, DEFAULT_VAL_REMOTE_HOST } from '@valbuild/core';
7
7
  export { hasRemoteFileSchema } from '@valbuild/core';
@@ -10,8 +10,8 @@ import path from 'path';
10
10
  import fs from 'fs';
11
11
  import vm from 'node:vm';
12
12
  import { Module } from 'node:module';
13
- import { r as resolveExistingJsonPath, f as findNestedJsonValuesRecords, v as validateJsonValuesEntries, i as isJsonValuesRootOp, a as rebaseContentOp, c as classifyJsonValuesOp, s as summaryOf, m as matchesFilter, b as byUpdatedAt, n as newSketchpad, d as isSketchpadId, e as applySketchpadChange, V as ValOps, g as bufferFromDataUrl, h as getFieldsForType, u as uploadRemoteFile, j as getFileExt, k as guessMimeTypeFromPath, l as createMetadataFromBuffer, D as DEFAULT_ANALYTICS_INGEST_URL, o as ValOpsMemory, p as isHlsMasterPlaylist, q as sumHlsSegmentDurations, t as parseHlsMasterVariants, w as largestHlsVariant, x as fallbackRefOf, y as mapHlsUris, z as movedRemoteHost, A as needsHostCheck, B as rewriteRefHost, C as fallbackRemoteHost, E as checkRemoteFiles, F as ValServer, G as createValRequestHandler, H as getNewJsonEntryPaths, I as formatPatchSourceError } from './ValRouterCore-69585ccd.esm.js';
14
- export { L as InMemoryPatchStore, o as ValOpsMemory, J as askOncePerHost, c as classifyJsonValuesOp, I as formatPatchSourceError, j as getFileExt, K as getSettings, a as rebaseContentOp, u as uploadRemoteFile } from './ValRouterCore-69585ccd.esm.js';
13
+ import { r as resolveExistingJsonPath, f as findNestedJsonValuesRecords, v as validateJsonValuesEntries, i as isJsonValuesRootOp, a as rebaseContentOp, c as classifyJsonValuesOp, s as summaryOf, m as matchesFilter, b as byUpdatedAt, n as newSketchpad, d as isSketchpadId, e as applySketchpadChange, V as ValOps, g as bufferFromDataUrl, h as getFieldsForType, u as uploadRemoteFile, j as getFileExt, k as guessMimeTypeFromPath, l as createMetadataFromBuffer, D as DEFAULT_ANALYTICS_INGEST_URL, o as ValOpsMemory, p as isHlsMasterPlaylist, q as sumHlsSegmentDurations, t as parseHlsMasterVariants, w as largestHlsVariant, x as fallbackRefOf, y as mapHlsUris, z as movedRemoteHost, A as needsHostCheck, B as rewriteRefHost, C as fallbackRemoteHost, E as checkRemoteFiles, F as ValServer, G as createValRequestHandler, H as getNewJsonEntryPaths, I as formatPatchSourceError } from './ValRouterCore-c5f6885a.esm.js';
14
+ export { L as InMemoryPatchStore, o as ValOpsMemory, J as askOncePerHost, c as classifyJsonValuesOp, I as formatPatchSourceError, j as getFileExt, K as getSettings, a as rebaseContentOp, u as uploadRemoteFile } from './ValRouterCore-c5f6885a.esm.js';
15
15
  import { createUIRequestHandler } from '@valbuild/ui/server';
16
16
  import z$1, { z } from 'zod';
17
17
  import { fromError } from 'zod-validation-error';
@@ -5047,7 +5047,7 @@ async function patchModuleText(text, patch) {
5047
5047
  const {
5048
5048
  tsOps,
5049
5049
  parseValFile
5050
- } = await import('./publishKit-bc8df53d.esm.js');
5050
+ } = await import('./publishKit-7441c0fd.esm.js');
5051
5051
  const applied = applyPatch(parseValFile(text), tsOps, patch);
5052
5052
  if (result.isErr(applied)) {
5053
5053
  const reason = messagesOf(applied.error).join(" ");
@@ -5058,6 +5058,106 @@ async function patchModuleText(text, patch) {
5058
5058
  return result.ok(unescape(sourceFile.getText(sourceFile).replace(/\\u/g, "%u")));
5059
5059
  }
5060
5060
 
5061
+ /**
5062
+ * A patch written into a module's files: {@link patchModuleText}, and an op
5063
+ * that reaches INTO a `.jsonValues()` entry written into that entry's own
5064
+ * `*.val.json`, as a save routes it (`ValOps.prepare`).
5065
+ *
5066
+ * The design tab's `create_patch` used to refuse those, and the assistant
5067
+ * rewrote the whole entry file to change one field -- over whatever had been
5068
+ * saved into it since it read it.
5069
+ *
5070
+ * Only into an entry that is already there. Adding, replacing or removing a
5071
+ * whole entry is a key in the `.val.ts` and a file beside it, which a save
5072
+ * writes from the record's schema; here that is still `write_files`, and the
5073
+ * error says so.
5074
+ *
5075
+ * `readFile` answers a file by its path without a leading slash: the
5076
+ * proposal's copy, else the build's, `null` for one the proposal deleted.
5077
+ * `moduleText` is `null` when no op is the module file's own; `entries` is
5078
+ * each entry file written, by the same kind of path.
5079
+ */
5080
+ async function patchModuleFiles(moduleFilePath, text, readFile, patch) {
5081
+ const entryFiles = await jsonEntryFilesOf(moduleFilePath, text);
5082
+ const textOps = [];
5083
+ const entryOps = new Map();
5084
+ for (const op of patch) {
5085
+ const key = op.path[0];
5086
+ // The record itself, or one of its entries as a whole -- a new one too,
5087
+ // which would otherwise be written into the record's text inline.
5088
+ if (entryFiles.size > 0 && op.path.length <= 1) {
5089
+ return result.err(`${key !== undefined ? `"${key}" is a whole entry` : "This is the whole record"} of a .jsonValues() record: add, replace or remove an entry by writing ${moduleFilePath} and the entry's .val.json with write_files.`);
5090
+ }
5091
+ const entryFile = key !== undefined ? entryFiles.get(key) : undefined;
5092
+ if (key === undefined || entryFile === undefined) {
5093
+ textOps.push(op);
5094
+ continue;
5095
+ }
5096
+ if (op.op === "file") {
5097
+ return result.err(`A file in a .jsonValues() entry is uploaded by the Studio, not written here.`);
5098
+ }
5099
+ if ((op.op === "move" || op.op === "copy") && op.from[0] !== key) {
5100
+ return result.err(`An op from one .jsonValues() entry into another is not written here: write the entries' .val.json files with write_files.`);
5101
+ }
5102
+ const rebased = rebaseContentOp(op, 1);
5103
+ if (result.isErr(rebased)) return result.err(rebased.error.message);
5104
+ entryOps.set(entryFile, [...(entryOps.get(entryFile) ?? []), rebased.value]);
5105
+ }
5106
+ let moduleText = null;
5107
+ if (textOps.length > 0) {
5108
+ const patched = await patchModuleText(text, textOps);
5109
+ if (result.isErr(patched)) return patched;
5110
+ moduleText = patched.value;
5111
+ }
5112
+ const entries = {};
5113
+ for (const [entryFile, ops] of entryOps) {
5114
+ const raw = readFile(entryFile);
5115
+ if (raw === null || raw === undefined) {
5116
+ return result.err(`${entryFile} is ${raw === null ? "deleted in this proposal" : "not in this proposal or on the site"}.`);
5117
+ }
5118
+ let content;
5119
+ try {
5120
+ content = JSON.parse(raw);
5121
+ } catch {
5122
+ return result.err(`${entryFile} is not JSON.`);
5123
+ }
5124
+ const applied = applyPatch(deepClone(content), new JSONOps(), ops);
5125
+ if (result.isErr(applied)) {
5126
+ return result.err(`${entryFile}: ${messagesOf(applied.error).join(" ")}`);
5127
+ }
5128
+ entries[entryFile] = applied.value;
5129
+ }
5130
+ return result.ok({
5131
+ moduleText,
5132
+ entries
5133
+ });
5134
+ }
5135
+
5136
+ /**
5137
+ * Each `.jsonValues()` entry's file, by key, without a leading slash: from the
5138
+ * `c.json(() => import("..."))` thunks in the module's text. Empty for a
5139
+ * module that has none, or whose text cannot be read that way.
5140
+ */
5141
+ async function jsonEntryFilesOf(moduleFilePath, text) {
5142
+ const files = new Map();
5143
+ if (!text.includes(".jsonValues(")) return files;
5144
+ const {
5145
+ parseValFile,
5146
+ analyzeValModule,
5147
+ analyzeJsonValuesEntries
5148
+ } = await import('./publishKit-7441c0fd.esm.js');
5149
+ try {
5150
+ const analysis = analyzeValModule(parseValFile(text));
5151
+ if (result.isErr(analysis)) return files;
5152
+ for (const [key, entry] of analyzeJsonValuesEntries(analysis.value.source)) {
5153
+ files.set(key, resolveExistingJsonPath(moduleFilePath, entry.importPath).replace(/^\/+/, ""));
5154
+ }
5155
+ } catch {
5156
+ // No `c.define` (`analyzeValModule` throws): no entries.
5157
+ }
5158
+ return files;
5159
+ }
5160
+
5061
5161
  /**
5062
5162
  * A patch error, or a tree of syntax errors, as sentences. Walked here rather
5063
5163
  * than with `syntax.ts`'s `flattenErrors`, which would bring the compiler in
@@ -5068,6 +5168,57 @@ function messagesOf(error) {
5068
5168
  return Array.isArray(error) ? error.flatMap(messagesOf) : [error.message];
5069
5169
  }
5070
5170
 
5171
+ /**
5172
+ * The Source each staged module file declares, read from its text: what a
5173
+ * staging sends content beside the files (`POST /proposals/:name/files`,
5174
+ * `modules`), so the proposal's Source moves with its code.
5175
+ *
5176
+ * A proposal's address serves a module's Source from what the proposal has
5177
+ * SAVED, over the site's, over the build -- never from the text. A save writes
5178
+ * both, so they agree. A staging wrote only the text, so after the design
5179
+ * tab's `create_patch` added a button to a module, its text and its build had
5180
+ * the button and the Source the server served and saved did not. The Studio,
5181
+ * lined up with that Source, could not apply an edit into the new button: the
5182
+ * canvas showed it, and then it was gone.
5183
+ *
5184
+ * Only what can be read without running anything: a `c.define(...)` whose
5185
+ * Source is a literal, a `.jsonValues()` record's entries as the markers its
5186
+ * stored Source holds (`evaluateModuleSource`) -- so an entry the design tab
5187
+ * adds is one the proposal has. Anything else -- a Source built by code, a
5188
+ * file of shared schemas -- is left out, and content keeps the Source it has
5189
+ * for it, as before this existed.
5190
+ */
5191
+ async function stagedModuleSources(files) {
5192
+ const modules = Object.entries(files).flatMap(([path, text]) => text !== null && /\.val\.(ts|js)$/.test(path) ? [{
5193
+ path,
5194
+ text
5195
+ }] : []);
5196
+ if (modules.length === 0) return {};
5197
+ // The compiler, loaded when a staging asks for it, as a save loads it.
5198
+ const {
5199
+ parseValFile,
5200
+ analyzeValModule,
5201
+ evaluateModuleSource
5202
+ } = await import('./publishKit-7441c0fd.esm.js');
5203
+ const sources = {};
5204
+ for (const {
5205
+ path,
5206
+ text
5207
+ } of modules) {
5208
+ try {
5209
+ const analysis = analyzeValModule(parseValFile(text));
5210
+ if (result.isErr(analysis)) continue;
5211
+ const source = evaluateModuleSource(analysis.value.source);
5212
+ if (result.isErr(source)) continue;
5213
+ sources[`/${path.replace(/^\/+/, "")}`] = source.value;
5214
+ } catch {
5215
+ // No `c.define` at all (`analyzeValModule` throws): code, not a module.
5216
+ continue;
5217
+ }
5218
+ }
5219
+ return sources;
5220
+ }
5221
+
5071
5222
  /**
5072
5223
  * Which of the site's pending changes a merge of a proposal moves into
5073
5224
  * proposals of their own (valbuild/home `docs/hosted-publishing.md`, step 8.2,
@@ -5299,6 +5450,35 @@ const PatchFileBody = z.object({
5299
5450
  message: z.string().max(500).optional()
5300
5451
  });
5301
5452
 
5453
+ /** A staging's body, as `write_files` sends it. */
5454
+ const StageFilesBody = z.object({
5455
+ files: z.record(z.string(), z.string().nullable())
5456
+ });
5457
+
5458
+ /**
5459
+ * A staging's body with the Source its module files declare added
5460
+ * (`stagedModuleSources`). A body this does not read goes as it came: content
5461
+ * answers it.
5462
+ */
5463
+ async function withStagedModuleSources(body) {
5464
+ let parsed;
5465
+ try {
5466
+ parsed = JSON.parse(body);
5467
+ } catch {
5468
+ return body;
5469
+ }
5470
+ const request = StageFilesBody.safeParse(parsed);
5471
+ if (!request.success || typeof parsed !== "object" || parsed === null) {
5472
+ return body;
5473
+ }
5474
+ const modules = await stagedModuleSources(request.data.files);
5475
+ if (Object.keys(modules).length === 0) return body;
5476
+ return JSON.stringify({
5477
+ ...parsed,
5478
+ modules
5479
+ });
5480
+ }
5481
+
5302
5482
  /** What `patchFileInProposal` reads of content's answer for a proposal's files. */
5303
5483
  const ProposalFilesRead = z.object({
5304
5484
  files: z.record(z.string(), z.string().nullable())
@@ -6187,6 +6367,8 @@ class ValOpsHttp extends ValOps {
6187
6367
  })
6188
6368
  };
6189
6369
  }
6370
+ // Staged module files go with the Source they declare.
6371
+ const body = (writes === null || writes === void 0 ? void 0 : writes.write) === "files" && init.body !== undefined ? await withStagedModuleSources(init.body) : init.body;
6190
6372
  const res = await fetch(`${this.contentUrl}/v1/${this.project}/proposals${path}`, {
6191
6373
  method: init.method,
6192
6374
  headers: {
@@ -6199,12 +6381,12 @@ class ValOpsHttp extends ValOps {
6199
6381
  ...(profileId !== null ? {
6200
6382
  "x-val-profile-id": profileId
6201
6383
  } : {}),
6202
- ...(init.body === undefined ? {} : {
6384
+ ...(body === undefined ? {} : {
6203
6385
  "Content-Type": json
6204
6386
  })
6205
6387
  },
6206
- ...(init.body === undefined ? {} : {
6207
- body: init.body
6388
+ ...(body === undefined ? {} : {
6389
+ body
6208
6390
  })
6209
6391
  });
6210
6392
  return {
@@ -6295,28 +6477,54 @@ class ValOpsHttp extends ValOps {
6295
6477
  message: `There is no module file ${moduleFilePath} in this proposal or on the site.`
6296
6478
  });
6297
6479
  }
6298
- const patched = await patchModuleText(text, patch);
6480
+ const patched = await patchModuleFiles(moduleFilePath, text, path => {
6481
+ var _this$projectSource2;
6482
+ const proposalCopy = files.data.files[path];
6483
+ return proposalCopy !== undefined ? proposalCopy : (_this$projectSource2 = this.projectSource) === null || _this$projectSource2 === void 0 ? void 0 : _this$projectSource2[path];
6484
+ }, patch);
6299
6485
  if (result.isErr(patched)) {
6300
6486
  return answer(422, {
6301
6487
  message: `The patch does not apply to ${moduleFilePath}: ${patched.error}`
6302
6488
  });
6303
6489
  }
6304
- let formatted = patched.value;
6305
- if ((_this$options = this.options) !== null && _this$options !== void 0 && _this$options.formatter) {
6490
+ const formatter = (_this$options = this.options) === null || _this$options === void 0 ? void 0 : _this$options.formatter;
6491
+ const format = async (written, path) => {
6492
+ if (!formatter) return result.ok(written);
6306
6493
  try {
6307
- formatted = await this.options.formatter(patched.value, moduleFilePath);
6494
+ return result.ok(await formatter(written, path));
6308
6495
  } catch (error) {
6496
+ return result.err(`The patched ${path} could not be formatted: ${error instanceof Error ? error.message : String(error)}`);
6497
+ }
6498
+ };
6499
+ const staging = {};
6500
+ if (patched.value.moduleText !== null) {
6501
+ const formatted = await format(patched.value.moduleText, moduleFilePath);
6502
+ if (result.isErr(formatted)) {
6309
6503
  return answer(422, {
6310
- message: `The patched ${moduleFilePath} could not be formatted: ${error instanceof Error ? error.message : String(error)}`
6504
+ message: formatted.error
6311
6505
  });
6312
6506
  }
6507
+ staging[filePath] = formatted.value;
6313
6508
  }
6509
+ // An entry's file as a save writes it: see `ValOps.prepare`.
6510
+ for (const [entryFile, content] of Object.entries(patched.value.entries)) {
6511
+ const formatted = await format(JSON.stringify(content, null, 2), `/${entryFile}`);
6512
+ if (result.isErr(formatted)) {
6513
+ return answer(422, {
6514
+ message: formatted.error
6515
+ });
6516
+ }
6517
+ staging[entryFile] = formatted.value;
6518
+ }
6519
+ const modules = await stagedModuleSources(staging);
6314
6520
  const staged = await content("/files", {
6315
6521
  method: "POST",
6316
6522
  body: JSON.stringify({
6317
- files: {
6318
- [filePath]: formatted
6319
- },
6523
+ files: staging,
6524
+ // The Source the patched text declares: see `stagedModuleSources`.
6525
+ ...(Object.keys(modules).length > 0 ? {
6526
+ modules
6527
+ } : {}),
6320
6528
  ...(message !== undefined ? {
6321
6529
  message
6322
6530
  } : {})
package/package.json CHANGED
@@ -27,7 +27,7 @@
27
27
  ],
28
28
  "exports": true
29
29
  },
30
- "version": "0.150.20",
30
+ "version": "0.150.22",
31
31
  "devDependencies": {
32
32
  "@prettier/sync": "^0.6.1",
33
33
  "@types/jest": "^30.0.0",
@@ -42,8 +42,8 @@
42
42
  "zod": "^4.4.3",
43
43
  "zod-validation-error": "^5.0.0",
44
44
  "@valbuild/core": "0.150.3",
45
- "@valbuild/shared": "0.150.20",
46
- "@valbuild/ui": "0.150.20"
45
+ "@valbuild/ui": "0.150.22",
46
+ "@valbuild/shared": "0.150.20"
47
47
  },
48
48
  "engines": {
49
49
  "node": "^20.19.0 || >=22"