@valbuild/server 0.151.0 → 0.152.1

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 (29) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/browser/dist/valbuild-server-browser.cjs.dev.js +2 -2
  3. package/browser/dist/valbuild-server-browser.cjs.prod.js +2 -2
  4. package/browser/dist/valbuild-server-browser.esm.js +2 -2
  5. package/dist/{ValRouter-ca467c83.cjs.dev.js → ValRouter-541c76f5.cjs.dev.js} +228 -374
  6. package/dist/{ValRouter-2827d620.esm.js → ValRouter-b4125d35.esm.js} +229 -375
  7. package/dist/{ValRouter-d43e0a33.cjs.prod.js → ValRouter-e1e0101b.cjs.prod.js} +228 -374
  8. package/dist/{ValRouterCore-eb1f53f5.cjs.prod.js → ValRouterCore-0c0359fe.cjs.prod.js} +48 -5
  9. package/dist/{ValRouterCore-0921fe9c.cjs.dev.js → ValRouterCore-bd3e9b6c.cjs.dev.js} +48 -5
  10. package/dist/{ValRouterCore-6c29fb75.esm.js → ValRouterCore-eea19e82.esm.js} +48 -5
  11. package/dist/declarations/src/ValOps.d.ts +20 -2
  12. package/dist/declarations/src/ValOpsHttp.d.ts +4 -39
  13. package/dist/declarations/src/patch/ts/jsonValuesModule.d.ts +1 -1
  14. package/dist/{inTabFetch-35cf5698.cjs.prod.js → inTabFetch-5caf8250.cjs.prod.js} +1 -1
  15. package/dist/{inTabFetch-49db354b.cjs.dev.js → inTabFetch-6d54acd8.cjs.dev.js} +1 -1
  16. package/dist/{inTabFetch-0cd45721.esm.js → inTabFetch-de7cf596.esm.js} +1 -1
  17. package/dist/{publishKit-3afe011d.cjs.dev.js → publishKit-42f08a69.cjs.dev.js} +2 -2
  18. package/dist/{publishKit-24e1406b.cjs.prod.js → publishKit-9600ecef.cjs.prod.js} +2 -2
  19. package/dist/{publishKit-d2e3e44d.esm.js → publishKit-c13ba76f.esm.js} +3 -3
  20. package/dist/valbuild-server.cjs.dev.js +2 -2
  21. package/dist/valbuild-server.cjs.prod.js +2 -2
  22. package/dist/valbuild-server.esm.js +4 -4
  23. package/internal/browser/dist/valbuild-server-internal-browser.cjs.dev.js +2 -2
  24. package/internal/browser/dist/valbuild-server-internal-browser.cjs.prod.js +2 -2
  25. package/internal/browser/dist/valbuild-server-internal-browser.esm.js +2 -2
  26. package/internal/dist/valbuild-server-internal.cjs.dev.js +2 -2
  27. package/internal/dist/valbuild-server-internal.cjs.prod.js +2 -2
  28. package/internal/dist/valbuild-server-internal.esm.js +2 -2
  29. package/package.json +4 -4
@@ -1,13 +1,13 @@
1
1
  import { Internal, deserializeSchema, DEFAULT_CONTENT_HOST, DEFAULT_VAL_REMOTE_HOST } from '@valbuild/core';
2
2
  import { createUIRequestHandler } from '@valbuild/ui/server';
3
- import { r as resolveExistingJsonPath, s as summaryOf, m as matchesFilter, h as byUpdatedAt, n as newSketchpad, i as isSketchpadId, j as applySketchpadChange, k as ValOps, V as VAL_CLIENT_HEADERS, l as bufferFromDataUrl, o as getFieldsForType, u as uploadRemoteFile, d as getFileExt, p as guessMimeTypeFromPath, q as createMetadataFromBuffer, D as DEFAULT_ANALYTICS_INGEST_URL, e as ValOpsMemory, t as sessionAuth, w as isHttpOps, x as isHlsMasterPlaylist, y as sumHlsSegmentDurations, z as parseHlsMasterVariants, A as largestHlsVariant, B as fallbackRefOf, C as mapHlsUris, E as movedRemoteHost, F as needsHostCheck, G as rewriteRefHost, H as fallbackRemoteHost, J as checkRemoteFiles, K as ValServer, L as createValRequestHandler } from './ValRouterCore-6c29fb75.esm.js';
3
+ import { r as resolveExistingJsonPath, s as summaryOf, m as matchesFilter, h as byUpdatedAt, n as newSketchpad, i as isSketchpadId, j as applySketchpadChange, k as ValOps, V as VAL_CLIENT_HEADERS, l as bufferFromDataUrl, o as getFieldsForType, u as uploadRemoteFile, d as getFileExt, p as guessMimeTypeFromPath, q as createMetadataFromBuffer, D as DEFAULT_ANALYTICS_INGEST_URL, e as ValOpsMemory, t as sessionAuth, w as isHttpOps, x as isHlsMasterPlaylist, y as sumHlsSegmentDurations, z as parseHlsMasterVariants, A as largestHlsVariant, B as fallbackRefOf, C as mapHlsUris, E as movedRemoteHost, F as needsHostCheck, G as rewriteRefHost, H as fallbackRemoteHost, J as checkRemoteFiles, K as ValServer, L as createValRequestHandler } from './ValRouterCore-eea19e82.esm.js';
4
4
  import path from 'path';
5
5
  import ts from 'typescript';
6
6
  import { z } from 'zod';
7
7
  import fs from 'fs';
8
8
  import { fromError } from 'zod-validation-error';
9
9
  import { result, pipe } from '@valbuild/core/fp';
