@valbuild/core 0.97.0 → 0.97.4

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.
@@ -274,23 +274,29 @@ function _inherits(t, e) {
274
274
  }), e && _setPrototypeOf(t, e);
275
275
  }
276
276
 
277
+ // Identity symbols are registered in the global Symbol registry so that
278
+ // multiple bundled copies of @valbuild/core (e.g. the editor SPA bundle vs.
279
+ // the host Next.js bundle) resolve to the same Symbol instance. Without
280
+ // this, a value produced by one copy reads as `undefined` when accessed
281
+ // via these keys from the other copy — extractValModules running in the
282
+ // SPA against `.val.ts` modules loaded from the host bundle was hitting
283
+ // this exact failure mode.
277
284
  /**
278
285
  * @internal
279
286
  */
280
- var GetSchema = Symbol("GetSchema");
281
- /**
287
+ var GetSchema = Symbol["for"]("@valbuild/core/GetSchema");
282
288
  /**
283
289
  * @internal
284
290
  */
285
- var Path = Symbol("Path");
291
+ var Path = Symbol["for"]("@valbuild/core/Path");
286
292
  /**
287
293
  * @internal
288
294
  */
289
- var GetSource = Symbol("GetSource");
295
+ var GetSource = Symbol["for"]("@valbuild/core/GetSource");
290
296
  /**
291
297
  * @internal
292
298
  */
