@valbuild/core 0.97.0 → 0.97.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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;
@@ -5110,149 +5116,158 @@ function modules(config, modules) {
5110
5116
  };
5111
5117
  }
5112
5118
 
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
- }
5119
+ function _regeneratorValues(e) {
5120
+ if (null != e) {
5121
+ var t = e["function" == typeof Symbol && Symbol.iterator || "@@iterator"],
5122
+ r = 0;
5123
+ if (t) return t.call(e);
5124
+ if ("function" == typeof e.next) return e;
5125
+ if (!isNaN(e.length)) return {
5126
+ next: function () {
5127
+ return e && r >= e.length && (e = void 0), {
5128
+ value: e && e[r++],
5129
+ done: !e
5130
+ };
5131
+ }
5132
+ };
5125
5133
  }
5126
- return {
5127
- url: src[FILE_REF_PROP],
5128
- metadata: src.metadata
5129
- };
5134
+ throw new TypeError(typeof e + " is not iterable");
5130
5135
  }
5131
5136
 
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;
5137
+ function _regeneratorDefine(e, r, n, t) {
5138
+ var i = Object.defineProperty;
5146
5139
  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);
5140
+ i({}, "", {});
5141
+ } catch (e) {
5142
+ i = 0;
5143
+ }
5144
+ _regeneratorDefine = function (e, r, n, t) {
5145
+ function o(r, n) {
5146
+ _regeneratorDefine(e, r, function (e) {
5147
+ return this._invoke(r, n, e);
5148
+ });
5149
+ }
5150
+ r ? i ? i(e, r, {
5151
+ value: n,
5152
+ enumerable: !t,
5153
+ configurable: !t,
5154
+ writable: !t
5155
+ }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
5156
+ }, _regeneratorDefine(e, r, n, t);
5157
+ }
5158
+
5159
+ function _regenerator() {
5160
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
5161
+ var e,
5162
+ t,
5163
+ r = "function" == typeof Symbol ? Symbol : {},
5164
+ n = r.iterator || "@@iterator",
5165
+ o = r.toStringTag || "@@toStringTag";
5166
+ function i(r, n, o, i) {
5167
+ var c = n && n.prototype instanceof Generator ? n : Generator,
5168
+ u = Object.create(c.prototype);
5169
+ return _regeneratorDefine(u, "_invoke", function (r, n, o) {
5170
+ var i,
5171
+ c,
5172
+ u,
5173
+ f = 0,
5174
+ p = o || [],
5175
+ y = !1,
5176
+ G = {
5177
+ p: 0,
5178
+ n: 0,
5179
+ v: e,
5180
+ a: d,
5181
+ f: d.bind(e, 4),
5182
+ d: function (t, r) {
5183
+ return i = t, c = 0, u = e, G.n = r, a;
5162
5184
  }
5163
- } catch (err) {
5164
- _iterator2.e(err);
5165
- } finally {
5166
- _iterator2.f();
5185
+ };
5186
+ function d(r, n) {
5187
+ for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
5188
+ var o,
5189
+ i = p[t],
5190
+ d = G.p,
5191
+ l = i[2];
5192
+ 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
5193
  }
5168
- break;
5169
- } else {
5170
- dereffedPath.push(segment);
5194
+ if (o || r > 1) return a;
5195
+ throw y = !0, n;
5171
5196
  }
5172
- }
5173
- } catch (err) {
5174
- _iterator.e(err);
5175
- } finally {
5176
- _iterator.f();
5197
+ return function (o, p, l) {
5198
+ if (f > 1) throw TypeError("Generator is already running");
5199
+ for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
5200
+ i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
5201
+ try {
5202
+ if (f = 2, i) {
5203
+ if (c || (o = "next"), t = i[o]) {
5204
+ if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
5205
+ if (!t.done) return t;
5206
+ u = t.value, c < 2 && (c = 0);
5207
+ } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
5208
+ i = e;
5209
+ } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
5210
+ } catch (t) {
5211
+ i = e, c = 1, u = t;
5212
+ } finally {
5213
+ f = 1;
5214
+ }
5215
+ }
5216
+ return {
5217
+ value: t,
5218
+ done: y
5219
+ };
5220
+ };
5221
+ }(r, o, i), !0), u;
5177
5222
  }
