@valbuild/server 0.153.5 → 0.154.0

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 (27) hide show
  1. package/CHANGELOG.md +35 -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-2ff58de9.cjs.dev.js → ValRouter-1f427c38.cjs.dev.js} +90 -8
  6. package/dist/{ValRouter-072c3dee.esm.js → ValRouter-558dc66d.esm.js} +90 -8
  7. package/dist/{ValRouter-60ee2fa5.cjs.prod.js → ValRouter-cd6e854a.cjs.prod.js} +90 -8
  8. package/dist/{ValRouterCore-4e3757ac.cjs.dev.js → ValRouterCore-0c088c9e.cjs.dev.js} +325 -21
  9. package/dist/{ValRouterCore-d658dc75.cjs.prod.js → ValRouterCore-4be8eaf1.cjs.prod.js} +325 -21
  10. package/dist/{ValRouterCore-257f140c.esm.js → ValRouterCore-fe985e4c.esm.js} +320 -22
  11. package/dist/declarations/src/patch/ts/syntax.d.ts +22 -0
  12. package/dist/{inTabFetch-0157c4a1.esm.js → inTabFetch-877e7d11.esm.js} +1 -1
  13. package/dist/{inTabFetch-09f7ae69.cjs.dev.js → inTabFetch-c8966e73.cjs.dev.js} +1 -1
  14. package/dist/{inTabFetch-7f2c9455.cjs.prod.js → inTabFetch-f6694ad2.cjs.prod.js} +1 -1
  15. package/dist/{publishKit-89923030.esm.js → publishKit-0709423c.esm.js} +3 -3
  16. package/dist/{publishKit-5227c288.cjs.dev.js → publishKit-cfe1273d.cjs.dev.js} +2 -2
  17. package/dist/{publishKit-26231426.cjs.prod.js → publishKit-e7f7db7c.cjs.prod.js} +2 -2
  18. package/dist/valbuild-server.cjs.dev.js +2 -2
  19. package/dist/valbuild-server.cjs.prod.js +2 -2
  20. package/dist/valbuild-server.esm.js +4 -4
  21. package/internal/browser/dist/valbuild-server-internal-browser.cjs.dev.js +2 -2
  22. package/internal/browser/dist/valbuild-server-internal-browser.cjs.prod.js +2 -2
  23. package/internal/browser/dist/valbuild-server-internal-browser.esm.js +2 -2
  24. package/internal/dist/valbuild-server-internal.cjs.dev.js +2 -2
  25. package/internal/dist/valbuild-server-internal.cjs.prod.js +2 -2
  26. package/internal/dist/valbuild-server-internal.esm.js +2 -2
  27. package/package.json +5 -5
package/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # @valbuild/server
2
2
 