293
- var ValError = Symbol("ValError");
299
+ var ValError = Symbol["for"]("@valbuild/core/ValError");
294
300
  var GenericSelector = /*#__PURE__*/_createClass(function GenericSelector(valOrExpr, path, schema, error) {
295
301
  _classCallCheck(this, GenericSelector);
296
302
  this[Path] = path;
@@ -2884,7 +2890,15 @@ function splitRemoteRef(ref) {
2884
2890
  error: "Invalid remote ref: " + ref
2885
2891
  };
2886
2892
  }
2887
- if (match[7].indexOf("public/val/") !== 0) {
2893
+ if (match[7].indexOf("public/") !== 0) {
2894
+ return {
2895
+ status: "error",
2896
+ error: "Invalid remote ref: " + ref
2897
+ };
2898
+ }
2899
+ if (match[7].split("/").some(function (segment) {
2900
+ return segment === "." || segment === "..";
2901
+ })) {
2888
2902
  return {
2889
2903
  status: "error",
2890
2904
  error: "Invalid remote ref: " + ref
@@ -3048,13 +3062,17 @@ var RecordSchema = /*#__PURE__*/function (_Schema) {
3048
3062
  // Should! never happen
3049
3063
  src);
3050
3064
  } else if (_this2.mediaOptions) {
3051
- // Media collection: validate key (path/URL) and entry (metadata)
3065
+ // Media collection: validate key (path/URL) and entry (metadata).
3066
+ // Gallery entries are keyed by their file path and the metadata is
3067
+ // derived, so surface entry errors on the key rather than the value.
3052
3068
  var keyErr = _this2.validateMediaKey(subPath, key);
3053
3069
  if (keyErr) {
3070
+ _this2.markKeyErrorsAtPath(keyErr, subPath);
3054
3071
  error = error ? _objectSpread2(_objectSpread2({}, error), keyErr) : keyErr;
3055
3072
  }
3056
3073
  var entryErr = _this2.validateMediaEntry(subPath, elem);
3057
3074
  if (entryErr) {
3075
+ _this2.markKeyErrorsAtPath(entryErr, subPath);
3058
3076
  error = error ? _objectSpread2(_objectSpread2({}, error), entryErr) : entryErr;
3059
3077
  }
3060
3078
  } else {
@@ -3073,6 +3091,19 @@ var RecordSchema = /*#__PURE__*/function (_Schema) {
3073
3091
  value: function isRemoteUrl(url) {
3074
3092
  return url.startsWith("https://") || url.startsWith("http://");
3075
3093
  }
3094
+
3095
+ /** Marks the validation errors reported at `path` as key errors (in place). */
3096
+ }, {
3097
+ key: "markKeyErrorsAtPath",
3098
+ value: function markKeyErrorsAtPath(errors, path) {
3099
+ if (errors && errors[path]) {
3100
+ errors[path] = errors[path].map(function (err) {
3101
+ return _objectSpread2(_objectSpread2({}, err), {}, {
3102
+ keyError: true
3103
+ });
3104
+ });
3105
+ }
3106
+ }
3076
3107
  }, {
3077
3108
  key: "validateMediaKey",
3078
3109
  value: function validateMediaKey(path, key) {
@@ -4897,6 +4928,9 @@ function router(router, item) {
4897
4928
  /**
4898
4929
  * Define a collection of images.
4899
4930
  *
4931
+ * All options are optional: `s.images()` accepts any image type (`"image/*"`) in
4932
+ * the default `/public/val` directory, with nullable alt text and remote disabled.
4933
+ *
4900
4934
  * @example
4901
4935
  * ```typescript
4902
4936
  * const schema = s.images({
@@ -4915,9 +4949,9 @@ function router(router, item) {
4915
4949
  * ```
4916
4950
  */
4917
4951
  var images = function images(options) {
4918
- var _options$directory, _options$alt, _options$remote;
4919
- var directory = (_options$directory = options.directory) !== null && _options$directory !== void 0 ? _options$directory : "/public/val";
4920
- var altSchema = (_options$alt = options.alt) !== null && _options$alt !== void 0 ? _options$alt : string().nullable();
4952
+ var _options$directory, _options$alt, _options$accept, _options$remote;
4953
+ var directory = (_options$directory = options === null || options === void 0 ? void 0 : options.directory) !== null && _options$directory !== void 0 ? _options$directory : "/public/val";
4954
+ var altSchema = (_options$alt = options === null || options === void 0 ? void 0 : options.alt) !== null && _options$alt !== void 0 ? _options$alt : string().nullable();
4921
4955
  var itemSchema = new ObjectSchema({
4922
4956
  width: new NumberSchema(undefined, false),
4923
4957
  height: new NumberSchema(undefined, false),
@@ -4926,9 +4960,9 @@ var images = function images(options) {
4926
4960
  }, false);
4927
4961
  return new RecordSchema(itemSchema, false, [], null, null, {
4928
4962
  type: "images",
4929
- accept: options.accept,
4963
+ accept: (_options$accept = options === null || options === void 0 ? void 0 : options.accept) !== null && _options$accept !== void 0 ? _options$accept : "image/*",
4930
4964
  directory: directory,
4931
- remote: (_options$remote = options.remote) !== null && _options$remote !== void 0 ? _options$remote : false,
4965
+ remote: (_options$remote = options === null || options === void 0 ? void 0 : options.remote) !== null && _options$remote !== void 0 ? _options$remote : false,
4932
4966
  altSchema: altSchema
4933
4967
  });
4934
4968
  };
@@ -5034,6 +5068,9 @@ var initRemote = function initRemote(config) {
5034
5068
  }
5035
5069
  return remote;
5036
5070
  };
5071
+
5072
+ // NOTE: the segments must match the ref built by createRemoteRef below and the RegEx in splitRemoteRef.
5073
+
5037
5074
  function createRemoteRef(remoteHost, _ref2) {
5038
5075
  var publicProjectId = _ref2.publicProjectId,
5039
5076
  coreVersion = _ref2.coreVersion,
@@ -5110,149 +5147,158 @@ function modules(config, modules) {
5110
5147
  };
5111
5148
  }
5112
5149
 
5113
- var DEFAULT_VAL_REMOTE_HOST = "https://remote.val.build";
5114
- function convertRemoteSource(src) {
5115
- if (src !== null && src !== void 0 && src.patch_id) {
5116
- var splitRemoteRefDataRes = splitRemoteRef(src[FILE_REF_PROP]);
5117
- if (splitRemoteRefDataRes.status === "success") {
5118
- return {
5119
- url: "/api/val/files/" + splitRemoteRefDataRes.filePath + "?patch_id=".concat(src["patch_id"], "&remote=true&ref=").concat(encodeURIComponent(src[FILE_REF_PROP])),
5120
- metadata: src.metadata
5121
- };
5122
- } else {
5123
- console.warn("Internal Val error: failed to split remote ref: ".concat(src[FILE_REF_PROP], ". The data format is different than what is expected. Check Val versions for mismatches."), splitRemoteRefDataRes.error);
5124
- }
5150
+ function _regeneratorValues(e) {
5151
+ if (null != e) {
5152
+ var t = e["function" == typeof Symbol && Symbol.iterator || "@@iterator"],
5153
+ r = 0;
5154
+ if (t) return t.call(e);
5155
+ if ("function" == typeof e.next) return e;
5156
+ if (!isNaN(e.length)) return {
5157
+ next: function () {
5158
+ return e && r >= e.length && (e = void 0), {
5159
+ value: e && e[r++],
5160
+ done: !e
5161
+ };
5162
+ }
5163
+ };
5125
5164
  }
5126
- return {
5127
- url: src[FILE_REF_PROP],
5128
- metadata: src.metadata
5129
- };
5165
+ throw new TypeError(typeof e + " is not iterable");
5130
5166
  }
5131
5167
 
5132
- var PatchError = /*#__PURE__*/_createClass(function PatchError(message) {
5133
- _classCallCheck(this, PatchError);
5134
- this.message = message;
5135
- });
5136
-
5137
- /**
5138
- * NOTE: MAY mutate the input document.
5139
- */
5140
-
5141
- function derefPath(path) {
5142
- var dereffedPath = [];
5143
- var referencedPath = null;
5144
- var _iterator = _createForOfIteratorHelper(path),
5145
- _step;
5168
+ function _regeneratorDefine(e, r, n, t) {
5169
+ var i = Object.defineProperty;
5146
5170
  try {
5147
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
5148
- var segment = _step.value;
5149
- if (segment.startsWith("$")) {
5150
- var dereffedSegment = segment.slice(1);
5151
- dereffedPath.push(dereffedSegment);
5152
- referencedPath = [];
5153
- var _iterator2 = _createForOfIteratorHelper(path.slice(dereffedPath.length)),
5154
- _step2;
5155
- try {
5156
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
5157
- var _segment = _step2.value;
5158
- if (_segment.startsWith("$")) {
5159
- return err(new PatchError("Cannot reference within reference: ".concat(_segment, ". Path: ").concat(path.join("/"))));
5160
- }
5161
- referencedPath.push(_segment);
5171
+ i({}, "", {});
5172
+ } catch (e) {
5173
+ i = 0;
5174
+ }
5175
+ _regeneratorDefine = function (e, r, n, t) {
5176
+ function o(r, n) {
5177
+ _regeneratorDefine(e, r, function (e) {
5178
+ return this._invoke(r, n, e);
5179
+ });
5180
+ }
5181
+ r ? i ? i(e, r, {
5182
+ value: n,
5183
+ enumerable: !t,
5184
+ configurable: !t,
5185
+ writable: !t
5186
+ }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
5187
+ }, _regeneratorDefine(e, r, n, t);
5188
+ }
5189
+
5190
+ function _regenerator() {
5191
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
5192
+ var e,
5193
+ t,
5194
+ r = "function" == typeof Symbol ? Symbol : {},
5195
+ n = r.iterator || "@@iterator",
5196
+ o = r.toStringTag || "@@toStringTag";
5197
+ function i(r, n, o, i) {
5198
+ var c = n && n.prototype instanceof Generator ? n : Generator,
5199
+ u = Object.create(c.prototype);
5200
+ return _regeneratorDefine(u, "_invoke", function (r, n, o) {
5201
+ var i,
5202
+ c,
5203
+ u,
5204
+ f = 0,
5205
+ p = o || [],
5206
+ y = !1,
5207
+ G = {
5208
+ p: 0,
5209
+ n: 0,
5210
+ v: e,
5211
+ a: d,
5212
+ f: d.bind(e, 4),
5213
+ d: function (t, r) {
5214
+ return i = t, c = 0, u = e, G.n = r, a;
5162
5215
  }
5163
- } catch (err) {
5164
- _iterator2.e(err);
5165
- } finally {
5166
- _iterator2.f();
5216
+ };
5217
+ function d(r, n) {
5218
+ for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
5219
+ var o,
5220
+ i = p[t],
5221
+ d = G.p,
5222
+ l = i[2];
5223
+ r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
5167
5224
  }
5168
- break;
5169
- } else {
5170
- dereffedPath.push(segment);
5225
+ if (o || r > 1) return a;
5226
+ throw y = !0, n;
5171
5227
  }
5172
- }
5173
- } catch (err) {
5174
- _iterator.e(err);
5175
- } finally {
5176
- _iterator.f();
5228
+ return function (o, p, l) {
5229
+ if (f > 1) throw TypeError("Generator is already running");
5230
+ for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
5231
+ i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
5232
+ try {
5233
+ if (f = 2, i) {
5234
+ if (c || (o = "next"), t = i[o]) {
5235
+ if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
5236
+ if (!t.done) return t;
5237
+ u = t.value, c < 2 && (c = 0);
5238
+ } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
5239
+ i = e;
5240
+ } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
5241
+ } catch (t) {
5242
+ i = e, c = 1, u = t;
5243
+ } finally {
5244
+ f = 1;
5245
+ }
5246
+ }
5247
+ return {
5248
+ value: t,
5249
+ done: y
5250
+ };
5251
+ };
5252
+ }(r, o, i), !0), u;
5177
5253
  }
5178
- return ok([dereffedPath, referencedPath]);
5254
+ var a = {};
5255
+ function Generator() {}
5256
+ function GeneratorFunction() {}
5257
+ function GeneratorFunctionPrototype() {}
5258
+ t = Object.getPrototypeOf;
5259
+ var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
5260
+ return this;
5261
+ }), t),
5262
+ u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
5263
+ function f(e) {
5264
+ return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
5265
+ }
5266
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
5267
+ return this;
5268
+ }), _regeneratorDefine(u, "toString", function () {
5269
+ return "[object Generator]";
5270
+ }), (_regenerator = function () {
5271
+ return {
5272
+ w: i,
5273
+ m: f
5274
+ };
5275
+ })();
5179
5276
  }
5180
- function derefPatch(patch, document, ops) {
5181
- var fileUpdates = {};
5182
- var dereferencedPatch = [];
5183
- var _iterator3 = _createForOfIteratorHelper(patch),
5184
- _step3;
5277
+
5278
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
5185
5279
  try {
5186
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
5187
- var op = _step3.value;
5188
- if (op.op === "replace") {
5189
- var maybeDerefRes = derefPath(op.path);
5190
- if (isErr(maybeDerefRes)) {
5191
- return maybeDerefRes;
5192
- }
5193
- var _maybeDerefRes$value = _slicedToArray(maybeDerefRes.value, 2),
5194
- dereffedPath = _maybeDerefRes$value[0],
5195
- referencedPath = _maybeDerefRes$value[1];
5196
- if (referencedPath) {
5197
- var maybeValue = ops.get(document, dereffedPath);
5198
- if (isOk(maybeValue)) {
5199
- var value = maybeValue.value;
5200
- if (isFile(value)) {
5201
- if (referencedPath.length > 0) {
5202
- return err(new PatchError("Cannot sub-reference file reference at path: ".concat(dereffedPath.join("/"))));
5203
- }
5204
- if (typeof op.value !== "string") {
5205
- return err(new PatchError("Expected base64 encoded string value for file reference, got ".concat(JSON.stringify(op.value))));
5206
- }
5207
- fileUpdates[value[FILE_REF_PROP]] = op.value;
5208
- // } else if (isRemote(value)) {
5209
- // if (!remotePatches[value[REMOTE_REF_PROP]]) {
5210
- // remotePatches[value[REMOTE_REF_PROP]] = [];
5211
- // }
5212
- // remotePatches[value[REMOTE_REF_PROP]].push({
5213
- // op: "replace",
5214
- // path: referencedPath,
5215
- // value: op.value,
5216
- // });
5217
- } else {
5218
- return err(new PatchError("Unknown reference: ".concat(JSON.stringify(op), " at path: ").concat(dereffedPath.join("/"))));
5219
- }
5220
- } else {
5221
- return maybeValue;
5222
- }
5223
- } else {
5224
- dereferencedPatch.push(op);
5225
- }
5226
- } else if (op.op === "file") {
5227
- if (!op.filePath.startsWith("/public")) {
5228
- return err(new PatchError("Path must start with /public"));
5229
- }
5230
- if (typeof op.value !== "string") {
5231
- return err(new PatchError("File operation must have a value that is typeof string. Found: ".concat(_typeof(op.value))));
5232
- }
5233
- fileUpdates[op.filePath] = op.value;
5234
- } else {
5235
- var _maybeDerefRes = derefPath(op.path);
5236
- if (isErr(_maybeDerefRes)) {
5237
- return _maybeDerefRes;
5238
- }
5239
- var _maybeDerefRes$value2 = _slicedToArray(_maybeDerefRes.value, 2),
5240
- _referencedPath = _maybeDerefRes$value2[1];
5241
- if (_referencedPath) {
5242
- throw new Error("Unimplemented operation: ".concat(JSON.stringify(op)));
5243
- }
5244
- dereferencedPatch.push(op);
5245
- }
5246
- }
5247
- } catch (err) {
5248
- _iterator3.e(err);
5249
- } finally {
5250
- _iterator3.f();
5280
+ var i = n[a](c),
5281
+ u = i.value;
5282
+ } catch (n) {
5283
+ return void e(n);
5251
5284
  }
5252
- return ok({
5253
- fileUpdates: fileUpdates,
5254
- dereferencedPatch: dereferencedPatch
5255
- });
5285
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
5286
+ }
5287
+ function _asyncToGenerator(n) {
5288
+ return function () {
5289
+ var t = this,
5290
+ e = arguments;
5291
+ return new Promise(function (r, o) {
5292
+ var a = n.apply(t, e);
5293
+ function _next(n) {
5294
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
5295
+ }
5296
+ function _throw(n) {
5297
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
5298
+ }
5299
+ _next(void 0);
5300
+ });
5301
+ };
5256
5302
  }
5257
5303
 
5258
5304
  /**
@@ -5588,6 +5634,352 @@ var getSHA256Hash = function getSHA256Hash(bits) {
5588
5634
  return createHash().update(bits).digest("hex");
5589
5635
  };
5590
5636
 
5637
+ // Lazily constructed: this module is also evaluated inside the QuickJS
5638
+ // sandbox (when user val modules import @valbuild/core), and that sandbox
5639
+ // has no `TextEncoder` global. `hash()` is never called from inside the
5640
+ // sandbox, so deferring construction avoids a ReferenceError at import time.
5641
+ var textEncoder;
5642
+ function getTextEncoder() {
5643
+ if (!textEncoder) {
5644
+ textEncoder = new TextEncoder();
5645
+ }
5646
+ return textEncoder;
5647
+ }
5648
+ function hash(input) {
5649
+ if (_typeof(input) === "object") {
5650
+ return hashObject(input);
5651
+ }
5652
+ return getSHA256Hash(getTextEncoder().encode(input));
5653
+ }
5654
+ function hashObject(obj) {
5655
+ var collector = [];
5656
+ collectObjectRecursive(obj, collector);
5657
+ return getSHA256Hash(getTextEncoder().encode(collector.join("")));
5658
+ }
5659
+ function collectObjectRecursive(item, collector) {
5660
+ if (typeof item === "string") {
5661
+ collector.push("\"", item, "\"");
5662
+ return;
5663
+ } else if (typeof item === "number") {
5664
+ collector.push(item.toString());
5665
+ return;
5666
+ } else if (_typeof(item) === "object") {
5667
+ if (Array.isArray(item)) {
5668
+ collector.push("[");
5669
+ for (var i = 0; i < item.length; i++) {
5670
+ collectObjectRecursive(item[i], collector);
5671
+ if (i !== item.length - 1) collector.push(",");
5672
+ }
5673
+ collector.push("]");
5674
+ } else {
5675
+ collector.push("{");
5676
+ var keys = Object.keys(item).sort();
5677
+ keys.forEach(function (key, i) {
5678
+ collector.push("\"".concat(key, "\":"));
5679
+ collectObjectRecursive(item[key], collector);
5680
+ if (i !== keys.length - 1) collector.push(",");
5681
+ });
5682
+ collector.push("}");
5683
+ }
5684
+ return;
5685
+ } else {
5686
+ console.warn("Unknown type encountered when hashing object", _typeof(item), item);
5687
+ }
5688
+ }
5689
+
5690
+ /**
5691
+ * Extracts schemas and sources from a ValModules registry and computes the
5692
+ * deterministic SHAs that the server and client both use to detect changes.
5693
+ *
5694
+ * Used by ValOps on the server and by ValSyncEngine on the client so the
5695
+ * hash algorithm has a single source of truth.
5696
+ */
5697
+ function extractValModules(_x) {
5698
+ return _extractValModules.apply(this, arguments);
5699
+ }
5700
+ function _extractValModules() {
5701
+ _extractValModules = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(valModules) {
5702
+ var moduleErrors, addModuleError, sources, schemas, serializedSchemas, configSha, sourcesSha, baseSha, schemaSha, _loop, _ret, moduleIdx;
5703
+ return _regenerator().w(function (_context2) {
5704
+ while (1) switch (_context2.n) {
5705
+ case 0:
5706
+ moduleErrors = [];
5707
+ addModuleError = function addModuleError(message, index, path) {
5708
+ moduleErrors[index] = {
5709
+ message: message,
5710
+ path: path
5711
+ };
5712
+ };
5713
+ sources = {};
5714
+ schemas = {};
5715
+ serializedSchemas = {};
5716
+ configSha = hash(JSON.stringify(valModules.config));
5717
+ sourcesSha = "";
5718
+ baseSha = configSha;
5719
+ schemaSha = configSha;
5720
+ _loop = /*#__PURE__*/_regenerator().m(function _loop(moduleIdx) {
5721
+ var module;
5722
+ return _regenerator().w(function (_context) {
5723
+ while (1) switch (_context.n) {
5724
+ case 0:
5725
+ module = valModules.modules[moduleIdx];
5726
+ if (module.def) {
5727
+ _context.n = 1;
5728
+ break;
5729
+ }
5730
+ addModuleError("val.modules is missing 'def' property", moduleIdx);
5731
+ return _context.a(2, 0);
5732
+ case 1:
5733
+ if (!(typeof module.def !== "function")) {
5734
+ _context.n = 2;
5735
+ break;
5736
+ }
5737
+ addModuleError("val.modules 'def' property is not a function", moduleIdx);
5738
+ return _context.a(2, 0);
5739
+ case 2:
5740
+ _context.n = 3;
5741
+ return module.def().then(function (value) {
5742
+ if (!value) {
5743
+ addModuleError("val.modules 'def' did not return a value", moduleIdx);
5744
+ return;
5745
+ }
5746
+ if (!value["default"]) {
5747
+ addModuleError("val.modules 'def' did not return a default export", moduleIdx);
5748
+ return;
5749
+ }
5750
+ var path = getValPath(value["default"]);
5751
+ if (path === undefined) {
5752
+ addModuleError("path is undefined", moduleIdx);
5753
+ return;
5754
+ }
5755
+ var schema = getSchema(value["default"]);
5756
+ if (schema === undefined) {
5757
+ addModuleError("schema in path '".concat(path, "' is undefined"), moduleIdx, path);
5758
+ return;
5759
+ }
5760
+ // Avoid `schema instanceof Schema` — the editor SPA and the host
5761
+ // Next.js bundle each ship their own copy of @valbuild/core, so the
5762
+ // `Schema` class identity differs between them and the instanceof
5763
+ // check would fail for cross-bundle modules. The executeSerialize
5764
+ // check below is the actual contract we depend on.
5765
+ if (typeof schema["executeSerialize"] !== "function") {
5766
+ addModuleError("schema.serialize in path '".concat(path, "' is not a function"), moduleIdx, path);
5767
+ return;
5768
+ }
5769
+ var source = getSource(value["default"]);
5770
+ if (source === undefined) {
5771
+ addModuleError("source in ".concat(path, " is undefined"), moduleIdx, path);
5772
+ return;
5773
+ }
5774
+ var serializedSchema;
5775
+ try {
5776
+ serializedSchema = schema["executeSerialize"]();
5777
+ } catch (e) {
5778
+ var message = e instanceof Error ? e.message : JSON.stringify(e);
5779
+ addModuleError("Could not serialize module: '".concat(path, "'. Error: ").concat(message), moduleIdx, path);
5780
+ return;
5781
+ }
5782
+ var pathM = path;
5783
+ sources[pathM] = source;
5784
+ schemas[pathM] = schema;
5785
+ serializedSchemas[pathM] = serializedSchema;
5786
+ sourcesSha = hash(sourcesSha + JSON.stringify({
5787
+ path: path,
5788
+ source: source
5789
+ }));
5790
+ baseSha = hash(baseSha + JSON.stringify({
5791
+ path: path,
5792
+ schema: serializedSchema,
5793
+ source: source,
5794
+ modulesErrors: moduleErrors
5795
+ }));
5796
+ schemaSha = hash(schemaSha + JSON.stringify(serializedSchema));
5797
+ });
5798
+ case 3:
5799
+ return _context.a(2);
5800
+ }
5801
+ }, _loop);
5802
+ });
5803
+ moduleIdx = 0;
5804
+ case 1:
5805
+ if (!(moduleIdx < valModules.modules.length)) {
5806
+ _context2.n = 4;
5807
+ break;
5808
+ }
5809
+ return _context2.d(_regeneratorValues(_loop(moduleIdx)), 2);
5810
+ case 2:
5811
+ _ret = _context2.v;
5812
+ if (!(_ret === 0)) {
5813
+ _context2.n = 3;
5814
+ break;
5815
+ }
5816
+ return _context2.a(3, 3);
5817
+ case 3:
5818
+ moduleIdx++;
5819
+ _context2.n = 1;
5820
+ break;
5821
+ case 4:
5822
+ return _context2.a(2, {
5823
+ sources: sources,
5824
+ schemas: schemas,
5825
+ serializedSchemas: serializedSchemas,
5826
+ baseSha: baseSha,
5827
+ schemaSha: schemaSha,
5828
+ sourcesSha: sourcesSha,
5829
+ configSha: configSha,
5830
+ moduleErrors: moduleErrors
5831
+ });
5832
+ }
5833
+ }, _callee);
5834
+ }));
5835
+ return _extractValModules.apply(this, arguments);
5836
+ }
5837
+
5838
+ var DEFAULT_VAL_REMOTE_HOST = "https://remote.val.build";
5839
+ function convertRemoteSource(src) {
5840
+ if (src !== null && src !== void 0 && src.patch_id) {
5841
+ var splitRemoteRefDataRes = splitRemoteRef(src[FILE_REF_PROP]);
5842
+ if (splitRemoteRefDataRes.status === "success") {
5843
+ return {
5844
+ url: "/api/val/files/" + splitRemoteRefDataRes.filePath + "?patch_id=".concat(src["patch_id"], "&remote=true&ref=").concat(encodeURIComponent(src[FILE_REF_PROP])),
5845
+ metadata: src.metadata
5846
+ };
5847
+ } else {
5848
+ console.warn("Internal Val error: failed to split remote ref: ".concat(src[FILE_REF_PROP], ". The data format is different than what is expected. Check Val versions for mismatches."), splitRemoteRefDataRes.error);
5849
+ }
5850
+ }
5851
+ return {
5852
+ url: src[FILE_REF_PROP],
5853
+ metadata: src.metadata
5854
+ };
5855
+ }
5856
+
5857
+ var PatchError = /*#__PURE__*/_createClass(function PatchError(message) {
5858
+ _classCallCheck(this, PatchError);
5859
+ this.message = message;
5860
+ });
5861
+
5862
+ /**
5863
+ * NOTE: MAY mutate the input document.
5864
+ */
5865
+
5866
+ function derefPath(path) {
5867
+ var dereffedPath = [];
5868
+ var referencedPath = null;
5869
+ var _iterator = _createForOfIteratorHelper(path),
5870
+ _step;
5871
+ try {
5872
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
5873
+ var segment = _step.value;
5874
+ if (segment.startsWith("$")) {
5875
+ var dereffedSegment = segment.slice(1);
5876
+ dereffedPath.push(dereffedSegment);
5877
+ referencedPath = [];
5878
+ var _iterator2 = _createForOfIteratorHelper(path.slice(dereffedPath.length)),
5879
+ _step2;
5880
+ try {
5881
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
5882
+ var _segment = _step2.value;
5883
+ if (_segment.startsWith("$")) {
5884
+ return err(new PatchError("Cannot reference within reference: ".concat(_segment, ". Path: ").concat(path.join("/"))));
5885
+ }
5886
+ referencedPath.push(_segment);
5887
+ }
5888
+ } catch (err) {
5889
+ _iterator2.e(err);
5890
+ } finally {
5891
+ _iterator2.f();
5892
+ }
5893
+ break;
5894
+ } else {
5895
+ dereffedPath.push(segment);
5896
+ }
5897
+ }
5898
+ } catch (err) {
5899
+ _iterator.e(err);
5900
+ } finally {
5901
+ _iterator.f();
5902
+ }
5903
+ return ok([dereffedPath, referencedPath]);
5904
+ }
5905
+ function derefPatch(patch, document, ops) {
5906
+ var fileUpdates = {};
5907
+ var dereferencedPatch = [];
5908
+ var _iterator3 = _createForOfIteratorHelper(patch),
5909
+ _step3;
5910
+ try {
5911
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
5912
+ var op = _step3.value;
5913
+ if (op.op === "replace") {
5914
+ var maybeDerefRes = derefPath(op.path);
5915
+ if (isErr(maybeDerefRes)) {
5916
+ return maybeDerefRes;
5917
+ }
5918
+ var _maybeDerefRes$value = _slicedToArray(maybeDerefRes.value, 2),
5919
+ dereffedPath = _maybeDerefRes$value[0],
5920
+ referencedPath = _maybeDerefRes$value[1];
5921
+ if (referencedPath) {
5922
+ var maybeValue = ops.get(document, dereffedPath);
5923
+ if (isOk(maybeValue)) {
5924
+ var value = maybeValue.value;
5925
+ if (isFile(value)) {
5926
+ if (referencedPath.length > 0) {
5927
+ return err(new PatchError("Cannot sub-reference file reference at path: ".concat(dereffedPath.join("/"))));
5928
+ }
5929
+ if (typeof op.value !== "string") {
5930
+ return err(new PatchError("Expected base64 encoded string value for file reference, got ".concat(JSON.stringify(op.value))));
5931
+ }
5932
+ fileUpdates[value[FILE_REF_PROP]] = op.value;
5933
+ // } else if (isRemote(value)) {
5934
+ // if (!remotePatches[value[REMOTE_REF_PROP]]) {
5935
+ // remotePatches[value[REMOTE_REF_PROP]] = [];
5936
+ // }
5937
+ // remotePatches[value[REMOTE_REF_PROP]].push({
5938
+ // op: "replace",
5939
+ // path: referencedPath,
5940
+ // value: op.value,
5941
+ // });
5942
+ } else {
5943
+ return err(new PatchError("Unknown reference: ".concat(JSON.stringify(op), " at path: ").concat(dereffedPath.join("/"))));
5944
+ }
5945
+ } else {
5946
+ return maybeValue;
5947
+ }
5948
+ } else {
5949
+ dereferencedPatch.push(op);
5950
+ }
5951
+ } else if (op.op === "file") {
5952
+ if (!op.filePath.startsWith("/public")) {
5953
+ return err(new PatchError("Path must start with /public"));
5954
+ }
5955
+ if (typeof op.value !== "string") {
5956
+ return err(new PatchError("File operation must have a value that is typeof string. Found: ".concat(_typeof(op.value))));
5957
+ }
5958
+ fileUpdates[op.filePath] = op.value;
5959
+ } else {
5960
+ var _maybeDerefRes = derefPath(op.path);
5961
+ if (isErr(_maybeDerefRes)) {
5962
+ return _maybeDerefRes;
5963
+ }
5964
+ var _maybeDerefRes$value2 = _slicedToArray(_maybeDerefRes.value, 2),
5965
+ _referencedPath = _maybeDerefRes$value2[1];
5966
+ if (_referencedPath) {
5967
+ throw new Error("Unimplemented operation: ".concat(JSON.stringify(op)));
5968
+ }
5969
+ dereferencedPatch.push(op);
5970
+ }
5971
+ }
5972
+ } catch (err) {
5973
+ _iterator3.e(err);
5974
+ } finally {
5975
+ _iterator3.f();
5976
+ }
5977
+ return ok({
5978
+ fileUpdates: fileUpdates,
5979
+ dereferencedPatch: dereferencedPatch
5980
+ });
5981
+ }
5982
+
5591
5983
  var EXT_TO_MIME_TYPES = {
5592
5984
  x3d: "application/vnd.hzn-3d-crossword",
5593
5985
  "3gp": "video/3gpp",
@@ -6783,4 +7175,4 @@ function tryJsonParse(str) {
6783
7175
  }
6784
7176
  }