5178
- return ok([dereffedPath, referencedPath]);
5223
+ var a = {};
5224
+ function Generator() {}
5225
+ function GeneratorFunction() {}
5226
+ function GeneratorFunctionPrototype() {}
5227
+ t = Object.getPrototypeOf;
5228
+ var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
5229
+ return this;
5230
+ }), t),
5231
+ u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
5232
+ function f(e) {
5233
+ return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
5234
+ }
5235
+ 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 () {
5236
+ return this;
5237
+ }), _regeneratorDefine(u, "toString", function () {
5238
+ return "[object Generator]";
5239
+ }), (_regenerator = function () {
5240
+ return {
5241
+ w: i,
5242
+ m: f
5243
+ };
5244
+ })();
5179
5245
  }
5180
- function derefPatch(patch, document, ops) {
5181
- var fileUpdates = {};
5182
- var dereferencedPatch = [];
5183
- var _iterator3 = _createForOfIteratorHelper(patch),
5184
- _step3;
5246
+
5247
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
5185
5248
  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();
5249
+ var i = n[a](c),
5250
+ u = i.value;
5251
+ } catch (n) {
5252
+ return void e(n);
5251
5253
  }
5252
- return ok({
5253
- fileUpdates: fileUpdates,
5254
- dereferencedPatch: dereferencedPatch
5255
- });
5254
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
5255
+ }
5256
+ function _asyncToGenerator(n) {
5257
+ return function () {
5258
+ var t = this,
5259
+ e = arguments;
5260
+ return new Promise(function (r, o) {
5261
+ var a = n.apply(t, e);
5262
+ function _next(n) {
5263
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
5264
+ }
5265
+ function _throw(n) {
5266
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
5267
+ }
5268
+ _next(void 0);
5269
+ });
5270
+ };
5256
5271
  }
5257
5272
 