3
+ ## 0.154.0
4
+
5
+ ### Patch Changes
6
+
7
+ - [#1067](https://github.com/valbuild/val/pull/1067) [`70bd897`](https://github.com/valbuild/val/commit/70bd89741d23f89407ddab56de2a70ad62e79fee) Thanks [@freekh](https://github.com/freekh)! - Two answers from `/api/val/patches` no longer tell the Studio something false when the content service behind it fails part of the way.
8
+
9
+ - **Discarding a change while the content service is down no longer looks like it worked.** If the content service answered with an error or could not be reached, `DELETE /api/val/patches` answered 200 with every patch as deleted. The Studio then forgot changes that still existed: a reload brought them back, and the next publish could ship a change you had discarded. It now answers 502 with the content service's reason, and the Studio keeps the change and says the discard failed.
10
+ - **An edit made while someone else is editing is no longer stuck unsaved.** A batch of edits is saved one patch at a time, so another editor's change can land between two of yours. When it did, the server answered the conflict without saying the first patch had been saved, the Studio sent that patch again, and the content service refused it as one it already had. The save then retried forever and the edit after it was never saved. The conflict now names what was saved, as the other partial failures already did, and the Studio sends only the rest.
11
+
12
+ - [#1068](https://github.com/valbuild/val/pull/1068) [`0b1cbe6`](https://github.com/valbuild/val/commit/0b1cbe6858094b21fa15a8fa9b88d5f4304d68e1) Thanks [@freekh](https://github.com/freekh)! - Saving an edit no longer fails with `Converting circular structure to JSON` when a `.val.ts` file uses object spreads, such as `{ title: "…", ...noMedia, learnMore: null }`.
13
+
14
+ An edit to a key written out after every spread in its object is now saved, and the spread is left as it is. An edit to a key a spread supplies, or one a later spread may override, is refused with a message that names the file, the line and the spread, so you know which value to write out — before, any spread anywhere along the edited path refused the save, and the refusal itself crashed `/save` with a 500.
15
+
16
+ - Updated dependencies [[`d2956df`](https://github.com/valbuild/val/commit/d2956df9d82f7cba1cd26a754ccbd0fa10a5d641), [`c71a92c`](https://github.com/valbuild/val/commit/c71a92ccc40eed16c9b2669d6b26efee51240eea), [`9ee9bdf`](https://github.com/valbuild/val/commit/9ee9bdf8f1feb57b2ab2f70c82a8c839256f8687), [`af4f6fc`](https://github.com/valbuild/val/commit/af4f6fc2b2f344ca474fc80664365a6fac4325b1), [`70bd897`](https://github.com/valbuild/val/commit/70bd89741d23f89407ddab56de2a70ad62e79fee), [`d85f2d7`](https://github.com/valbuild/val/commit/d85f2d75c3dd2732ad1fb9f0c6c0023f4f5de834), [`7f49d72`](https://github.com/valbuild/val/commit/7f49d72b5d2a447025cfec474ff1d85b21e4333e)]:
17
+ - @valbuild/ui@0.154.0
18
+ - @valbuild/shared@0.154.0
19
+
20
+ ## 0.153.6
21
+
22
+ ### Patch Changes
23
+
24
+ - [#1057](https://github.com/valbuild/val/pull/1057) [`79b4452`](https://github.com/valbuild/val/commit/79b4452441ae2a9442f1217cca372f2d7cebd5a4) Thanks [@freekh](https://github.com/freekh)! - Security fixes. Update if you run Val's dev server, or have deployed a site without `VAL_API_KEY` and `VAL_SECRET`.
25
+
26
+ - **`/api/val/files` serves media only.** It answered any path in the project, without a sign-in: `/api/val/files/.env` returned the file. It now serves files under `/public`, and their drafts, and nothing else.
27
+ - **An upload cannot be written outside Val's patch store.** A file's path and a patch's id are checked before anything is written or read, so a path with `..` in it is refused.
28
+ - **In local filesystem mode, the API answers only your own Studio.** A request from another site's page is refused, and so is one addressed to a host name that is not `localhost` or an IP address. If you develop on another name (`my-app.test`, a tunnel that passes its own `Host`), list it in the `VAL_ALLOWED_HOSTS` environment variable, comma separated.
29
+ - **A deployed site without credentials no longer serves the API.** Without `VAL_API_KEY` and `VAL_SECRET` an app runs in local filesystem mode, which has no sign-in. With `NODE_ENV=production` it now refuses, and says what to set.
30
+ - **`redirect_to` stays on your site.** `/api/val/logout`, `/enable`, `/disable` and `/authorize` redirected to any URL they were given. They now accept a path, or a URL on the same site.
31
+ - **Draft mode is turned on after sign-in**, not when the sign-in starts, so a visitor who is not signed in can no longer switch it on.
32
+ - `image-size`, `simple-git` and `zod` are updated past their published advisories.
33
+
34
+ - Updated dependencies [[`a561665`](https://github.com/valbuild/val/commit/a5616659c202eaa5ad61e1a035c9b9ca2a007e9a), [`00b13fe`](https://github.com/valbuild/val/commit/00b13fe0ed9adc2ce22b3e9827e9fa5b10d5bfdf), [`79b4452`](https://github.com/valbuild/val/commit/79b4452441ae2a9442f1217cca372f2d7cebd5a4), [`3944e3e`](https://github.com/valbuild/val/commit/3944e3e3c33678bca2a0aa46fcc0f4adbf8c2ba5), [`a8a1056`](https://github.com/valbuild/val/commit/a8a105620849ff73b91aff1492c39548926a7a7f), [`2c98fcc`](https://github.com/valbuild/val/commit/2c98fcc776f15c979dae74a1a86ca91cad70e7de), [`0dd664f`](https://github.com/valbuild/val/commit/0dd664f7bde9bfb552ecd643b2345998c69d5914)]:
35
+ - @valbuild/ui@0.153.6
36
+ - @valbuild/shared@0.153.6
37
+
3
38
  ## 0.153.5
4
39
 
5
40
  ### Patch Changes
@@ -2,9 +2,9 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var inTabFetch = require('../../dist/inTabFetch-09f7ae69.cjs.dev.js');
5
+ var inTabFetch = require('../../dist/inTabFetch-c8966e73.cjs.dev.js');
6
6
  require('@valbuild/core');
7
- require('../../dist/ValRouterCore-4e3757ac.cjs.dev.js');
7
+ require('../../dist/ValRouterCore-0c088c9e.cjs.dev.js');
8
8
  require('zod');
9
9
  require('@valbuild/shared/internal');
10
10
  require('zod-validation-error');
@@ -2,9 +2,9 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var inTabFetch = require('../../dist/inTabFetch-7f2c9455.cjs.prod.js');
5
+ var inTabFetch = require('../../dist/inTabFetch-f6694ad2.cjs.prod.js');
6
6
  require('@valbuild/core');
7
- require('../../dist/ValRouterCore-d658dc75.cjs.prod.js');
7
+ require('../../dist/ValRouterCore-4be8eaf1.cjs.prod.js');
8
8
  require('zod');
9
9
  require('@valbuild/shared/internal');
10
10
  require('zod-validation-error');
@@ -1,6 +1,6 @@
1
- export { c as createInTabValFetch } from '../../dist/inTabFetch-0157c4a1.esm.js';
1
+ export { c as createInTabValFetch } from '../../dist/inTabFetch-877e7d11.esm.js';
2
2
  import '@valbuild/core';
3
- import '../../dist/ValRouterCore-257f140c.esm.js';
3
+ import '../../dist/ValRouterCore-fe985e4c.esm.js';
4
4
  import 'zod';
5
5
  import '@valbuild/shared/internal';
6
6
  import 'zod-validation-error';
@@ -2,7 +2,7 @@
2
2
 
3
3
  var core = require('@valbuild/core');
4
4
  var server = require('@valbuild/ui/server');
5
- var ValRouterCore = require('./ValRouterCore-4e3757ac.cjs.dev.js');
5
+ var ValRouterCore = require('./ValRouterCore-0c088c9e.cjs.dev.js');
6
6
  var path = require('path');
7
7
  var ts = require('typescript');
8
8
  var z = require('zod');
@@ -135,17 +135,61 @@ function evaluateExpression(value) {
135
135
  return fp.result.err(new ValSyntaxError("Expression must be a literal", value));
136
136
  }
137
137
  }
138
+
139
+ /**
140
+ * Finds the property `key` is written as in an object literal, for an edit to
141
+ * write into.
142
+ *
143
+ * An object may spread another into itself (`{ ...noMedia, code: null }`): the
144
+ * module evaluates it, so the value reads fine, and an edit to a key written
145
+ * out AFTER every spread can go ahead - that property is the one that wins.
146
+ * What cannot is an edit to a key a spread might supply or override, since we
147
+ * would be writing a value the module does not end up with. Those are
148
+ * refused, naming the spread, so the author knows which line to write out.
149
+ */
138
150
  function findObjectPropertyAssignment(value, key) {
139
- return fp.pipe(validateObjectProperties(value.properties), fp.result.flatMap(assignments => {
151
+ const spreads = value.properties.filter(ts__default["default"].isSpreadAssignment);
152
+ return fp.pipe(validateObjectProperties(value.properties.filter(property => !ts__default["default"].isSpreadAssignment(property))), fp.result.flatMap(assignments => {
140
153
  const matchingAssignments = assignments.filter(assignment => assignment.name.text === key);
141
- if (matchingAssignments.length === 0) return fp.result.ok(undefined);
142
154
  if (matchingAssignments.length > 1) {
143
155
  return fp.result.err(new ValSyntaxError(`Object key "${key}" is ambiguous`, value));
144
156
  }
145
157
  const [assignment] = matchingAssignments;
158
+ if (assignment === undefined) {
159
+ if (spreads.length > 0) {
160
+ return fp.result.err(new ValSyntaxError(`Cannot edit "${key}": it is not written out in this object, so it may come from ${spreadNames(spreads)}. Write "${key}" out after the spread to make it editable`, spreads[spreads.length - 1]));
161
+ }
162
+ return fp.result.ok(undefined);
163
+ }
164
+ const overriding = spreads.filter(spread => spread.pos > assignment.pos);
165
+ if (overriding.length > 0) {
166
+ return fp.result.err(new ValSyntaxError(`Cannot edit "${key}": ${spreadNames(overriding)} comes after it and may override it. Move "${key}" after the spread to make it editable`, assignment));
167
+ }
146
168
  return fp.result.ok(assignment);
147
169
  }));
148
170
  }
171
+
172
+ /**
173
+ * Finds the property `key` is written as, for a REMOVE: stricter than
174
+ * {@link findObjectPropertyAssignment}, because removing a key from an object
175
+ * that spreads another into it is refused outright. The key's own property may
176
+ * be all that hides a value the spread supplies, and removing it would bring
177
+ * that value back - and for a `.jsonValues()` entry, delete its file as well.
178
+ *
179
+ * Every remove goes through this, so the two that exist (a value, and a
180
+ * `.jsonValues()` entry) cannot disagree about it.
181
+ */
182
+ function findObjectPropertyAssignmentToRemove(value, key) {
183
+ const spreads = value.properties.filter(ts__default["default"].isSpreadAssignment);
184
+ if (spreads.length > 0) {
185
+ return fp.result.err(new ValSyntaxError(`Cannot remove "${key}" from an object that spreads another into it: ${spreadNames(spreads)} may have a "${key}" of its own, and removing this one would bring it back`, value));
186
+ }
187
+ return findObjectPropertyAssignment(value, key);
188
+ }
189
+ function spreadNames(spreads) {
190
+ // Not `getText()`: it needs parent pointers, and the parsers here do not set them.
191
+ return spreads.map(spread => ts__default["default"].isIdentifier(spread.expression) ? `"...${spread.expression.text}"` : "a spread").join(", ");
192
+ }
149
193
  function validateInitializers(nodes) {
150
194
  for (const node of nodes) {
151
195
  if (ts__default["default"].isSpreadElement(node)) {
@@ -277,7 +321,7 @@ function removeValJsonEntry(document, recordPath, key) {
277
321
  if (!ts__default["default"].isObjectLiteralExpression(recordNode)) {
278
322
  return fp.result.err(new patch.PatchError("Cannot remove jsonValues entry: record source is not an object literal"));
279
323
  }
280
- return fp.pipe(findObjectPropertyAssignment(recordNode, key), fp.result.flatMap(assignment => {
324
+ return fp.pipe(findObjectPropertyAssignmentToRemove(recordNode, key), fp.result.flatMap(assignment => {
281
325
  if (!assignment) {
282
326
  return fp.result.err(new patch.PatchError(`Cannot remove jsonValues entry '${key}': it does not exist`));
283
327
  }
@@ -492,7 +536,7 @@ function removeFromNode(document, node, key) {
492
536
  if (ts__default["default"].isArrayLiteralExpression(node)) {
493
537
  return fp.pipe(parseAndValidateArrayInboundsIndex(key, node.elements), fp.result.map(index => removeAt(document, node.elements, index)));
494
538
  } else if (ts__default["default"].isObjectLiteralExpression(node)) {
495
- return fp.pipe(findObjectPropertyAssignment(node, key), fp.result.flatMap(assignment => {
539
+ return fp.pipe(findObjectPropertyAssignmentToRemove(node, key), fp.result.flatMap(assignment => {
496
540
  if (!assignment) {
497
541
  return fp.result.err(new patch.PatchError("Cannot remove object element which does not exist"));
498
542
  }
@@ -2205,7 +2249,7 @@ function createFsSketchpadStore(rootDir, now = () => new Date()) {
2205
2249
  * as a bundler does.
2206
2250
  */
2207
2251
  function loadTypeScriptKit() {
2208
- return Promise.resolve().then(function () { return require('./publishKit-5227c288.cjs.dev.js'); });
2252
+ return Promise.resolve().then(function () { return require('./publishKit-cfe1273d.cjs.dev.js'); });
2209
2253
  }
2210
2254
 
2211
2255
  /** Serializes a schema, or gives up quietly — serialization errors are reported elsewhere. */
@@ -2963,6 +3007,21 @@ class ValOpsFS extends ValRouterCore.ValOps {
2963
3007
  //
2964
3008
  // Staging is what makes that state unreachable rather than tolerated. See
2965
3009
  // `uploadsDir`.
3010
+ // Both are joined onto the patches directory below. See `safeFilePath`.
3011
+ if (!ValRouterCore.isSafePatchId(patchId)) {
3012
+ return {
3013
+ error: {
3014
+ message: "Not a valid patch id."
3015
+ }
3016
+ };
3017
+ }
3018
+ if (!ValRouterCore.isMediaFilePath(filePath)) {
3019
+ return {
3020
+ error: {
3021
+ message: `Cannot store a file at '${filePath}'. ${ValRouterCore.MEDIA_FILE_PATH_ACCEPTS}`
3022
+ }
3023
+ };
3024
+ }
2966
3025
  const patchesDir = this.getPatchesDir();
2967
3026
  const patchFilePath = stagedPatchBinaryFile(patchesDir, patchId, filePath);
2968
3027
  const metadataFilePath = stagedPatchBinaryFileMetadata(patchesDir, patchId, filePath);
@@ -3070,6 +3129,9 @@ class ValOpsFS extends ValRouterCore.ValOps {
3070
3129
  async getBase64EncodedBinaryFileFromPatch(filePath, patchId) {
3071
3130
  // Straight from the id. This used to read and parse every patch on disk to
3072
3131
  // work out which directory the file was under, on every single image request.
3132
+ if (!ValRouterCore.isSafePatchId(patchId) || !ValRouterCore.isMediaFilePath(filePath)) {
3133
+ return null;
3134
+ }
3073
3135
  const patchesDir = this.getPatchesDir();
3074
3136
  const absPath = this.wherePatchFileIs(patchBinaryFile(patchesDir, patchId, filePath), stagedPatchBinaryFile(patchesDir, patchId, filePath));
3075
3137
  if (absPath === null) {
@@ -3267,6 +3329,16 @@ class ValOpsFS extends ValRouterCore.ValOps {
3267
3329
  }] of localFileDescriptors) {
3268
3330
  const filePath = ref;
3269
3331
  const absPath = path__default["default"].join(this.rootDir, ...filePath.split("/"));
3332
+ // A publish writes uploaded files under /public and nowhere else.
3333
+ // `createPatch` refuses any other path, so this is for a patch that was
3334
+ // already on disk, or put there by hand.
3335
+ if (!ValRouterCore.isPublicFilePath(filePath) || !ValRouterCore.isSafePatchId(patchId)) {
3336
+ errors[absPath] = {
3337
+ message: `Not written: '${filePath}' is not under /public.`,
3338
+ filePath
3339
+ };
3340
+ continue;
3341
+ }
3270
3342
  try {
3271
3343
  this.host.copyFile(patchBinaryFile(this.getPatchesDir(), patchId, filePath), absPath);
3272
3344
  updatedFiles.push(absPath);
@@ -3317,6 +3389,9 @@ class ValOpsFS extends ValRouterCore.ValOps {
3317
3389
  async openBinaryFile(filePath, fromPatch) {
3318
3390
  let absPath;
3319
3391
  if (fromPatch) {
3392
+ if (!ValRouterCore.isSafePatchId(fromPatch.patchId) || !ValRouterCore.isMediaFilePath(filePath)) {
3393
+ return null;
3394
+ }
3320
3395
  const patchesDir = this.getPatchesDir();
3321
3396
  absPath = this.wherePatchFileIs(patchBinaryFile(patchesDir, fromPatch.patchId, filePath), stagedPatchBinaryFile(patchesDir, fromPatch.patchId, filePath));
3322
3397
  } else {
@@ -4989,7 +5064,7 @@ async function stagedModuleSources(files) {
4989
5064
  parseValFile,
4990
5065
  analyzeValModule,
4991
5066
  evaluateModuleSource
4992
- } = await Promise.resolve().then(function () { return require('./publishKit-5227c288.cjs.dev.js'); });
5067
+ } = await Promise.resolve().then(function () { return require('./publishKit-cfe1273d.cjs.dev.js'); });
4993
5068
  const sources = {};
4994
5069
  for (const {
4995
5070
  path,
@@ -14328,7 +14403,7 @@ commitPrepared,
14328
14403
  publishOverride) {
14329
14404
  var _opts$versions;
14330
14405
  const valServerConfig = await initHandlerOptions(route, opts, config);
14331
- return ValRouterCore.ValServer(valModules, {
14406
+ const server = ValRouterCore.ValServer(valModules, {
14332
14407
  formatter,
14333
14408
  commitPrepared,
14334
14409
  publishOverride,
@@ -14340,6 +14415,13 @@ publishOverride) {
14340
14415
  } : {}),
14341
14416
  ...valServerConfig
14342
14417
  }, callbacks, nodePlatform);
14418
+ // fs mode has no sign-in, so which requests it answers is decided here.
14419
+ ValRouterCore.setRequestGuard(server, {
14420
+ mode: valServerConfig.mode,
14421
+ production: process.env.NODE_ENV === "production",
14422
+ allowedHosts: ValRouterCore.parseAllowedHosts(process.env.VAL_ALLOWED_HOSTS)
14423
+ });
14424
+ return server;
14343
14425
  }
14344
14426
 
14345
14427
  /**
@@ -1,6 +1,6 @@
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-257f140c.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 isSafePatchId, o as isMediaFilePath, M as MEDIA_FILE_PATH_ACCEPTS, p as bufferFromDataUrl, q as getFieldsForType, u as uploadRemoteFile, d as getFileExt, t as isPublicFilePath, w as guessMimeTypeFromPath, x as createMetadataFromBuffer, D as DEFAULT_ANALYTICS_INGEST_URL, e as ValOpsMemory, y as sessionAuth, z as isHttpOps, A as isHlsMasterPlaylist, B as sumHlsSegmentDurations, C as parseHlsMasterVariants, E as largestHlsVariant, F as fallbackRefOf, G as mapHlsUris, H as movedRemoteHost, J as needsHostCheck, K as rewriteRefHost, L as fallbackRemoteHost, N as checkRemoteFiles, O as ValServer, P as setRequestGuard, Q as parseAllowedHosts, R as createValRequestHandler } from './ValRouterCore-fe985e4c.esm.js';
4
4
  import path from 'path';
5
5
  import ts from 'typescript';
6
6
  import { z } from 'zod';
@@ -101,17 +101,61 @@ function evaluateExpression(value) {
101
101
  return result.err(new ValSyntaxError("Expression must be a literal", value));
102
102
  }
103
103
  }
104
+
105
+ /**
106
+ * Finds the property `key` is written as in an object literal, for an edit to
107
+ * write into.
108
+ *
109
+ * An object may spread another into itself (`{ ...noMedia, code: null }`): the
110
+ * module evaluates it, so the value reads fine, and an edit to a key written
111
+ * out AFTER every spread can go ahead - that property is the one that wins.
112
+ * What cannot is an edit to a key a spread might supply or override, since we
113
+ * would be writing a value the module does not end up with. Those are
114
+ * refused, naming the spread, so the author knows which line to write out.
115
+ */
104
116
  function findObjectPropertyAssignment(value, key) {
105
- return pipe(validateObjectProperties(value.properties), result.flatMap(assignments => {
117
+ const spreads = value.properties.filter(ts.isSpreadAssignment);
118
+ return pipe(validateObjectProperties(value.properties.filter(property => !ts.isSpreadAssignment(property))), result.flatMap(assignments => {
106
119
  const matchingAssignments = assignments.filter(assignment => assignment.name.text === key);
107
- if (matchingAssignments.length === 0) return result.ok(undefined);
108
120
  if (matchingAssignments.length > 1) {
109
121
  return result.err(new ValSyntaxError(`Object key "${key}" is ambiguous`, value));
110
122
  }
111
123
  const [assignment] = matchingAssignments;
124
+ if (assignment === undefined) {
125
+ if (spreads.length > 0) {
126
+ return result.err(new ValSyntaxError(`Cannot edit "${key}": it is not written out in this object, so it may come from ${spreadNames(spreads)}. Write "${key}" out after the spread to make it editable`, spreads[spreads.length - 1]));
127
+ }
128
+ return result.ok(undefined);
129
+ }
130
+ const overriding = spreads.filter(spread => spread.pos > assignment.pos);
131
+ if (overriding.length > 0) {
132
+ return result.err(new ValSyntaxError(`Cannot edit "${key}": ${spreadNames(overriding)} comes after it and may override it. Move "${key}" after the spread to make it editable`, assignment));
133
+ }
112
134
  return result.ok(assignment);
113
135
  }));
114
136
  }
137
+
138
+ /**
139
+ * Finds the property `key` is written as, for a REMOVE: stricter than
140
+ * {@link findObjectPropertyAssignment}, because removing a key from an object
141
+ * that spreads another into it is refused outright. The key's own property may
142
+ * be all that hides a value the spread supplies, and removing it would bring
143
+ * that value back - and for a `.jsonValues()` entry, delete its file as well.
144
+ *
145
+ * Every remove goes through this, so the two that exist (a value, and a
146
+ * `.jsonValues()` entry) cannot disagree about it.
147
+ */
148
+ function findObjectPropertyAssignmentToRemove(value, key) {
149
+ const spreads = value.properties.filter(ts.isSpreadAssignment);
150
+ if (spreads.length > 0) {
151
+ return result.err(new ValSyntaxError(`Cannot remove "${key}" from an object that spreads another into it: ${spreadNames(spreads)} may have a "${key}" of its own, and removing this one would bring it back`, value));
152
+ }
153
+ return findObjectPropertyAssignment(value, key);
154
+ }
155
+ function spreadNames(spreads) {
156
+ // Not `getText()`: it needs parent pointers, and the parsers here do not set them.
157
+ return spreads.map(spread => ts.isIdentifier(spread.expression) ? `"...${spread.expression.text}"` : "a spread").join(", ");
158
+ }
115
159
  function validateInitializers(nodes) {
116
160
  for (const node of nodes) {
117
161
  if (ts.isSpreadElement(node)) {
@@ -243,7 +287,7 @@ function removeValJsonEntry(document, recordPath, key) {
243
287
  if (!ts.isObjectLiteralExpression(recordNode)) {
244
288
  return result.err(new PatchError("Cannot remove jsonValues entry: record source is not an object literal"));
245
289
  }
246
- return pipe(findObjectPropertyAssignment(recordNode, key), result.flatMap(assignment => {
290
+ return pipe(findObjectPropertyAssignmentToRemove(recordNode, key), result.flatMap(assignment => {
247
291
  if (!assignment) {
248
292
  return result.err(new PatchError(`Cannot remove jsonValues entry '${key}': it does not exist`));
249
293
  }
@@ -458,7 +502,7 @@ function removeFromNode(document, node, key) {
458
502
  if (ts.isArrayLiteralExpression(node)) {
459
503
  return pipe(parseAndValidateArrayInboundsIndex(key, node.elements), result.map(index => removeAt(document, node.elements, index)));
460
504
  } else if (ts.isObjectLiteralExpression(node)) {
461
- return pipe(findObjectPropertyAssignment(node, key), result.flatMap(assignment => {
505
+ return pipe(findObjectPropertyAssignmentToRemove(node, key), result.flatMap(assignment => {
462
506
  if (!assignment) {
463
507
  return result.err(new PatchError("Cannot remove object element which does not exist"));
464
508
  }
@@ -2171,7 +2215,7 @@ function createFsSketchpadStore(rootDir, now = () => new Date()) {
2171
2215
  * as a bundler does.
2172
2216
  */
2173
2217
  function loadTypeScriptKit() {
2174
- return import('./publishKit-89923030.esm.js');
2218
+ return import('./publishKit-0709423c.esm.js');
2175
2219
  }
2176
2220
 
2177
2221
  /** Serializes a schema, or gives up quietly — serialization errors are reported elsewhere. */
@@ -2929,6 +2973,21 @@ class ValOpsFS extends ValOps {
2929
2973
  //
2930
2974
  // Staging is what makes that state unreachable rather than tolerated. See
2931
2975
  // `uploadsDir`.
2976
+ // Both are joined onto the patches directory below. See `safeFilePath`.
2977
+ if (!isSafePatchId(patchId)) {
2978
+ return {
2979
+ error: {
2980
+ message: "Not a valid patch id."
2981
+ }
2982
+ };
2983
+ }
2984
+ if (!isMediaFilePath(filePath)) {
2985
+ return {
2986
+ error: {
2987
+ message: `Cannot store a file at '${filePath}'. ${MEDIA_FILE_PATH_ACCEPTS}`
2988
+ }
2989
+ };
2990
+ }
2932
2991
  const patchesDir = this.getPatchesDir();
2933
2992
  const patchFilePath = stagedPatchBinaryFile(patchesDir, patchId, filePath);
2934
2993
  const metadataFilePath = stagedPatchBinaryFileMetadata(patchesDir, patchId, filePath);
@@ -3036,6 +3095,9 @@ class ValOpsFS extends ValOps {
3036
3095
  async getBase64EncodedBinaryFileFromPatch(filePath, patchId) {
3037
3096
  // Straight from the id. This used to read and parse every patch on disk to
3038
3097
  // work out which directory the file was under, on every single image request.
3098
+ if (!isSafePatchId(patchId) || !isMediaFilePath(filePath)) {
3099
+ return null;
3100
+ }
3039
3101
  const patchesDir = this.getPatchesDir();
3040
3102
  const absPath = this.wherePatchFileIs(patchBinaryFile(patchesDir, patchId, filePath), stagedPatchBinaryFile(patchesDir, patchId, filePath));
3041
3103
  if (absPath === null) {
@@ -3233,6 +3295,16 @@ class ValOpsFS extends ValOps {
3233
3295
  }] of localFileDescriptors) {
3234
3296
  const filePath = ref;
3235
3297
  const absPath = path.join(this.rootDir, ...filePath.split("/"));
3298
+ // A publish writes uploaded files under /public and nowhere else.
3299
+ // `createPatch` refuses any other path, so this is for a patch that was
3300
+ // already on disk, or put there by hand.
3301
+ if (!isPublicFilePath(filePath) || !isSafePatchId(patchId)) {
3302
+ errors[absPath] = {
3303
+ message: `Not written: '${filePath}' is not under /public.`,
3304
+ filePath
3305
+ };
3306
+ continue;
3307
+ }
3236
3308
  try {
3237
3309
  this.host.copyFile(patchBinaryFile(this.getPatchesDir(), patchId, filePath), absPath);
3238
3310
  updatedFiles.push(absPath);
@@ -3283,6 +3355,9 @@ class ValOpsFS extends ValOps {
3283
3355
  async openBinaryFile(filePath, fromPatch) {
3284
3356
  let absPath;
3285
3357
  if (fromPatch) {
3358
+ if (!isSafePatchId(fromPatch.patchId) || !isMediaFilePath(filePath)) {
3359
+ return null;
3360
+ }
3286
3361
  const patchesDir = this.getPatchesDir();
3287
3362
  absPath = this.wherePatchFileIs(patchBinaryFile(patchesDir, fromPatch.patchId, filePath), stagedPatchBinaryFile(patchesDir, fromPatch.patchId, filePath));
3288
3363
  } else {
@@ -4955,7 +5030,7 @@ async function stagedModuleSources(files) {
4955
5030
  parseValFile,
4956
5031
  analyzeValModule,
4957
5032
  evaluateModuleSource
4958
- } = await import('./publishKit-89923030.esm.js');
5033
+ } = await import('./publishKit-0709423c.esm.js');
4959
5034
  const sources = {};
4960
5035
  for (const {
4961
5036
  path,
@@ -14294,7 +14369,7 @@ commitPrepared,
14294
14369
  publishOverride) {
14295
14370
  var _opts$versions;
14296
14371
  const valServerConfig = await initHandlerOptions(route, opts, config);
14297
- return ValServer(valModules, {
14372
+ const server = ValServer(valModules, {
14298
14373
  formatter,
14299
14374
  commitPrepared,
14300
14375
  publishOverride,
@@ -14306,6 +14381,13 @@ publishOverride) {
14306
14381
  } : {}),
14307
14382
  ...valServerConfig
14308
14383
  }, callbacks, nodePlatform);
14384
+ // fs mode has no sign-in, so which requests it answers is decided here.
14385
+ setRequestGuard(server, {
14386
+ mode: valServerConfig.mode,
14387
+ production: process.env.NODE_ENV === "production",
14388
+ allowedHosts: parseAllowedHosts(process.env.VAL_ALLOWED_HOSTS)
14389
+ });
14390
+ return server;
14309
14391
  }
14310
14392
 
14311
14393
  /**
@@ -2,7 +2,7 @@
2
2
 
3
3
  var core = require('@valbuild/core');
4
4
  var server = require('@valbuild/ui/server');
5
- var ValRouterCore = require('./ValRouterCore-d658dc75.cjs.prod.js');
5
+ var ValRouterCore = require('./ValRouterCore-4be8eaf1.cjs.prod.js');
6
6
  var path = require('path');
7
7
  var ts = require('typescript');
8
8
  var z = require('zod');
@@ -135,17 +135,61 @@ function evaluateExpression(value) {
135
135
  return fp.result.err(new ValSyntaxError("Expression must be a literal", value));
136
136
  }
137
137
  }
138
+
139
+ /**
140
+ * Finds the property `key` is written as in an object literal, for an edit to
141
+ * write into.
142
+ *
143
+ * An object may spread another into itself (`{ ...noMedia, code: null }`): the
144
+ * module evaluates it, so the value reads fine, and an edit to a key written
145
+ * out AFTER every spread can go ahead - that property is the one that wins.
146
+ * What cannot is an edit to a key a spread might supply or override, since we
147
+ * would be writing a value the module does not end up with. Those are
148
+ * refused, naming the spread, so the author knows which line to write out.
149
+ */
138
150
  function findObjectPropertyAssignment(value, key) {
139
- return fp.pipe(validateObjectProperties(value.properties), fp.result.flatMap(assignments => {
151
+ const spreads = value.properties.filter(ts__default["default"].isSpreadAssignment);
152
+ return fp.pipe(validateObjectProperties(value.properties.filter(property => !ts__default["default"].isSpreadAssignment(property))), fp.result.flatMap(assignments => {
140
153
  const matchingAssignments = assignments.filter(assignment => assignment.name.text === key);
141
- if (matchingAssignments.length === 0) return fp.result.ok(undefined);
142
154
  if (matchingAssignments.length > 1) {
143
155
  return fp.result.err(new ValSyntaxError(`Object key "${key}" is ambiguous`, value));
144
156
  }
145
157
  const [assignment] = matchingAssignments;
158
+ if (assignment === undefined) {
159
+ if (spreads.length > 0) {
160
+ return fp.result.err(new ValSyntaxError(`Cannot edit "${key}": it is not written out in this object, so it may come from ${spreadNames(spreads)}. Write "${key}" out after the spread to make it editable`, spreads[spreads.length - 1]));
161
+ }
162
+ return fp.result.ok(undefined);
163
+ }
164
+ const overriding = spreads.filter(spread => spread.pos > assignment.pos);
165
+ if (overriding.length > 0) {
166
+ return fp.result.err(new ValSyntaxError(`Cannot edit "${key}": ${spreadNames(overriding)} comes after it and may override it. Move "${key}" after the spread to make it editable`, assignment));
167
+ }
146
168
  return fp.result.ok(assignment);
147
169
  }));
148
170
  }
171
+
172
+ /**
173
+ * Finds the property `key` is written as, for a REMOVE: stricter than
174
+ * {@link findObjectPropertyAssignment}, because removing a key from an object
175
+ * that spreads another into it is refused outright. The key's own property may
176
+ * be all that hides a value the spread supplies, and removing it would bring
177
+ * that value back - and for a `.jsonValues()` entry, delete its file as well.
178
+ *
179
+ * Every remove goes through this, so the two that exist (a value, and a
180
+ * `.jsonValues()` entry) cannot disagree about it.
181
+ */
182
+ function findObjectPropertyAssignmentToRemove(value, key) {
183
+ const spreads = value.properties.filter(ts__default["default"].isSpreadAssignment);
184
+ if (spreads.length > 0) {
185
+ return fp.result.err(new ValSyntaxError(`Cannot remove "${key}" from an object that spreads another into it: ${spreadNames(spreads)} may have a "${key}" of its own, and removing this one would bring it back`, value));
186
+ }
187
+ return findObjectPropertyAssignment(value, key);
188
+ }
189
+ function spreadNames(spreads) {
190
+ // Not `getText()`: it needs parent pointers, and the parsers here do not set them.
191
+ return spreads.map(spread => ts__default["default"].isIdentifier(spread.expression) ? `"...${spread.expression.text}"` : "a spread").join(", ");
192
+ }
149
193
  function validateInitializers(nodes) {
150
194
  for (const node of nodes) {
151
195
  if (ts__default["default"].isSpreadElement(node)) {
@@ -277,7 +321,7 @@ function removeValJsonEntry(document, recordPath, key) {
277
321
  if (!ts__default["default"].isObjectLiteralExpression(recordNode)) {
278
322
  return fp.result.err(new patch.PatchError("Cannot remove jsonValues entry: record source is not an object literal"));
279
323
  }
280
- return fp.pipe(findObjectPropertyAssignment(recordNode, key), fp.result.flatMap(assignment => {
324
+ return fp.pipe(findObjectPropertyAssignmentToRemove(recordNode, key), fp.result.flatMap(assignment => {
281
325
  if (!assignment) {
282
326
  return fp.result.err(new patch.PatchError(`Cannot remove jsonValues entry '${key}': it does not exist`));
283
327
  }
@@ -492,7 +536,7 @@ function removeFromNode(document, node, key) {
492
536
  if (ts__default["default"].isArrayLiteralExpression(node)) {
493
537
  return fp.pipe(parseAndValidateArrayInboundsIndex(key, node.elements), fp.result.map(index => removeAt(document, node.elements, index)));
494
538
  } else if (ts__default["default"].isObjectLiteralExpression(node)) {
495
- return fp.pipe(findObjectPropertyAssignment(node, key), fp.result.flatMap(assignment => {
539
+ return fp.pipe(findObjectPropertyAssignmentToRemove(node, key), fp.result.flatMap(assignment => {
496
540
  if (!assignment) {
497
541
  return fp.result.err(new patch.PatchError("Cannot remove object element which does not exist"));
498
542
  }
@@ -2205,7 +2249,7 @@ function createFsSketchpadStore(rootDir, now = () => new Date()) {
2205
2249
  * as a bundler does.
2206
2250
  */
2207
2251
  function loadTypeScriptKit() {
2208
- return Promise.resolve().then(function () { return require('./publishKit-26231426.cjs.prod.js'); });
2252
+ return Promise.resolve().then(function () { return require('./publishKit-e7f7db7c.cjs.prod.js'); });
2209
2253
  }
2210
2254
 
2211
2255
  /** Serializes a schema, or gives up quietly — serialization errors are reported elsewhere. */
@@ -2963,6 +3007,21 @@ class ValOpsFS extends ValRouterCore.ValOps {
2963
3007
  //
2964
3008
  // Staging is what makes that state unreachable rather than tolerated. See
2965
3009
  // `uploadsDir`.
3010
+ // Both are joined onto the patches directory below. See `safeFilePath`.
3011
+ if (!ValRouterCore.isSafePatchId(patchId)) {
3012
+ return {
3013
+ error: {
3014
+ message: "Not a valid patch id."
3015
+ }
3016
+ };
3017
+ }
3018
+ if (!ValRouterCore.isMediaFilePath(filePath)) {
3019
+ return {
3020
+ error: {
3021
+ message: `Cannot store a file at '${filePath}'. ${ValRouterCore.MEDIA_FILE_PATH_ACCEPTS}`
3022
+ }
3023
+ };
3024
+ }
2966
3025
  const patchesDir = this.getPatchesDir();
2967
3026
  const patchFilePath = stagedPatchBinaryFile(patchesDir, patchId, filePath);
2968
3027
  const metadataFilePath = stagedPatchBinaryFileMetadata(patchesDir, patchId, filePath);
@@ -3070,6 +3129,9 @@ class ValOpsFS extends ValRouterCore.ValOps {
3070
3129
  async getBase64EncodedBinaryFileFromPatch(filePath, patchId) {
3071
3130
  // Straight from the id. This used to read and parse every patch on disk to
3072
3131
  // work out which directory the file was under, on every single image request.
3132
+ if (!ValRouterCore.isSafePatchId(patchId) || !ValRouterCore.isMediaFilePath(filePath)) {
3133
+ return null;
3134
+ }
3073
3135
  const patchesDir = this.getPatchesDir();
3074
3136
  const absPath = this.wherePatchFileIs(patchBinaryFile(patchesDir, patchId, filePath), stagedPatchBinaryFile(patchesDir, patchId, filePath));
3075
3137
  if (absPath === null) {
@@ -3267,6 +3329,16 @@ class ValOpsFS extends ValRouterCore.ValOps {
3267
3329
  }] of localFileDescriptors) {
3268
3330
  const filePath = ref;
3269
3331
  const absPath = path__default["default"].join(this.rootDir, ...filePath.split("/"));
3332
+ // A publish writes uploaded files under /public and nowhere else.
3333
+ // `createPatch` refuses any other path, so this is for a patch that was
3334
+ // already on disk, or put there by hand.
3335
+ if (!ValRouterCore.isPublicFilePath(filePath) || !ValRouterCore.isSafePatchId(patchId)) {
3336
+ errors[absPath] = {
3337
+ message: `Not written: '${filePath}' is not under /public.`,
3338
+ filePath
3339
+ };
3340
+ continue;
3341
+ }
3270
3342
  try {
3271
3343
  this.host.copyFile(patchBinaryFile(this.getPatchesDir(), patchId, filePath), absPath);
3272
3344
  updatedFiles.push(absPath);
@@ -3317,6 +3389,9 @@ class ValOpsFS extends ValRouterCore.ValOps {
3317
3389
  async openBinaryFile(filePath, fromPatch) {
3318
3390
  let absPath;
3319
3391
  if (fromPatch) {
3392
+ if (!ValRouterCore.isSafePatchId(fromPatch.patchId) || !ValRouterCore.isMediaFilePath(filePath)) {
3393
+ return null;
3394
+ }
3320
3395
  const patchesDir = this.getPatchesDir();
3321
3396
  absPath = this.wherePatchFileIs(patchBinaryFile(patchesDir, fromPatch.patchId, filePath), stagedPatchBinaryFile(patchesDir, fromPatch.patchId, filePath));
3322
3397
  } else {
@@ -4989,7 +5064,7 @@ async function stagedModuleSources(files) {
4989
5064
  parseValFile,
4990
5065
  analyzeValModule,
4991
5066
  evaluateModuleSource
4992
- } = await Promise.resolve().then(function () { return require('./publishKit-26231426.cjs.prod.js'); });
5067
+ } = await Promise.resolve().then(function () { return require('./publishKit-e7f7db7c.cjs.prod.js'); });
4993
5068
  const sources = {};
4994
5069
  for (const {
4995
5070
  path,
@@ -14328,7 +14403,7 @@ commitPrepared,
14328
14403
  publishOverride) {
14329
14404
  var _opts$versions;
14330
14405
  const valServerConfig = await initHandlerOptions(route, opts, config);
14331
- return ValRouterCore.ValServer(valModules, {
14406
+ const server = ValRouterCore.ValServer(valModules, {
14332
14407
  formatter,
14333
14408
  commitPrepared,
14334
14409
  publishOverride,
@@ -14340,6 +14415,13 @@ publishOverride) {
14340
14415
  } : {}),
14341
14416
  ...valServerConfig
14342
14417
  }, callbacks, nodePlatform);
14418
+ // fs mode has no sign-in, so which requests it answers is decided here.
14419
+ ValRouterCore.setRequestGuard(server, {
14420
+ mode: valServerConfig.mode,
14421
+ production: "production" === "production",
14422
+ allowedHosts: ValRouterCore.parseAllowedHosts(process.env.VAL_ALLOWED_HOSTS)
14423
+ });
14424
+ return server;
14343
14425
  }
14344
14426
 
14345
14427
  /**