10
- import { Patch, Sketchpad, STAGED_SCHEMA_PREFIX, schemaErrorsOf, PatchSets, joinSharedChanges, schemaTypesOfPath, sideFiles, sideSource, rebaseContentOp, JSONValue, SketchpadSummary, PlanRefusalError, PatchId as PatchId$1, SerializedSchema, valModulesEntryPath, getErrorMessageFromUnknownJson, newestCommitSha, LOCAL_FILE_IN_REMOTE_PROJECT_WARNING, LOCAL_FILE_IN_REMOTE_PROJECT_HINT, traverseSchemaSource, richTextImageSchema, forEachRichTextImage, isStudioFix } from '@valbuild/shared/internal';
10
+ import { Patch, Sketchpad, STAGED_SCHEMA_PREFIX, schemaErrorsOf, PatchSets, joinSharedChanges, schemaTypesOfPath, sideFiles, sideSource, JSONValue, SketchpadSummary, getErrorMessageFromUnknownJson, PlanRefusalError, PatchId as PatchId$1, SerializedSchema, valModulesEntryPath, newestCommitSha, LOCAL_FILE_IN_REMOTE_PROJECT_WARNING, LOCAL_FILE_IN_REMOTE_PROJECT_HINT, traverseSchemaSource, richTextImageSchema, forEachRichTextImage, isStudioFix } from '@valbuild/shared/internal';
11
11
  import os from 'os';
12
12
  import crypto$1, { randomBytes, createHash } from 'crypto';
13
13
  import { Buffer as Buffer$1 } from 'buffer';