6785
7177
 
6786
- export { ArraySchema as A, BooleanSchema as B, DEFAULT_CONTENT_HOST as D, FATAL_ERROR_TYPES as F, GenericSelector as G, Internal as I, KeyOfSchema as K, LiteralSchema as L, ModuleFilePathSep as M, NumberSchema as N, ObjectSchema as O, PatchError as P, RecordSchema as R, Schema as S, UnionSchema as U, VAL_EXTENSION as V, _typeof as _, _slicedToArray as a, _createClass as b, _classCallCheck as c, _toConsumableArray as d, DEFAULT_APP_HOST as e, DEFAULT_VAL_REMOTE_HOST as f, FILE_REF_PROP as g, FILE_REF_SUBTYPE_TAG as h, initVal as i, derefPatch as j, StringSchema as k, ImageSchema as l, modules as m, FileSchema as n, DateSchema as o, DateTimeSchema as p, RouteSchema as q, RichTextSchema as r, splitModuleFilePathAndModulePath as s, deserializeSchema as t, getSourcePathFromRoute as u };
7178
+ export { ArraySchema as A, BooleanSchema as B, DEFAULT_CONTENT_HOST as D, FATAL_ERROR_TYPES as F, GenericSelector as G, Internal as I, KeyOfSchema as K, LiteralSchema as L, ModuleFilePathSep as M, NumberSchema as N, ObjectSchema as O, PatchError as P, RecordSchema as R, Schema as S, UnionSchema as U, VAL_EXTENSION as V, _typeof as _, _slicedToArray as a, _createClass as b, _classCallCheck as c, _toConsumableArray as d, DEFAULT_APP_HOST as e, extractValModules as f, DEFAULT_VAL_REMOTE_HOST as g, FILE_REF_PROP as h, initVal as i, FILE_REF_SUBTYPE_TAG as j, derefPatch as k, StringSchema as l, modules as m, ImageSchema as n, FileSchema as o, DateSchema as p, DateTimeSchema as q, RouteSchema as r, splitModuleFilePathAndModulePath as s, RichTextSchema as t, deserializeSchema as u, getSourcePathFromRoute as v };