5258
5273
  /**
@@ -5588,6 +5603,352 @@ var getSHA256Hash = function getSHA256Hash(bits) {
5588
5603
  return createHash().update(bits).digest("hex");
5589
5604
  };
5590
5605
 
5606
+ // Lazily constructed: this module is also evaluated inside the QuickJS
5607
+ // sandbox (when user val modules import @valbuild/core), and that sandbox
5608
+ // has no `TextEncoder` global. `hash()` is never called from inside the
5609
+ // sandbox, so deferring construction avoids a ReferenceError at import time.
5610
+ var textEncoder;
5611
+ function getTextEncoder() {
5612
+ if (!textEncoder) {
5613
+ textEncoder = new TextEncoder();
5614
+ }
5615
+ return textEncoder;
5616
+ }
5617
+ function hash(input) {
5618
+ if (_typeof(input) === "object") {
5619
+ return hashObject(input);
5620
+ }
5621
+ return getSHA256Hash(getTextEncoder().encode(input));
5622
+ }
5623
+ function hashObject(obj) {
5624
+ var collector = [];
5625
+ collectObjectRecursive(obj, collector);
5626
+ return getSHA256Hash(getTextEncoder().encode(collector.join("")));
5627
+ }
5628
+ function collectObjectRecursive(item, collector) {
5629
+ if (typeof item === "string") {
5630
+ collector.push("\"", item, "\"");
5631
+ return;
5632
+ } else if (typeof item === "number") {
5633
+ collector.push(item.toString());
5634
+ return;
5635
+ } else if (_typeof(item) === "object") {
5636
+ if (Array.isArray(item)) {
5637
+ collector.push("[");
5638
+ for (var i = 0; i < item.length; i++) {
5639
+ collectObjectRecursive(item[i], collector);
5640
+ if (i !== item.length - 1) collector.push(",");
5641
+ }
5642
+ collector.push("]");
5643
+ } else {
5644
+ collector.push("{");
5645
+ var keys = Object.keys(item).sort();
5646
+ keys.forEach(function (key, i) {
5647
+ collector.push("\"".concat(key, "\":"));
5648
+ collectObjectRecursive(item[key], collector);
5649
+ if (i !== keys.length - 1) collector.push(",");
5650
+ });
5651
+ collector.push("}");
5652
+ }
5653
+ return;
5654
+ } else {
5655
+ console.warn("Unknown type encountered when hashing object", _typeof(item), item);
5656
+ }
5657
+ }
5658
+
5659
+ /**
5660
+ * Extracts schemas and sources from a ValModules registry and computes the
5661
+ * deterministic SHAs that the server and client both use to detect changes.
5662
+ *
5663
+ * Used by ValOps on the server and by ValSyncEngine on the client so the
5664
+ * hash algorithm has a single source of truth.
5665
+ */
5666
+ function extractValModules(_x) {
5667
+ return _extractValModules.apply(this, arguments);
5668
+ }
5669
+ function _extractValModules() {
5670
+ _extractValModules = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(valModules) {
5671
+ var moduleErrors, addModuleError, sources, schemas, serializedSchemas, configSha, sourcesSha, baseSha, schemaSha, _loop, _ret, moduleIdx;
5672
+ return _regenerator().w(function (_context2) {
5673
+ while (1) switch (_context2.n) {
5674
+ case 0:
5675
+ moduleErrors = [];
5676
+ addModuleError = function addModuleError(message, index, path) {
5677
+ moduleErrors[index] = {
5678
+ message: message,
5679
+ path: path
5680
+ };
5681
+ };
5682
+ sources = {};
5683
+ schemas = {};
5684
+ serializedSchemas = {};
5685
+ configSha = hash(JSON.stringify(valModules.config));
5686
+ sourcesSha = "";
5687
+ baseSha = configSha;
5688
+ schemaSha = configSha;
5689
+ _loop = /*#__PURE__*/_regenerator().m(function _loop(moduleIdx) {
5690
+ var module;
5691
+ return _regenerator().w(function (_context) {
5692
+ while (1) switch (_context.n) {
5693
+ case 0:
5694
+ module = valModules.modules[moduleIdx];
5695
+ if (module.def) {
5696
+ _context.n = 1;
5697
+ break;
5698
+ }
5699
+ addModuleError("val.modules is missing 'def' property", moduleIdx);
5700
+ return _context.a(2, 0);
5701
+ case 1:
5702
+ if (!(typeof module.def !== "function")) {
5703
+ _context.n = 2;
5704
+ break;
5705
+ }
5706
+ addModuleError("val.modules 'def' property is not a function", moduleIdx);
5707
+ return _context.a(2, 0);
5708
+ case 2:
5709
+ _context.n = 3;
5710
+ return module.def().then(function (value) {
5711
+ if (!value) {
5712
+ addModuleError("val.modules 'def' did not return a value", moduleIdx);
5713
+ return;
5714
+ }
5715
+ if (!value["default"]) {
5716
+ addModuleError("val.modules 'def' did not return a default export", moduleIdx);
5717
+ return;
5718
+ }
5719
+ var path = getValPath(value["default"]);
5720
+ if (path === undefined) {
5721
+ addModuleError("path is undefined", moduleIdx);
5722
+ return;
5723
+ }
5724
+ var schema = getSchema(value["default"]);
5725
+ if (schema === undefined) {
5726
+ addModuleError("schema in path '".concat(path, "' is undefined"), moduleIdx, path);
5727
+ return;
5728
+ }
5729
+ // Avoid `schema instanceof Schema` — the editor SPA and the host
5730
+ // Next.js bundle each ship their own copy of @valbuild/core, so the
5731
+ // `Schema` class identity differs between them and the instanceof
5732
+ // check would fail for cross-bundle modules. The executeSerialize
5733
+ // check below is the actual contract we depend on.
5734
+ if (typeof schema["executeSerialize"] !== "function") {
5735
+ addModuleError("schema.serialize in path '".concat(path, "' is not a function"), moduleIdx, path);
5736
+ return;
5737
+ }
5738
+ var source = getSource(value["default"]);
5739
+ if (source === undefined) {
5740
+ addModuleError("source in ".concat(path, " is undefined"), moduleIdx, path);
5741
+ return;
5742
+ }
5743
+ var serializedSchema;
5744
+ try {
5745
+ serializedSchema = schema["executeSerialize"]();
5746
+ } catch (e) {
5747
+ var message = e instanceof Error ? e.message : JSON.stringify(e);
5748
+ addModuleError("Could not serialize module: '".concat(path, "'. Error: ").concat(message), moduleIdx, path);
5749
+ return;
5750
+ }
5751
+ var pathM = path;
5752
+ sources[pathM] = source;
5753
+ schemas[pathM] = schema;
5754
+ serializedSchemas[pathM] = serializedSchema;
5755
+ sourcesSha = hash(sourcesSha + JSON.stringify({
5756
+ path: path,
5757
+ source: source
5758
+ }));
5759
+ baseSha = hash(baseSha + JSON.stringify({
5760
+ path: path,
5761
+ schema: serializedSchema,
5762
+ source: source,
5763
+ modulesErrors: moduleErrors
5764
+ }));
5765
+ schemaSha = hash(schemaSha + JSON.stringify(serializedSchema));
5766
+ });
5767
+ case 3:
5768
+ return _context.a(2);
5769
+ }
5770
+ }, _loop);
5771
+ });
5772
+ moduleIdx = 0;
5773
+ case 1:
5774
+ if (!(moduleIdx < valModules.modules.length)) {
5775
+ _context2.n = 4;
5776
+ break;
5777
+ }
5778
+ return _context2.d(_regeneratorValues(_loop(moduleIdx)), 2);
5779
+ case 2:
5780
+ _ret = _context2.v;
5781
+ if (!(_ret === 0)) {
5782
+ _context2.n = 3;
5783
+ break;
5784
+ }
5785
+ return _context2.a(3, 3);
5786
+ case 3:
5787
+ moduleIdx++;
5788
+ _context2.n = 1;
5789
+ break;
5790
+ case 4:
5791
+ return _context2.a(2, {
5792
+ sources: sources,
5793
+ schemas: schemas,
5794
+ serializedSchemas: serializedSchemas,
5795
+ baseSha: baseSha,
5796
+ schemaSha: schemaSha,
5797
+ sourcesSha: sourcesSha,
5798
+ configSha: configSha,
5799
+ moduleErrors: moduleErrors
5800
+ });
5801
+ }
5802
+ }, _callee);
5803
+ }));
5804
+ return _extractValModules.apply(this, arguments);
5805
+ }
5806
+
5807
+ var DEFAULT_VAL_REMOTE_HOST = "https://remote.val.build";
5808
+ function convertRemoteSource(src) {
5809
+ if (src !== null && src !== void 0 && src.patch_id) {
5810
+ var splitRemoteRefDataRes = splitRemoteRef(src[FILE_REF_PROP]);
5811
+ if (splitRemoteRefDataRes.status === "success") {
5812
+ return {
5813
+ url: "/api/val/files/" + splitRemoteRefDataRes.filePath + "?patch_id=".concat(src["patch_id"], "&remote=true&ref=").concat(encodeURIComponent(src[FILE_REF_PROP])),
5814
+ metadata: src.metadata
5815
+ };
5816
+ } else {
5817
+ 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);
5818
+ }
5819
+ }
5820
+ return {
5821
+ url: src[FILE_REF_PROP],
5822
+ metadata: src.metadata
5823
+ };
5824
+ }
5825
+
5826
+ var PatchError = /*#__PURE__*/_createClass(function PatchError(message) {
5827
+ _classCallCheck(this, PatchError);
5828
+ this.message = message;
5829
+ });
5830
+
5831
+ /**
5832
+ * NOTE: MAY mutate the input document.
5833
+ */
5834
+
5835
+ function derefPath(path) {
5836
+ var dereffedPath = [];
5837
+ var referencedPath = null;
5838
+ var _iterator = _createForOfIteratorHelper(path),
5839
+ _step;
5840
+ try {
5841
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
5842
+ var segment = _step.value;
5843
+ if (segment.startsWith("$")) {
5844
+ var dereffedSegment = segment.slice(1);
5845
+ dereffedPath.push(dereffedSegment);
5846
+ referencedPath = [];
5847
+ var _iterator2 = _createForOfIteratorHelper(path.slice(dereffedPath.length)),
5848
+ _step2;
5849
+ try {
5850
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
5851
+ var _segment = _step2.value;
5852
+ if (_segment.startsWith("$")) {
5853
+ return err(new PatchError("Cannot reference within reference: ".concat(_segment, ". Path: ").concat(path.join("/"))));
5854
+ }
5855
+ referencedPath.push(_segment);
5856
+ }
5857
+ } catch (err) {
5858
+ _iterator2.e(err);
5859
+ } finally {
5860
+ _iterator2.f();
5861
+ }
5862
+ break;
5863
+ } else {
5864
+ dereffedPath.push(segment);
5865
+ }
5866
+ }
5867
+ } catch (err) {
5868
+ _iterator.e(err);
5869
+ } finally {
5870
+ _iterator.f();
5871
+ }
5872
+ return ok([dereffedPath, referencedPath]);
5873
+ }
5874
+ function derefPatch(patch, document, ops) {
5875
+ var fileUpdates = {};
5876
+ var dereferencedPatch = [];
5877
+ var _iterator3 = _createForOfIteratorHelper(patch),
5878
+ _step3;
5879
+ try {
5880
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
5881
+ var op = _step3.value;
5882
+ if (op.op === "replace") {
5883
+ var maybeDerefRes = derefPath(op.path);
5884
+ if (isErr(maybeDerefRes)) {
5885
+ return maybeDerefRes;
5886
+ }
5887
+ var _maybeDerefRes$value = _slicedToArray(maybeDerefRes.value, 2),
5888
+ dereffedPath = _maybeDerefRes$value[0],
5889
+ referencedPath = _maybeDerefRes$value[1];
5890
+ if (referencedPath) {
5891
+ var maybeValue = ops.get(document, dereffedPath);
5892
+ if (isOk(maybeValue)) {
5893
+ var value = maybeValue.value;
5894
+ if (isFile(value)) {
5895
+ if (referencedPath.length > 0) {
5896
+ return err(new PatchError("Cannot sub-reference file reference at path: ".concat(dereffedPath.join("/"))));
5897
+ }
5898
+ if (typeof op.value !== "string") {
5899
+ return err(new PatchError("Expected base64 encoded string value for file reference, got ".concat(JSON.stringify(op.value))));
5900
+ }
5901
+ fileUpdates[value[FILE_REF_PROP]] = op.value;
5902
+ // } else if (isRemote(value)) {
5903
+ // if (!remotePatches[value[REMOTE_REF_PROP]]) {
5904
+ // remotePatches[value[REMOTE_REF_PROP]] = [];
5905
+ // }
5906
+ // remotePatches[value[REMOTE_REF_PROP]].push({
5907
+ // op: "replace",
5908
+ // path: referencedPath,
5909
+ // value: op.value,
5910
+ // });
5911
+ } else {
5912
+ return err(new PatchError("Unknown reference: ".concat(JSON.stringify(op), " at path: ").concat(dereffedPath.join("/"))));
5913
+ }
5914
+ } else {
5915
+ return maybeValue;
5916
+ }
5917
+ } else {
5918
+ dereferencedPatch.push(op);
5919
+ }
5920
+ } else if (op.op === "file") {
5921
+ if (!op.filePath.startsWith("/public")) {
5922
+ return err(new PatchError("Path must start with /public"));
5923
+ }
5924
+ if (typeof op.value !== "string") {
5925
+ return err(new PatchError("File operation must have a value that is typeof string. Found: ".concat(_typeof(op.value))));
5926
+ }
5927
+ fileUpdates[op.filePath] = op.value;
5928
+ } else {
5929
+ var _maybeDerefRes = derefPath(op.path);
5930
+ if (isErr(_maybeDerefRes)) {
5931
+ return _maybeDerefRes;
5932
+ }
5933
+ var _maybeDerefRes$value2 = _slicedToArray(_maybeDerefRes.value, 2),
5934
+ _referencedPath = _maybeDerefRes$value2[1];
5935
+ if (_referencedPath) {
5936
+ throw new Error("Unimplemented operation: ".concat(JSON.stringify(op)));
5937
+ }
5938
+ dereferencedPatch.push(op);
5939
+ }
5940
+ }
5941
+ } catch (err) {
5942
+ _iterator3.e(err);
5943
+ } finally {
5944
+ _iterator3.f();
5945
+ }
5946
+ return ok({
5947
+ fileUpdates: fileUpdates,
5948
+ dereferencedPatch: dereferencedPatch
5949
+ });
5950
+ }
5951
+
5591
5952
  var EXT_TO_MIME_TYPES = {
5592
5953
  x3d: "application/vnd.hzn-3d-crossword",
5593
5954
  "3gp": "video/3gpp",
@@ -6783,4 +7144,4 @@ function tryJsonParse(str) {
6783
7144
  }
6784
7145
  }
6785
7146
 
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 };
7147
+ 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 };