@@ -585,7 +585,7 @@ function jsonValuesRecordKeys(source) {
585
585
  * as written. An error for anything that is not a literal.
586
586
  *
587
587
  * What a staging records for a module (`stagedModuleSources`): without the
588
- * markers, an entry the design tab added to a record was in the module's code
588
+ * markers, an entry the assistant added to a record was in the module's code
589
589
  * and not in its Source, and an edit into it was undone.
590
590
  */
591
591
  function evaluateModuleSource(source) {
@@ -2171,7 +2171,7 @@ function createFsSketchpadStore(rootDir, now = () => new Date()) {
2171
2171
  * as a bundler does.
2172
2172
  */
2173
2173
  function loadTypeScriptKit() {
2174
- return import('./publishKit-d2e3e44d.esm.js');
2174
+ return import('./publishKit-c13ba76f.esm.js');
2175
2175
  }
2176
2176
 
2177
2177
  /** Serializes a schema, or gives up quietly — serialization errors are reported elsewhere. */
@@ -4861,146 +4861,6 @@ function sameJson(a, b) {
4861
4861
  return JSON.stringify(a) === JSON.stringify(b);
4862
4862
  }
4863
4863
 
4864
- /**
4865
- * A module's file with a patch written into it: what a save does to a
4866
- * `.val.ts`, for one file and one patch, with nothing pending around it.
4867
- *
4868
- * The design tab's `create_patch` (valbuild/home `docs/design-tab.md`): there
4869
- * the assistant changes a proposal's code, and content it writes goes into the
4870
- * module's file and is staged with the code -- so a field it just added can
4871
- * be filled in the same change, and is built and rendered with it.
4872
- *
4873
- * Only the module's own file. A `.jsonValues()` entry lives in a `*.val.json`
4874
- * of its own, which a save routes to op by op (`ValOps.prepare`); a patch that
4875
- * reaches into one fails here, and the message says to write that file.
4876
- */
4877
- async function patchModuleText(text, patch) {
4878
- // The TypeScript compiler, loaded when a patch asks for it, as a save loads
4879
- // it: see `publishKit.ts`.
4880
- const {
4881
- tsOps,
4882
- parseValFile
4883
- } = await import('./publishKit-d2e3e44d.esm.js');
4884
- const applied = applyPatch(parseValFile(text), tsOps, patch);
4885
- if (result.isErr(applied)) {
4886
- const reason = messagesOf(applied.error).join(" ");
4887
- return result.err(text.includes(".jsonValues(") ? `${reason} This module keeps entries in .val.json files of their own: change an entry by writing its file with write_files.` : reason);
4888
- }
4889
- const sourceFile = applied.value;
4890
- // As a save writes it: https://github.com/microsoft/TypeScript/issues/36174
4891
- return result.ok(unescape(sourceFile.getText(sourceFile).replace(/\\u/g, "%u")));
4892
- }
4893
-
4894
- /**
4895
- * A patch written into a module's files: {@link patchModuleText}, and an op
4896
- * that reaches INTO a `.jsonValues()` entry written into that entry's own
4897
- * `*.val.json`, as a save routes it (`ValOps.prepare`).
4898
- *
4899
- * The design tab's `create_patch` used to refuse those, and the assistant
4900
- * rewrote the whole entry file to change one field -- over whatever had been
4901
- * saved into it since it read it.
4902
- *
4903
- * Only into an entry that is already there. Adding, replacing or removing a
4904
- * whole entry is a key in the `.val.ts` and a file beside it, which a save
4905
- * writes from the record's schema; here that is still `write_files`, and the
4906
- * error says so.
4907
- *
4908
- * `readFile` answers a file by its path without a leading slash: the
4909
- * proposal's copy, else the build's, `null` for one the proposal deleted.
4910
- * `moduleText` is `null` when no op is the module file's own; `entries` is
4911
- * each entry file written, by the same kind of path.
4912
- */
4913
- async function patchModuleFiles(moduleFilePath, text, readFile, patch) {
4914
- const entryFiles = await jsonEntryFilesOf(moduleFilePath, text);
4915
- const textOps = [];
4916
- const entryOps = new Map();
4917
- for (const op of patch) {
4918
- const key = op.path[0];
4919
- // The record itself, or one of its entries as a whole -- a new one too,
4920
- // which would otherwise be written into the record's text inline.
4921
- if (entryFiles.size > 0 && op.path.length <= 1) {
4922
- 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.`);
4923
- }
4924
- const entryFile = key !== undefined ? entryFiles.get(key) : undefined;
4925
- if (key === undefined || entryFile === undefined) {
4926
- textOps.push(op);
4927
- continue;
4928
- }
4929
- if (op.op === "file") {
4930
- return result.err(`A file in a .jsonValues() entry is uploaded by the Studio, not written here.`);
4931
- }
4932
- if ((op.op === "move" || op.op === "copy") && op.from[0] !== key) {
4933
- return result.err(`An op from one .jsonValues() entry into another is not written here: write the entries' .val.json files with write_files.`);
4934
- }
4935
- const rebased = rebaseContentOp(op, 1);
4936
- if (result.isErr(rebased)) return result.err(rebased.error.message);
4937
- entryOps.set(entryFile, [...(entryOps.get(entryFile) ?? []), rebased.value]);
4938
- }
4939
- let moduleText = null;
4940
- if (textOps.length > 0) {
4941
- const patched = await patchModuleText(text, textOps);
4942
- if (result.isErr(patched)) return patched;
4943
- moduleText = patched.value;
4944
- }
4945
- const entries = {};
4946
- for (const [entryFile, ops] of entryOps) {
4947
- const raw = readFile(entryFile);
4948
- if (raw === null || raw === undefined) {
4949
- return result.err(`${entryFile} is ${raw === null ? "deleted in this proposal" : "not in this proposal or on the site"}.`);
4950
- }
4951
- let content;
4952
- try {
4953
- content = JSON.parse(raw);
4954
- } catch {
4955
- return result.err(`${entryFile} is not JSON.`);
4956
- }
4957
- const applied = applyPatch(deepClone(content), new JSONOps(), ops);
4958
- if (result.isErr(applied)) {
4959
- return result.err(`${entryFile}: ${messagesOf(applied.error).join(" ")}`);
4960
- }
4961
- entries[entryFile] = applied.value;
4962
- }
4963
- return result.ok({
4964
- moduleText,
4965
- entries
4966
- });
4967
- }
4968
-
4969
- /**
4970
- * Each `.jsonValues()` entry's file, by key, without a leading slash: from the
4971
- * `c.json(() => import("..."))` thunks in the module's text. Empty for a
4972
- * module that has none, or whose text cannot be read that way.
4973
- */
4974
- async function jsonEntryFilesOf(moduleFilePath, text) {
4975
- const files = new Map();
4976
- if (!text.includes(".jsonValues(")) return files;
4977
- const {
4978
- parseValFile,
4979
- analyzeValModule,
4980
- analyzeJsonValuesEntries
4981
- } = await import('./publishKit-d2e3e44d.esm.js');
4982
- try {
4983
- const analysis = analyzeValModule(parseValFile(text));
4984
- if (result.isErr(analysis)) return files;
4985
- for (const [key, entry] of analyzeJsonValuesEntries(analysis.value.source)) {
4986
- files.set(key, resolveExistingJsonPath(moduleFilePath, entry.importPath).replace(/^\/+/, ""));
4987
- }
4988
- } catch {
4989
- // No `c.define` (`analyzeValModule` throws): no entries.
4990
- }
4991
- return files;
4992
- }
4993
-
4994
- /**
4995
- * A patch error, or a tree of syntax errors, as sentences. Walked here rather
4996
- * than with `syntax.ts`'s `flattenErrors`, which would bring the compiler in
4997
- * with this module.
4998
- */
4999
-
5000
- function messagesOf(error) {
5001
- return Array.isArray(error) ? error.flatMap(messagesOf) : [error.message];
5002
- }
5003
-
5004
4864
  /**
5005
4865
  * The Source each staged module file declares, read from its text: what a
5006
4866
  * staging sends content beside the files (`POST /proposals/:name/files`,
@@ -5008,15 +4868,15 @@ function messagesOf(error) {
5008
4868
  *
5009
4869
  * A proposal's address serves a module's Source from what the proposal has
5010
4870
  * SAVED, over the site's, over the build -- never from the text. A save writes
5011
- * both, so they agree. A staging wrote only the text, so after the design
5012
- * tab's `create_patch` added a button to a module, its text and its build had
4871
+ * both, so they agree. A staging wrote only the text, so after the assistant
4872
+ * added a button to a module, its text and its build had
5013
4873
  * the button and the Source the server served and saved did not. The Studio,
5014
4874
  * lined up with that Source, could not apply an edit into the new button: the
5015
4875
  * canvas showed it, and then it was gone.
5016
4876
  *
5017
4877
  * Only what can be read without running anything: a `c.define(...)` whose
5018
4878
  * Source is a literal, a `.jsonValues()` record's entries as the markers its
5019
- * stored Source holds (`evaluateModuleSource`) -- so an entry the design tab
4879
+ * stored Source holds (`evaluateModuleSource`) -- so an entry the assistant
5020
4880
  * adds is one the proposal has. Anything else -- a Source built by code, a
5021
4881
  * file of shared schemas -- is left out, and content keeps the Source it has
5022
4882
  * for it, as before this existed.
@@ -5032,7 +4892,7 @@ async function stagedModuleSources(files) {
5032
4892
  parseValFile,
5033
4893
  analyzeValModule,
5034
4894
  evaluateModuleSource
5035
- } = await import('./publishKit-d2e3e44d.esm.js');
4895
+ } = await import('./publishKit-c13ba76f.esm.js');
5036
4896
  const sources = {};
5037
4897
  for (const {
5038
4898
  path,
@@ -5269,6 +5129,126 @@ function createHttpSketchpadStore(options) {
5269
5129
  };
5270
5130
  }
5271
5131
 
5132
+ /**
5133
+ * What to tell a person when the content service did not do what was asked.
5134
+ *
5135
+ * Written because the old sentences guessed, and guessed wrong. The patches
5136
+ * request answered "It is most likely due to a network issue. Check your
5137
+ * network connection" for ANY non-2xx answer -- including a 500 from a content
5138
+ * service whose database was missing a column, while the editor's network was
5139
+ * fine. A status code is an answer, and an answer means the network worked.
5140
+ *
5141
+ * So there are two shapes and they say different things:
5142
+ *
5143
+ * - **The service answered** with an error (`status`). It is named, the
5144
+ * sentence says it answered with an error or refused, and the status line
5145
+ * and the service's own words go in `details` for whoever has to report it.
5146
+ * - **The service could not be reached** (`unreachable`: `fetch` threw). That
5147
+ * IS a connection failure -- but between this site's server and the
5148
+ * service, not the editor's: the editor reached this server, or nothing
5149
+ * would have asked. So it never says "your connection" either.
5150
+ *
5151
+ * `retryable` is what decides whether a caller offers Try again: a 5xx, a
5152
+ * timeout or a service that could not be reached may well work the next time;
5153
+ * a 4xx is the same refusal again, and a button that leads to the same error
5154
+ * is worse than none.
5155
+ */
5156
+
5157
+ /** Long enough for a database error, short enough for a dialog. */
5158
+ const MAX_BODY_LENGTH = 500;
5159
+
5160
+ /**
5161
+ * The content service, by a name a person would recognise.
5162
+ *
5163
+ * `content.val.build` is Val Build. Anything else -- a self-hosted engine, a
5164
+ * staging host, the e2e mock -- is named by its host, so the person can tell
5165
+ * WHICH service failed rather than being told "the server", which in a page
5166
+ * that is itself a server says nothing.
5167
+ */
5168
+ function contentServiceName(contentUrl) {
5169
+ let host;
5170
+ try {
5171
+ host = new URL(contentUrl).host;
5172
+ } catch {
5173
+ return "the content service";
5174
+ }
5175
+ if (host === "val.build" || host.endsWith(".val.build")) {
5176
+ return "Val Build";
5177
+ }
5178
+ return `the content service at ${host}`;
5179
+ }
5180
+
5181
+ /**
5182
+ * The service answered `status`.
5183
+ *
5184
+ * `what` completes "could not ...": "load your changes", "save your change".
5185
+ * `body` is the raw response text; a JSON body is read the way the rest of
5186
+ * `ValOpsHttp` reads one, so `home`'s `{ message: "Internal Server Error",
5187
+ * details: "<the real cause>" }` keeps the real cause.
5188
+ */
5189
+ function contentServiceAnswered(service, what, response) {
5190
+ const retryable = response.status >= 500 || response.status === 408 || response.status === 429;
5191
+ const Service = capitalize(service);
5192
+ const message = retryable ? `${Service} answered with an error, so Val could not ${what}.` : `${Service} refused to ${what}.`;
5193
+ const statusLine = `HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ""} from ${service}`;
5194
+ const said = bodyText(response.body);
5195
+ return {
5196
+ message,
5197
+ details: said === null ? statusLine : `${statusLine}: ${said}`,
5198
+ retryable
5199
+ };
5200
+ }
5201
+
5202
+ /** `fetch` threw: the service was never heard from. */
5203
+ function contentServiceUnreachable(service, what, error) {
5204
+ return {
5205
+ message: `${capitalize(service)} could not be reached from this site's server, so Val could not ${what}.`,
5206
+ details: errorText(error),
5207
+ retryable: true
5208
+ };
5209
+ }
5210
+ function bodyText(body) {
5211
+ const trimmed = body.trim();
5212
+ if (trimmed === "") return null;
5213
+ let text = trimmed;
5214
+ try {
5215
+ const json = JSON.parse(trimmed);
5216
+ text = getErrorMessageFromUnknownJson(json, trimmed);
5217
+ } catch {
5218
+ // Not JSON: the text is what the service said.
5219
+ }
5220
+ return text.length <= MAX_BODY_LENGTH ? text : `${text.slice(0, MAX_BODY_LENGTH)}…`;
5221
+ }
5222
+
5223
+ /**
5224
+ * The reason a `fetch` threw, with its cause.
5225
+ *
5226
+ * Node's `fetch` throws `TypeError: fetch failed` and hides what failed in
5227
+ * `cause` (`ECONNREFUSED`, a DNS miss, a certificate), which is the half
5228
+ * support needs.
5229
+ */
5230
+ function errorText(error) {
5231
+ if (!(error instanceof Error)) {
5232
+ return String(error);
5233
+ }
5234
+ const cause = error.cause;
5235
+ if (cause instanceof Error && cause.message !== error.message) {
5236
+ return `${error.message}: ${cause.message}`;
5237
+ }
5238
+ return error.message;
5239
+ }
5240
+ function capitalize(text) {
5241
+ return text.length === 0 ? text : text[0].toUpperCase() + text.slice(1);
5242
+ }
5243
+
5244
+ /**
5245
+ * One string, for the error shapes that carry only a `message`: the sentence
5246
+ * first, the evidence after it in brackets.
5247
+ */
5248
+ function contentServiceFailureText(failure) {
5249
+ return `${failure.message} (${failure.details})`;
5250
+ }
5251
+
5272
5252
  const textEncoder$2 = new TextEncoder();
5273
5253
 
5274
5254
  /** The body of the content API's 403 for a write the project's plan refuses. */
@@ -5276,13 +5256,6 @@ const PlanRefusedBody = z.object({
5276
5256
  error: PlanRefusalError
5277
5257
  });
5278
5258
 
5279
- /** `POST /proposals-api/<name>/patch-file`: see `patchFileInProposal`. */
5280
- const PatchFileBody = z.object({
5281
- moduleFilePath: z.string().regex(/^\/.+\.val\.(ts|js)$/),
5282
- patch: Patch,
5283
- message: z.string().max(500).optional()
5284
- });
5285
-
5286
5259
  /** A staging's body, as `write_files` sends it. */
5287
5260
  const StageFilesBody = z.object({
5288
5261
  files: z.record(z.string(), z.string().nullable())
@@ -5311,11 +5284,6 @@ async function withStagedModuleSources(body) {
5311
5284
  modules
5312
5285
  });
5313
5286
  }
5314
-
5315
- /** What `patchFileInProposal` reads of content's answer for a proposal's files. */
5316
- const ProposalFilesRead = z.object({
5317
- files: z.record(z.string(), z.string().nullable())
5318
- });
5319
5287
  const PatchId = z.string().refine(s => !!s); // TODO: validate
5320
5288
  const CommitSha = z.string().refine(s => !!s); // TODO: validate
5321
5289
  z.string().refine(s => !!s); // TODO: validate
@@ -6241,38 +6209,15 @@ class ValOpsHttp extends ValOps {
6241
6209
  };
6242
6210
  }
6243
6211
 
6244
- /**
6245
- * The writes the SITE's server may make to a proposal's files: what the
6246
- * design tab does (valbuild/home `docs/design-tab.md`, step 2) -- stage
6247
- * code, build it, and report its typecheck. The tab is served by the site's
6248
- * build so that a build the assistant breaks in the proposal cannot take
6249
- * down the tools it would fix it with; at the proposal's address those
6250
- * tools run on the proposal's own code.
6251
- *
6252
- * The typecheck too, though it blocks the proposal's Publish (adept.md,
6253
- * decision 20): it is the proposal's staged files checked against the
6254
- * site's, the same program from either address, and the content service
6255
- * keeps it only for the inputs it was made from. Without it the tab's
6256
- * Types check, and the assistant's `typecheck`, had nothing to show.
6257
- *
6258
- * And a quick preview: the browser half of a build of the staged files,
6259
- * which Val Build makes and nothing serves.
6260
- *
6261
- * The rest stay the proposal's own: Update from the site and the lockfile
6262
- * are answered from the proposal's build and schemas, and bringing back a
6263
- * point's code is the Studio at its address finishing a restore.
6264
- */
6265
- static SITE_MAY_WRITE = new Set(["files", "build", "quick-preview", "typecheck"]);
6266
-
6267
6212
  /**
6268
6213
  * Whether this server may make a write to a proposal's files: the
6269
- * proposal's own server, any of them; the site's, the design tab's; and a
6270
- * proposal's address, none to another proposal. Either way the site's own
6271
- * files change only when a proposal is merged.
6214
+ * proposal's own server, to its own files, and no other. The site's server
6215
+ * makes none -- code is changed in the proposal's own Studio, in code mode
6216
+ * -- and a proposal's address none to another proposal. Either way the
6217
+ * site's own files change only when a proposal is merged.
6272
6218
  */
6273
6219
  mayWriteFiles(write) {
6274
- if (this.proposal !== null) return write.name === this.proposal.name;
6275
- return ValOpsHttp.SITE_MAY_WRITE.has(write.write);
6220
+ return this.proposal !== null && write.name === this.proposal.name;
6276
6221
  }
6277
6222
 
6278
6223
  /**
@@ -6299,17 +6244,13 @@ class ValOpsHttp extends ValOps {
6299
6244
  return /^\/publish-jobs\/[A-Za-z0-9_-]{1,100}\/(merge-prepare|steps|renew|cancel)$/.test(path);
6300
6245
  }
6301
6246
  async proposalsApi(path, init, profileId) {
6302
- var _exec, _exec2, _exec3, _exec4, _exec5;
6247
+ var _exec, _exec2, _exec3, _exec4;
6303
6248
  const json = "application/json";
6304
6249
  const updating = (_exec = /^\/([0-9a-f]{20})\/update-content$/.exec(path)) === null || _exec === void 0 ? void 0 : _exec[1];
6305
6250
  if (updating !== undefined && init.method === "POST") {
6306
6251
  return this.updateContentFromSite(updating, init.body, profileId);
6307
6252
  }
6308
- const patching = (_exec2 = /^\/([0-9a-f]{20})\/patch-file$/.exec(path)) === null || _exec2 === void 0 ? void 0 : _exec2[1];
6309
- if (patching !== undefined && init.method === "POST") {
6310
- return this.patchFileInProposal(patching, init.body, profileId);
6311
- }
6312
- const withCode = (_exec3 = /^\/([0-9a-f]{20})\/update-code$/.exec(path)) === null || _exec3 === void 0 ? void 0 : _exec3[1];
6253
+ const withCode = (_exec2 = /^\/([0-9a-f]{20})\/update-code$/.exec(path)) === null || _exec2 === void 0 ? void 0 : _exec2[1];
6313
6254
  if (withCode !== undefined && init.method === "POST") {
6314
6255
  return this.updateCodeFromSite(withCode, init.body, profileId);
6315
6256
  }
@@ -6319,11 +6260,11 @@ class ValOpsHttp extends ValOps {
6319
6260
  * build's schemas (step 8.2). Anywhere else they go to content as they
6320
6261
  * are, and the site's pending changes block as they always did.
6321
6262
  */
6322
- const checking = (_exec4 = /^\/([0-9a-f]{20})\/merge-checks$/.exec(path)) === null || _exec4 === void 0 ? void 0 : _exec4[1];
6263
+ const checking = (_exec3 = /^\/([0-9a-f]{20})\/merge-checks$/.exec(path)) === null || _exec3 === void 0 ? void 0 : _exec3[1];
6323
6264
  if (checking !== undefined && init.method === "GET" && (await this.answersMovesFor(checking, profileId))) {
6324
6265
  return this.mergeChecksWithMoves(checking, profileId);
6325
6266
  }
6326
- const pressing = (_exec5 = /^\/([0-9a-f]{20})\/merge$/.exec(path)) === null || _exec5 === void 0 ? void 0 : _exec5[1];
6267
+ const pressing = (_exec4 = /^\/([0-9a-f]{20})\/merge$/.exec(path)) === null || _exec4 === void 0 ? void 0 : _exec4[1];
6327
6268
  if (pressing !== undefined && init.method === "POST" && (await this.answersMovesFor(pressing, profileId))) {
6328
6269
  return this.pressMergeWithMoves(pressing, init.body, profileId);
6329
6270
  }
@@ -6375,147 +6316,6 @@ class ValOpsHttp extends ValOps {
6375
6316
  };
6376
6317
  }
6377
6318
 
6378
- /**
6379
- * A patch written into a module's FILE in a proposal, and staged there as
6380
- * code: the design tab's `create_patch` (valbuild/home `docs/design-tab.md`).
6381
- * The assistant there changes the proposal's code, so content it writes goes
6382
- * with that code -- a field it just added is filled in the same change, and
6383
- * built and rendered with it -- rather than into the proposal's saves, which
6384
- * the site's server does not write.
6385
- *
6386
- * Answered here, at `POST /<name>/patch-file`: the file is the proposal's
6387
- * copy if it has one, otherwise the one this build was made from, and the
6388
- * patch is written into it as a save writes one (`patchModuleText`). Who may
6389
- * is who may stage files: {@link ValOpsHttp.mayWriteFiles}.
6390
- */
6391
- async patchFileInProposal(name, body, profileId) {
6392
- var _this$projectSource, _this$options2;
6393
- const json = "application/json";
6394
- const answer = (status, value) => ({
6395
- status,
6396
- contentType: json,
6397
- body: JSON.stringify(value)
6398
- });
6399
- if (!this.mayWriteFiles({
6400
- name,
6401
- write: "files"
6402
- })) {
6403
- return answer(403, {
6404
- message: "Files are changed in the proposal this Studio is open in, not in another."
6405
- });
6406
- }
6407
- let parsedBody;
6408
- try {
6409
- parsedBody = body === undefined || body === "" ? {} : JSON.parse(body);
6410
- } catch {
6411
- return answer(400, {
6412
- message: "The patch's body is not JSON."
6413
- });
6414
- }
6415
- const request = PatchFileBody.safeParse(parsedBody);
6416
- if (!request.success) {
6417
- return answer(400, {
6418
- message: `Invalid patch: ${fromError(request.error).toString()}`
6419
- });
6420
- }
6421
- const {
6422
- moduleFilePath,
6423
- patch,
6424
- message
6425
- } = request.data;
6426
- const content = this.proposalContent(name, profileId);
6427
- const read = await content("/files");
6428
- if (!read.ok) {
6429
- return {
6430
- status: read.status,
6431
- contentType: json,
6432
- body: await read.text()
6433
- };
6434
- }
6435
- const files = ProposalFilesRead.safeParse(await read.json());
6436
- if (!files.success) {
6437
- return answer(502, {
6438
- message: `Content answered the proposal's files in a shape this Val does not read: ${fromError(files.error).toString()}`
6439
- });
6440
- }
6441
- const filePath = moduleFilePath.replace(/^\/+/, "");
6442
- const own = files.data.files[filePath];
6443
- if (own === null) {
6444
- return answer(409, {
6445
- message: `${moduleFilePath} is deleted in this proposal.`
6446
- });
6447
- }
6448
- if (own === undefined && this.projectSource === null) {
6449
- return answer(409, {
6450
- message: `This build does not carry its source, so ${moduleFilePath} can only be patched once the proposal has its own copy: write it with write_files.`
6451
- });
6452
- }
6453
- const text = own ?? ((_this$projectSource = this.projectSource) === null || _this$projectSource === void 0 ? void 0 : _this$projectSource[filePath]);
6454
- if (text === undefined) {
6455
- return answer(404, {
6456
- message: `There is no module file ${moduleFilePath} in this proposal or on the site.`
6457
- });
6458
- }
6459
- const patched = await patchModuleFiles(moduleFilePath, text, path => {
6460
- var _this$projectSource2;
6461
- const proposalCopy = files.data.files[path];
6462
- return proposalCopy !== undefined ? proposalCopy : (_this$projectSource2 = this.projectSource) === null || _this$projectSource2 === void 0 ? void 0 : _this$projectSource2[path];
6463
- }, patch);
6464
- if (result.isErr(patched)) {
6465
- return answer(422, {
6466
- message: `The patch does not apply to ${moduleFilePath}: ${patched.error}`
6467
- });
6468
- }
6469
- const formatter = (_this$options2 = this.options) === null || _this$options2 === void 0 ? void 0 : _this$options2.formatter;
6470
- const format = async (written, path) => {
6471
- if (!formatter) return result.ok(written);
6472
- try {
6473
- return result.ok(await formatter(written, path));
6474
- } catch (error) {
6475
- return result.err(`The patched ${path} could not be formatted: ${error instanceof Error ? error.message : String(error)}`);
6476
- }
6477
- };
6478
- const staging = {};
6479
- if (patched.value.moduleText !== null) {
6480
- const formatted = await format(patched.value.moduleText, moduleFilePath);
6481
- if (result.isErr(formatted)) {
6482
- return answer(422, {
6483
- message: formatted.error
6484
- });
6485
- }
6486
- staging[filePath] = formatted.value;
6487
- }
6488
- // An entry's file as a save writes it: see `ValOps.prepare`.
6489
- for (const [entryFile, content] of Object.entries(patched.value.entries)) {
6490
- const formatted = await format(JSON.stringify(content, null, 2), `/${entryFile}`);
6491
- if (result.isErr(formatted)) {
6492
- return answer(422, {
6493
- message: formatted.error
6494
- });
6495
- }
6496
- staging[entryFile] = formatted.value;
6497
- }
6498
- const modules = await stagedModuleSources(staging);
6499
- const staged = await content("/files", {
6500
- method: "POST",
6501
- body: JSON.stringify({
6502
- files: staging,
6503
- // The Source the patched text declares: see `stagedModuleSources`.
6504
- ...(Object.keys(modules).length > 0 ? {
6505
- modules
6506
- } : {}),
6507
- ...(message !== undefined ? {
6508
- message
6509
- } : {})
6510
- })
6511
- });
6512
- return {
6513
- status: staged.status,
6514
- contentType: staged.headers.get("Content-Type") ?? json,
6515
- body: await staged.text()
6516
- };
6517
- }
6518
-
6519
6319
  /**
6520
6320
  * Update from the site, for a proposal that changes only content
6521
6321
  * (valbuild/home `docs/hosted-publishing.md`, step 8.2, slice 1a): content
@@ -7426,7 +7226,7 @@ class ValOpsHttp extends ValOps {
7426
7226
  return {
7427
7227
  status: "error",
7428
7228
  error: {
7429
- message: "Could not get nonce. Error: " + (e instanceof Error ? e.message : e.toString())
7229
+ message: contentServiceFailureText(contentServiceUnreachable(contentServiceName(this.contentUrl), "connect for live updates", e))
7430
7230
  }
7431
7231
  };
7432
7232
  });
@@ -7692,7 +7492,12 @@ class ValOpsHttp extends ValOps {
7692
7492
  }
7693
7493
  };
7694
7494
  }
7695
- Internal.log.error("Could not get patches. HTTP error: " + patchesRes.status + " " + patchesRes.statusText);
7495
+ const failure = contentServiceAnswered(contentServiceName(this.contentUrl), "load your changes", {
7496
+ status: patchesRes.status,
7497
+ statusText: patchesRes.statusText,
7498
+ body: await patchesRes.text().catch(() => "")
7499
+ });
7500
+ Internal.log.error(`Could not get patches. ${failure.message} ${failure.details}`);
7696
7501
  if (patchesRes.status === 401) {
7697
7502
  return {
7698
7503
  patches,
@@ -7701,19 +7506,29 @@ class ValOpsHttp extends ValOps {
7701
7506
  }
7702
7507
  };
7703
7508
  }
7509
+ /*
7510
+ * The service ANSWERED, so this is not a network problem -- it used to
7511
+ * say "most likely due to a network issue. Check your network
7512
+ * connection" about a 500, to an editor whose network was fine. What it
7513
+ * said goes in `details`. The Studio asks again on the next `/stat`,
7514
+ * which fails fast and is retried while the service is failing.
7515
+ */
7704
7516
  return {
7705
7517
  patches,
7706
7518
  error: {
7707
- message: "Could not get your changes. It is most likely due to a network issue. Check your network connection and please try again."
7519
+ message: failure.message,
7520
+ details: failure.details
7708
7521
  }
7709
7522
  };
7710
7523
  } catch (err) {
7711
- Internal.log.error("Could not get patches (connection error):", err instanceof Error ? err.message : JSON.stringify(err));
7524
+ const failure = contentServiceUnreachable(contentServiceName(this.contentUrl), "load your changes", err);
7525
+ Internal.log.error(`Could not get patches. ${failure.message} ${failure.details}`);
7712
7526
  return {
7713
7527
  patches: [],
7714
7528
  networkError: true,
7715
7529
  error: {
7716
- message: `Error: ${err instanceof Error ? err.message : JSON.stringify(err)}`
7530
+ message: failure.message,
7531
+ details: failure.details
7717
7532
  }
7718
7533
  };
7719
7534
  }
