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