@@ -7747,7 +7562,6 @@ class ValOpsHttp extends ValOps {
7747
7562
  coreVersion: Internal.VERSION.core
7748
7563
  })
7749
7564
  }).then(async res => {
7750
- var _res$headers$get3;
7751
7565
  if (res.ok) {
7752
7566
  const parsed = SavePatchResponse.safeParse(await res.json());
7753
7567
  if (parsed.success) {
@@ -7769,8 +7583,27 @@ class ValOpsHttp extends ValOps {
7769
7583
  message: "Conflict: " + (await res.text())
7770
7584
  });
7771
7585
  }
7772
- if ((_res$headers$get3 = res.headers.get("Content-Type")) !== null && _res$headers$get3 !== void 0 && _res$headers$get3.includes("application/json")) {
7773
- const json = await res.json();
7586
+ const body = await res.text();
7587
+ const failure = contentServiceAnswered(contentServiceName(this.contentUrl), "save your change", {
7588
+ status: res.status,
7589
+ statusText: res.statusText,
7590
+ body
7591
+ });
7592
+ if (failure.retryable) {
7593
+ /*
7594
+ * The SERVICE failed -- a 500 from a database missing a column was
7595
+ * the one that found this. It used to be an `other`, which the
7596
+ * Studio is told is a bad patch and drops: the field went back to
7597
+ * its old value and the status bar said "All changes saved".
7598
+ */
7599
+ return result.err({
7600
+ errorType: "service-error",
7601
+ message: failure.message,
7602
+ details: failure.details
7603
+ });
7604
+ }
7605
+ const json = parseJsonOrNull(body);
7606
+ if (json !== null) {
7774
7607
  const message = getErrorMessageFromUnknownJson(json, "Unknown error");
7775
7608
  /*
7776
7609
  * Refused for the plan: the patch is fine, and the reason comes as
@@ -7795,12 +7628,14 @@ class ValOpsHttp extends ValOps {
7795
7628
  }
7796
7629
  return result.err({
7797
7630
  errorType: "other",
7798
- message: "Could not save patch. HTTP error: " + res.status + " " + res.statusText
7631
+ message: `${failure.message} ${failure.details}`
7799
7632
  });
7800
7633
  }).catch(e => {
7634
+ const failure = contentServiceUnreachable(contentServiceName(this.contentUrl), "save your change", e);
7801
7635
  return result.err({
7802
- errorType: "other",
7803
- message: `Could save source file patch (connection error?): ${e instanceof Error ? e.message : e.toString()}`
7636
+ errorType: "service-error",
7637
+ message: failure.message,
7638
+ details: failure.details
7804
7639
  });
7805
7640
  });
7806
7641
  }
@@ -7841,13 +7676,17 @@ class ValOpsHttp extends ValOps {
7841
7676
  }
7842
7677
  return {
7843
7678
  error: {
7844
- message: "Could not save patch file. HTTP error: " + res.status + " " + res.statusText
7679
+ message: contentServiceFailureText(contentServiceAnswered(contentServiceName(this.contentUrl), "save the file", {
7680
+ status: res.status,
7681
+ statusText: res.statusText,
7682
+ body: await res.text().catch(() => "")
7683
+ }))
7845
7684
  }
7846
7685
  };
7847
7686
  }).catch(e => {
7848
7687
  return {
7849
7688
  error: {
7850
- message: `Could save source binary file in patch (connection error?): ${e.toString()}`
7689
+ message: contentServiceFailureText(contentServiceUnreachable(contentServiceName(this.contentUrl), "save the file", e))
7851
7690
  }
7852
7691
  };
7853
7692
  });
@@ -7885,13 +7724,17 @@ class ValOpsHttp extends ValOps {
7885
7724
  }
7886
7725
  return {
7887
7726
  error: {
7888
- message: "Could not get files. HTTP error: " + res.status + " " + res.statusText
7727
+ message: contentServiceFailureText(contentServiceAnswered(contentServiceName(this.contentUrl), "load the files", {
7728
+ status: res.status,
7729
+ statusText: res.statusText,
7730
+ body: await res.text().catch(() => "")
7731
+ }))
7889
7732
  }
7890
7733
  };
7891
7734
  }).catch(e => {
7892
7735
  return {
7893
7736
  error: {
7894
- message: `Could not get file (connection error?): ${e instanceof Error ? e.message : e.toString()}`
7737
+ message: contentServiceFailureText(contentServiceUnreachable(contentServiceName(this.contentUrl), "load the files", e))
7895
7738
  }
7896
7739
  };
7897
7740
  });
@@ -8037,14 +7880,18 @@ class ValOpsHttp extends ValOps {
8037
7880
  }
8038
7881
  return {
8039
7882
  errors: [{
8040
- message: "Could not get metadata. HTTP error: " + metadataRes.status + " " + metadataRes.statusText,
7883
+ message: contentServiceFailureText(contentServiceAnswered(contentServiceName(this.contentUrl), "read the file's details", {
7884
+ status: metadataRes.status,
7885
+ statusText: metadataRes.statusText,
7886
+ body: await metadataRes.text().catch(() => "")
7887
+ })),
8041
7888
  filePath
8042
7889
  }]
8043
7890
  };
8044
7891
  } catch (err) {
8045
7892
  return {
8046
7893
  errors: [{
8047
- message: "Could not get metadata (connection error?): " + (err instanceof Error ? err.message : (err === null || err === void 0 ? void 0 : err.toString()) || "unknown error")
7894
+ message: contentServiceFailureText(contentServiceUnreachable(contentServiceName(this.contentUrl), "read the file's details", err))
8048
7895
  }]
8049
7896
  };
8050
7897
  }
@@ -8109,13 +7956,17 @@ class ValOpsHttp extends ValOps {
8109
7956
  }
8110
7957
  return {
8111
7958
  error: {
8112
- message: "Could not delete patches. HTTP error: " + res.status + " " + res.statusText
7959
+ message: contentServiceFailureText(contentServiceAnswered(contentServiceName(this.contentUrl), "discard the changes", {
7960
+ status: res.status,
7961
+ statusText: res.statusText,
7962
+ body: await res.text().catch(() => "")
7963
+ }))
8113
7964
  }
8114
7965
  };
8115
7966
  }).catch(e => {
8116
7967
  return {
8117
7968
  error: {
8118
- message: `Could not delete patches (connection error?): ${e instanceof Error ? e.message : e.toString()}`
7969
+ message: contentServiceFailureText(contentServiceUnreachable(contentServiceName(this.contentUrl), "discard the changes", e))
8119
7970
  }
8120
7971
  };
8121
7972
  });
@@ -8128,7 +7979,7 @@ class ValOpsHttp extends ValOps {
8128
7979
  */
8129
7980
  intoProposal) {
8130
7981
  try {
8131
- var _this$proposal4, _res$headers$get4;
7982
+ var _this$proposal4;
8132
7983
  /*
8133
7984
  * A save in a proposal is a commit on the proposal's branch, at its own
8134
7985
  * route: the site's `/commit` refuses a proposal's patches, which is
@@ -8222,34 +8073,37 @@ class ValOpsHttp extends ValOps {
8222
8073
  }
8223
8074
  };
8224
8075
  }
8225
- if ((_res$headers$get4 = res.headers.get("Content-Type")) !== null && _res$headers$get4 !== void 0 && _res$headers$get4.includes("application/json")) {
8226
- const json = z.object({
8227
- isNotFastForward: z.boolean().optional()
8228
- }).safeParse(await res.json());
8229
- if (json.success && json.data.isNotFastForward) {
8230
- return {
8231
- isNotFastForward: true,
8232
- error: {
8233
- message: "Could not commit. Not a fast-forward commit"
8234
- }
8235
- };
8236
- }
8237
- const message = getErrorMessageFromUnknownJson(json, "Unknown error");
8076
+ const body = await res.text().catch(() => "");
8077
+ const payload = parseJsonOrNull(body);
8078
+ const notFastForward = z.object({
8079
+ isNotFastForward: z.boolean().optional()
8080
+ }).safeParse(payload);
8081
+ if (notFastForward.success && notFastForward.data.isNotFastForward) {
8238
8082
  return {
8083
+ isNotFastForward: true,
8239
8084
  error: {
8240
- message
8085
+ message: "Could not commit. Not a fast-forward commit"
8241
8086
  }
8242
8087
  };
8243
8088
  }
8089
+ /*
8090
+ * The service's own words, read from the PAYLOAD. This used to hand
8091
+ * `getErrorMessageFromUnknownJson` the zod `safeParse` result, which
8092
+ * has no `message`, so every commit failure read "Unknown error".
8093
+ */
8244
8094
  return {
8245
8095
  error: {
8246
- message: "Could not commit. HTTP error: " + res.status + " " + res.statusText
8096
+ message: contentServiceFailureText(contentServiceAnswered(contentServiceName(this.contentUrl), "publish", {
8097
+ status: res.status,
8098
+ statusText: res.statusText,
8099
+ body
8100
+ }))
8247
8101
  }
8248
8102
  };
8249
8103
  } catch (err) {
8250
8104
  return {
8251
8105
  error: {
8252
- message: `Could not commit (connection error?): ${err instanceof Error ? err.message : (err === null || err === void 0 ? void 0 : err.toString()) || "unknown error"}`
8106
+ message: contentServiceFailureText(contentServiceUnreachable(contentServiceName(this.contentUrl), "publish", err))
8253
8107
  }
8254
8108
  };
8255
8109
  }
@@ -8288,9 +8142,9 @@ class ValOpsHttp extends ValOps {
8288
8142
  });
8289
8143
  }
8290
8144
  if (!res.ok) {
8291
- var _res$headers$get5;
8145
+ var _res$headers$get3;
8292
8146
  let message = `${res.status} ${res.statusText}`;
8293
- if ((_res$headers$get5 = res.headers.get("Content-Type")) !== null && _res$headers$get5 !== void 0 && _res$headers$get5.includes("application/json")) {
8147
+ if ((_res$headers$get3 = res.headers.get("Content-Type")) !== null && _res$headers$get3 !== void 0 && _res$headers$get3.includes("application/json")) {
8294
8148
  message = getErrorMessageFromUnknownJson(await res.json(), message);
8295
8149
  }
8296
8150
  // A 5xx from the service reading a record it says it has is a real