@oddington/sdk 0.1.82 → 0.1.84

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.
package/dist/browser.js CHANGED
@@ -2098,11 +2098,11 @@ var require_luxon = /* @__PURE__ */ __commonJS({
2098
2098
  static invalid(reason, explanation = null) {
2099
2099
  if (!reason)
2100
2100
  throw new InvalidArgumentError("need to specify a reason the Duration is invalid");
2101
- let invalid16 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
2101
+ let invalid18 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
2102
2102
  if (Settings.throwOnInvalid)
2103
- throw new InvalidDurationError(invalid16);
2103
+ throw new InvalidDurationError(invalid18);
2104
2104
  return new _Duration({
2105
- invalid: invalid16
2105
+ invalid: invalid18
2106
2106
  });
2107
2107
  }
2108
2108
  static normalizeUnit(unit) {
@@ -2369,11 +2369,11 @@ var require_luxon = /* @__PURE__ */ __commonJS({
2369
2369
  static invalid(reason, explanation = null) {
2370
2370
  if (!reason)
2371
2371
  throw new InvalidArgumentError("need to specify a reason the Interval is invalid");
2372
- let invalid16 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
2372
+ let invalid18 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
2373
2373
  if (Settings.throwOnInvalid)
2374
- throw new InvalidIntervalError(invalid16);
2374
+ throw new InvalidIntervalError(invalid18);
2375
2375
  return new _Interval({
2376
- invalid: invalid16
2376
+ invalid: invalid18
2377
2377
  });
2378
2378
  }
2379
2379
  static fromDateTimes(start, end) {
@@ -3230,9 +3230,9 @@ var require_luxon = /* @__PURE__ */ __commonJS({
3230
3230
  else {
3231
3231
  for (let u of orderedUnits)
3232
3232
  isUndefined(obj[u]) && (obj[u] = defaultUnitValues[u]);
3233
- let invalid16 = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
3234
- if (invalid16)
3235
- return DateTime.invalid(invalid16);
3233
+ let invalid18 = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
3234
+ if (invalid18)
3235
+ return DateTime.invalid(invalid18);
3236
3236
  let offsetProvis = guessOffsetForZone(zone);
3237
3237
  [ts, o] = objToTS(obj, offsetProvis, zone);
3238
3238
  }
@@ -3260,17 +3260,17 @@ var require_luxon = /* @__PURE__ */ __commonJS({
3260
3260
  }
3261
3261
  var zoneOffsetTs, zoneOffsetGuessCache = /* @__PURE__ */ new Map(), DateTime = class _DateTime {
3262
3262
  constructor(config) {
3263
- let zone = config.zone || Settings.defaultZone, invalid16 = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (zone.isValid ? null : unsupportedZone(zone));
3263
+ let zone = config.zone || Settings.defaultZone, invalid18 = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (zone.isValid ? null : unsupportedZone(zone));
3264
3264
  this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;
3265
3265
  let c = null, o = null;
3266
- if (!invalid16)
3266
+ if (!invalid18)
3267
3267
  if (config.old && config.old.ts === this.ts && config.old.zone.equals(zone))
3268
3268
  [c, o] = [config.old.c, config.old.o];
3269
3269
  else {
3270
3270
  let ot = isNumber(config.o) && !config.old ? config.o : zone.offset(this.ts);
3271
- c = tsToObj(this.ts, ot), invalid16 = Number.isNaN(c.year) ? new Invalid("invalid input") : null, c = invalid16 ? null : c, o = invalid16 ? null : ot;
3271
+ c = tsToObj(this.ts, ot), invalid18 = Number.isNaN(c.year) ? new Invalid("invalid input") : null, c = invalid18 ? null : c, o = invalid18 ? null : ot;
3272
3272
  }
3273
- this._zone = zone, this.loc = config.loc || Locale.create(), this.invalid = invalid16, this.weekData = null, this.localWeekData = null, this.c = c, this.o = o, this.isLuxonDateTime = !0;
3273
+ this._zone = zone, this.loc = config.loc || Locale.create(), this.invalid = invalid18, this.weekData = null, this.localWeekData = null, this.c = c, this.o = o, this.isLuxonDateTime = !0;
3274
3274
  }
3275
3275
  // CONSTRUCT
3276
3276
  static now() {
@@ -3349,9 +3349,9 @@ var require_luxon = /* @__PURE__ */ __commonJS({
3349
3349
  let v = normalized[u];
3350
3350
  isUndefined(v) ? foundFirst ? normalized[u] = defaultValues[u] : normalized[u] = objNow[u] : foundFirst = !0;
3351
3351
  }
3352
- let higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid16 = higherOrderInvalid || hasInvalidTimeData(normalized);
3353
- if (invalid16)
3354
- return _DateTime.invalid(invalid16);
3352
+ let higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid18 = higherOrderInvalid || hasInvalidTimeData(normalized);
3353
+ if (invalid18)
3354
+ return _DateTime.invalid(invalid18);
3355
3355
  let gregorian = useWeekData ? weekToGregorian(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse), inst = new _DateTime({
3356
3356
  ts: tsFinal,
3357
3357
  zone: zoneToUse,
@@ -3382,8 +3382,8 @@ var require_luxon = /* @__PURE__ */ __commonJS({
3382
3382
  locale,
3383
3383
  numberingSystem,
3384
3384
  defaultToEN: !0
3385
- }), [vals, parsedZone, specificOffset, invalid16] = parseFromTokens(localeToUse, text5, fmt);
3386
- return invalid16 ? _DateTime.invalid(invalid16) : parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text5, specificOffset);
3385
+ }), [vals, parsedZone, specificOffset, invalid18] = parseFromTokens(localeToUse, text5, fmt);
3386
+ return invalid18 ? _DateTime.invalid(invalid18) : parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text5, specificOffset);
3387
3387
  }
3388
3388
  static fromString(text5, fmt, opts = {}) {
3389
3389
  return _DateTime.fromFormat(text5, fmt, opts);
@@ -3395,11 +3395,11 @@ var require_luxon = /* @__PURE__ */ __commonJS({
3395
3395
  static invalid(reason, explanation = null) {
3396
3396
  if (!reason)
3397
3397
  throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");
3398
- let invalid16 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
3398
+ let invalid18 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
3399
3399
  if (Settings.throwOnInvalid)
3400
- throw new InvalidDateTimeError(invalid16);
3400
+ throw new InvalidDateTimeError(invalid18);
3401
3401
  return new _DateTime({
3402
- invalid: invalid16
3402
+ invalid: invalid18
3403
3403
  });
3404
3404
  }
3405
3405
  static isDateTime(o) {
@@ -5049,40 +5049,40 @@ var FileOperationError = class extends Error {
5049
5049
  };
5050
5050
  var FILE_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, FILE_ORIGINAL_MAX_BYTES = 5 * 1024 ** 3;
5051
5051
  function parseFileDescriptor(value) {
5052
- let invalid16 = () => {
5052
+ let invalid18 = () => {
5053
5053
  throw new FileOperationError("unavailable", 503, !0);
5054
5054
  };
5055
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid16();
5055
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
5056
5056
  let f = value;
5057
- if (Object.keys(f).sort().join(",") !== "enrichments,id,mediaType,name,path,sha256,size" || typeof f.id != "string" || !FILE_ID_PATTERN.test(f.id) || !safeFileName(f.name) || !safeFilePath(f.path) || !Number.isSafeInteger(f.size) || f.size < 0 || f.size > FILE_ORIGINAL_MAX_BYTES || typeof f.sha256 != "string" || !/^[0-9a-f]{64}$/.test(f.sha256) || !f.enrichments || typeof f.enrichments != "object" || Array.isArray(f.enrichments) || !isCanonicalOriginalMediaType(f.mediaType)) return invalid16();
5057
+ if (Object.keys(f).sort().join(",") !== "enrichments,id,mediaType,name,path,sha256,size" || typeof f.id != "string" || !FILE_ID_PATTERN.test(f.id) || !safeFileName(f.name) || !safeFilePath(f.path) || !Number.isSafeInteger(f.size) || f.size < 0 || f.size > FILE_ORIGINAL_MAX_BYTES || typeof f.sha256 != "string" || !/^[0-9a-f]{64}$/.test(f.sha256) || !f.enrichments || typeof f.enrichments != "object" || Array.isArray(f.enrichments) || !isCanonicalOriginalMediaType(f.mediaType)) return invalid18();
5058
5058
  for (let [name4, descriptor] of Object.entries(f.enrichments)) {
5059
- if (!safeEnrichmentName(name4)) return invalid16();
5059
+ if (!safeEnrichmentName(name4)) return invalid18();
5060
5060
  parseEnrichmentDescriptor(descriptor);
5061
5061
  }
5062
- return new TextEncoder().encode(JSON.stringify(f)).byteLength > 16 * 1024 ? invalid16() : f;
5062
+ return new TextEncoder().encode(JSON.stringify(f)).byteLength > 16 * 1024 ? invalid18() : f;
5063
5063
  }
5064
5064
  function parseEnrichmentDescriptor(value) {
5065
- let invalid16 = () => {
5065
+ let invalid18 = () => {
5066
5066
  throw new FileOperationError("unavailable", 503, !0);
5067
5067
  };
5068
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid16();
5068
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
5069
5069
  let d = value;
5070
- return Object.keys(d).sort().join(",") !== "mediaType,sha256,size" || !["application/octet-stream", "text/plain", "text/markdown", "application/json"].includes(d.mediaType) || !Number.isSafeInteger(d.size) || d.size < 0 || d.size > 16 * 1024 * 1024 || typeof d.sha256 != "string" || !/^[0-9a-f]{64}$/.test(d.sha256) ? invalid16() : d;
5070
+ return Object.keys(d).sort().join(",") !== "mediaType,sha256,size" || !["application/octet-stream", "text/plain", "text/markdown", "application/json"].includes(d.mediaType) || !Number.isSafeInteger(d.size) || d.size < 0 || d.size > 16 * 1024 * 1024 || typeof d.sha256 != "string" || !/^[0-9a-f]{64}$/.test(d.sha256) ? invalid18() : d;
5071
5071
  }
5072
5072
  function safeEnrichmentName(value) {
5073
5073
  return safeFileName(value) && !/^original(?:\.|$)/i.test(value);
5074
5074
  }
5075
5075
  function parseFileEnrichMetadata(value, maxBytes) {
5076
- let invalid16 = (reason = "invalid_metadata") => {
5076
+ let invalid18 = (reason = "invalid_metadata") => {
5077
5077
  throw new FileOperationError("invalid_input", 400, !1, { reason });
5078
5078
  };
5079
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid16();
5079
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
5080
5080
  let d = value;
5081
- if (Object.keys(d).some((key) => !["name", "size", "mediaType", "replace"].includes(key))) return invalid16();
5082
- if (!safeEnrichmentName(d.name)) return invalid16("invalid_enrichment_name");
5083
- if (!Number.isSafeInteger(d.size) || d.size < 0) return invalid16("invalid_size");
5084
- if (d.mediaType !== void 0 && (typeof d.mediaType != "string" || d.mediaType.length > 255 || /[\u0000-\u001f\u007f]/.test(d.mediaType))) return invalid16("invalid_media_type");
5085
- if (d.replace !== void 0 && (typeof d.replace != "string" || !/^[0-9a-f]{64}$/.test(d.replace))) return invalid16("invalid_replacement");
5081
+ if (Object.keys(d).some((key) => !["name", "size", "mediaType", "replace"].includes(key))) return invalid18();
5082
+ if (!safeEnrichmentName(d.name)) return invalid18("invalid_enrichment_name");
5083
+ if (!Number.isSafeInteger(d.size) || d.size < 0) return invalid18("invalid_size");
5084
+ if (d.mediaType !== void 0 && (typeof d.mediaType != "string" || d.mediaType.length > 255 || /[\u0000-\u001f\u007f]/.test(d.mediaType))) return invalid18("invalid_media_type");
5085
+ if (d.replace !== void 0 && (typeof d.replace != "string" || !/^[0-9a-f]{64}$/.test(d.replace))) return invalid18("invalid_replacement");
5086
5086
  if (d.size > maxBytes) throw new FileOperationError(
5087
5087
  "request_too_large",
5088
5088
  413,
@@ -5115,42 +5115,42 @@ function isCanonicalOriginalMediaType(value) {
5115
5115
  }
5116
5116
  }
5117
5117
  function parseFileUpdate(value) {
5118
- let invalid16 = (reason = "invalid_metadata") => {
5118
+ let invalid18 = (reason = "invalid_metadata") => {
5119
5119
  throw new FileOperationError("invalid_input", 400, !1, { reason });
5120
5120
  };
5121
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid16();
5121
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
5122
5122
  let input = value, update = {};
5123
- if (!Object.keys(input).length || Object.keys(input).some((key) => !["name", "path", "mediaType"].includes(key))) return invalid16();
5123
+ if (!Object.keys(input).length || Object.keys(input).some((key) => !["name", "path", "mediaType"].includes(key))) return invalid18();
5124
5124
  if (Object.hasOwn(input, "name")) {
5125
- if (!safeFileName(input.name)) return invalid16("invalid_name");
5125
+ if (!safeFileName(input.name)) return invalid18("invalid_name");
5126
5126
  update.name = input.name;
5127
5127
  }
5128
5128
  if (Object.hasOwn(input, "path")) {
5129
- if (!safeManagedFilePath(input.path)) return invalid16("invalid_path");
5129
+ if (!safeManagedFilePath(input.path)) return invalid18("invalid_path");
5130
5130
  update.path = input.path;
5131
5131
  }
5132
5132
  return Object.hasOwn(input, "mediaType") && (update.mediaType = declaredOriginalMediaType(input.mediaType)), update;
5133
5133
  }
5134
5134
  function parseFileCreateMetadata(value, maxBytes) {
5135
- let invalid16 = (reason = "invalid_metadata") => {
5135
+ let invalid18 = (reason = "invalid_metadata") => {
5136
5136
  throw new FileOperationError("invalid_input", 400, !1, { reason });
5137
5137
  };
5138
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid16();
5138
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
5139
5139
  let input = value;
5140
- if (Object.keys(input).some((key) => !["name", "path", "storage", "mediaType", "size", "requestKey"].includes(key))) return invalid16();
5140
+ if (Object.keys(input).some((key) => !["name", "path", "storage", "mediaType", "size", "requestKey"].includes(key))) return invalid18();
5141
5141
  let path = input.path === void 0 ? "Files" : input.path;
5142
- if (!safeFileName(input.name)) return invalid16("invalid_name");
5143
- if (!safeManagedFilePath(path)) return invalid16("invalid_path");
5144
- if (input.storage !== void 0 && input.storage !== "remote" && input.storage !== "local") return invalid16("invalid_storage");
5142
+ if (!safeFileName(input.name)) return invalid18("invalid_name");
5143
+ if (!safeManagedFilePath(path)) return invalid18("invalid_path");
5144
+ if (input.storage !== void 0 && input.storage !== "remote" && input.storage !== "local") return invalid18("invalid_storage");
5145
5145
  let mediaType = input.mediaType === void 0 ? "application/octet-stream" : declaredOriginalMediaType(input.mediaType);
5146
- if (!Number.isSafeInteger(input.size) || input.size < 0) return invalid16("invalid_size");
5146
+ if (!Number.isSafeInteger(input.size) || input.size < 0) return invalid18("invalid_size");
5147
5147
  if (input.size > maxBytes) throw new FileOperationError(
5148
5148
  "request_too_large",
5149
5149
  413,
5150
5150
  !1,
5151
5151
  { reason: "size_limit", limitBytes: maxBytes, receivedBytes: input.size }
5152
5152
  );
5153
- return typeof input.requestKey != "string" || input.requestKey.length < 1 || input.requestKey.length > 256 || input.requestKey !== input.requestKey.trim() || /[\u0000-\u001f\u007f]/.test(input.requestKey) ? invalid16("invalid_request_key") : {
5153
+ return typeof input.requestKey != "string" || input.requestKey.length < 1 || input.requestKey.length > 256 || input.requestKey !== input.requestKey.trim() || /[\u0000-\u001f\u007f]/.test(input.requestKey) ? invalid18("invalid_request_key") : {
5154
5154
  name: input.name,
5155
5155
  path,
5156
5156
  ...input.storage ? { storage: input.storage } : {},
@@ -5440,6 +5440,46 @@ function validateResponseDefinition(value) {
5440
5440
  let definition = object(value, "response definition");
5441
5441
  return Object.hasOwn(definition, "options") ? (keys(definition, ["type", "options"], "response definition"), definition.type !== "selection" && fail("Expected a selection definition"), { type: "selection", options: selectionOptions(definition.options, !1) }) : validateLegacyResponseDefinition(definition);
5442
5442
  }
5443
+ function validatePublishedSelectionDefinition(value) {
5444
+ let definition = object(value, "response definition");
5445
+ return keys(definition, ["type", "options"], "response definition"), definition.type !== "selection" && fail("Expected a selection definition"), { type: "selection", options: selectionOptions(definition.options, !0) };
5446
+ }
5447
+ function validatePublishedResponseDefinition(value) {
5448
+ let definition = object(value, "response definition");
5449
+ return Object.hasOwn(definition, "options") ? validatePublishedSelectionDefinition(definition) : validateLegacyResponseDefinition(definition);
5450
+ }
5451
+ function selectionResponse(saved, value) {
5452
+ let response2 = object(value, "response");
5453
+ keys(response2, ["option", "value", "note"], "response");
5454
+ let number = natural(response2.option, "option number", 1), option = saved.options[number - 1];
5455
+ option || fail("Option was not published");
5456
+ let answer;
5457
+ switch (option.type) {
5458
+ case "choice":
5459
+ answer = id(response2.value, "choice value"), answer !== option.value && fail("Choice does not match published option");
5460
+ break;
5461
+ case "record":
5462
+ answer = validateRecordReference(response2.value), (answer.repository !== option.value.repository || answer.ref !== option.value.ref) && fail("Record does not match published option");
5463
+ break;
5464
+ case "record-picker":
5465
+ answer = validateRecordReference(response2.value), (answer.repository !== option.source.collection.repository || option.source.refPrefix && !answer.ref.startsWith(option.source.refPrefix)) && fail("Record does not match picker source");
5466
+ break;
5467
+ }
5468
+ return option.type === "choice" && option.note ? { option: number, value: answer, note: text(response2.note, "required note").trim() } : (Object.hasOwn(response2, "note") && fail("This option does not accept a note"), { option: number, value: answer });
5469
+ }
5470
+ function validateResponse(definition, value) {
5471
+ let saved = validatePublishedResponseDefinition(definition);
5472
+ if ("options" in saved) return selectionResponse(saved, value);
5473
+ let response2 = object(value, "response");
5474
+ if (saved.source.type === "records") {
5475
+ keys(response2, ["selection"], "response");
5476
+ let record4 = validateRecordReference(response2.selection);
5477
+ return record4.repository !== saved.source.collection.repository && fail("Record belongs to another repository"), { selection: record4 };
5478
+ }
5479
+ keys(response2, ["selection", "note"], "response");
5480
+ let choice = id(response2.selection, "response selection"), option = saved.source.options.find((option2) => option2.value === choice);
5481
+ return option || fail("Choice was not published"), option.note ? { selection: choice, note: text(response2.note, "required note").trim() } : (Object.hasOwn(response2, "note") && fail("This choice does not accept a note"), { selection: choice });
5482
+ }
5443
5483
  function handlerReference(value) {
5444
5484
  let source2 = object(value, "handler reference");
5445
5485
  return keys(source2, ["id", "input"], "handler reference"), { id: id(source2.id, "handler ID"), input: serializable(source2.input) };
@@ -5548,6 +5588,60 @@ function publicationRequestKey(value) {
5548
5588
  let options = object(value, "publication options");
5549
5589
  return keys(options, ["requestKey"], "publication options"), id(options.requestKey, "publication request key");
5550
5590
  }
5591
+ function askPublicationOptions(value) {
5592
+ let options = object(value, "publication options");
5593
+ return keys(options, ["requestKey", "wait"], "publication options"), options.wait !== void 0 && typeof options.wait != "boolean" && fail("publication wait must be a boolean"), { requestKey: id(options.requestKey, "publication request key"), wait: options.wait === !0 };
5594
+ }
5595
+ function resolvedAskAnswer(question2, value) {
5596
+ let answer = object(value, `answer ${question2.id}`);
5597
+ if (answer.answered === !1)
5598
+ return keys(answer, ["answered"], `answer ${question2.id}`), { answered: !1 };
5599
+ if (answer.answered !== !0 && fail(`answer ${question2.id} requires answered`), "options" in question2.response) {
5600
+ keys(answer, ["answered", "option", "value", "note"], `answer ${question2.id}`);
5601
+ let definition = { type: "selection", options: question2.response.options.map((option, index) => ({
5602
+ ...option,
5603
+ id: index + 1
5604
+ })) }, response3 = validateResponse(definition, {
5605
+ option: answer.option,
5606
+ value: answer.value,
5607
+ ...Object.hasOwn(answer, "note") ? { note: answer.note } : {}
5608
+ });
5609
+ return "option" in response3 || fail(`answer ${question2.id} must use a numbered selection`), {
5610
+ answered: !0,
5611
+ option: response3.option,
5612
+ value: response3.value,
5613
+ ...response3.note === void 0 ? {} : { note: response3.note }
5614
+ };
5615
+ }
5616
+ keys(answer, ["answered", "value", "note"], `answer ${question2.id}`);
5617
+ let response2 = validateResponse(question2.response, {
5618
+ selection: answer.value,
5619
+ ...Object.hasOwn(answer, "note") ? { note: answer.note } : {}
5620
+ });
5621
+ return "selection" in response2 || fail(`answer ${question2.id} must use a source selection`), {
5622
+ answered: !0,
5623
+ value: response2.selection,
5624
+ ...response2.note === void 0 ? {} : { note: response2.note }
5625
+ };
5626
+ }
5627
+ function validateResolvedAsk(value, publication) {
5628
+ let source2 = object(value, "resolved Ask");
5629
+ keys(source2, ["id", "number", "revision", "title", "outcome", "answers"], "resolved Ask");
5630
+ let answers = object(source2.answers, "resolved Ask answers");
5631
+ keys(answers, publication.questions.map((question2) => question2.id), "resolved Ask answers");
5632
+ let retained = Object.fromEntries(publication.questions.map((question2) => [
5633
+ question2.id,
5634
+ resolvedAskAnswer(question2, answers[question2.id])
5635
+ ]));
5636
+ return {
5637
+ id: id(source2.id, "resolved Ask ID"),
5638
+ number: natural(source2.number, "resolved Ask number", 1),
5639
+ revision: natural(source2.revision, "resolved Ask revision", 1),
5640
+ title: text(source2.title, "resolved Ask title"),
5641
+ outcome: text(source2.outcome, "resolved Ask outcome"),
5642
+ answers: retained
5643
+ };
5644
+ }
5551
5645
  function digestPublicationRequest(value, options) {
5552
5646
  let source2 = object(value, "digest");
5553
5647
  return keys(source2, ["title", "description", "recipients", "views", "body", "notifyImmediately"], "digest"), {
@@ -5556,16 +5650,23 @@ function digestPublicationRequest(value, options) {
5556
5650
  };
5557
5651
  }
5558
5652
  function createInboxPublisher(transport) {
5653
+ async function publishAsk(value, options) {
5654
+ let source2 = object(value, "ask");
5655
+ keys(source2, ["title", "description", "recipients", "views", "body", "questions", "notifyImmediately", "tags", "recordRefs"], "ask");
5656
+ let publication = enforcePublicationSize(validatePublication({ ...source2, kind: "ask" }));
5657
+ publication.kind !== "ask" && fail("Expected an Ask publication");
5658
+ let boundedOptions = askPublicationOptions(options);
5659
+ if (boundedOptions.wait)
5660
+ return publication.questions.some((question2) => question2.handler) || fail("A waiting Ask requires a handler-backed Question"), transport.wait || fail("Waiting Ask publication requires a hosted queue-origin processing Run"), validateResolvedAsk(await transport.wait({
5661
+ requestKey: boundedOptions.requestKey,
5662
+ wait: !0,
5663
+ item: publication
5664
+ }), publication);
5665
+ let result2 = await transport.publish({ requestKey: boundedOptions.requestKey, item: publication });
5666
+ return id(result2.id, "published ask ID"), (!("revision" in result2) || !Number.isSafeInteger(result2.revision) || result2.revision !== 1) && fail("Initial ask publication must return revision 1"), { id: result2.id, revision: result2.revision };
5667
+ }
5559
5668
  return {
5560
- async publishAsk(value, options) {
5561
- let source2 = object(value, "ask");
5562
- keys(source2, ["title", "description", "recipients", "views", "body", "questions", "notifyImmediately", "tags", "recordRefs"], "ask");
5563
- let result2 = await transport.publish({
5564
- requestKey: publicationRequestKey(options),
5565
- item: enforcePublicationSize(validatePublication({ ...source2, kind: "ask" }))
5566
- });
5567
- return id(result2.id, "published ask ID"), (!("revision" in result2) || !Number.isSafeInteger(result2.revision) || result2.revision !== 1) && fail("Initial ask publication must return revision 1"), { id: result2.id, revision: result2.revision };
5568
- },
5669
+ publishAsk,
5569
5670
  async publishDigest(value, options) {
5570
5671
  let result2 = await transport.publish(digestPublicationRequest(value, options));
5571
5672
  return { id: id(result2.id, "published digest ID") };
@@ -6265,14 +6366,14 @@ var AIError = class extends Error {
6265
6366
  code;
6266
6367
  detail;
6267
6368
  };
6268
- function capture(value, invalid16, oversized, limit = ROUTINE_AI_VALUE_BYTES) {
6369
+ function capture(value, invalid18, oversized, limit = ROUTINE_AI_VALUE_BYTES) {
6269
6370
  try {
6270
6371
  assertRoutineJson(value);
6271
6372
  let encoded = JSON.stringify(value);
6272
6373
  if (new TextEncoder().encode(encoded).byteLength > limit) throw new AIError(oversized);
6273
6374
  return freezeRoutineMetadata(JSON.parse(encoded));
6274
6375
  } catch (error) {
6275
- throw error instanceof AIError ? error : new AIError(invalid16);
6376
+ throw error instanceof AIError ? error : new AIError(invalid18);
6276
6377
  }
6277
6378
  }
6278
6379
  function parseRoutineAIRequest(value) {
@@ -6337,12 +6438,12 @@ function acceptText(request3, text5) {
6337
6438
 
6338
6439
  var ROUTINE_STEP_SUMMARY_BYTES = 256 * 1024, ROUTINE_STEP_OUTPUT_BYTES = 1024 * 1024;
6339
6440
  function parseRoutineStepOutputDetail(value) {
6340
- let invalid16 = () => {
6441
+ let invalid18 = () => {
6341
6442
  throw new AppRoutineContractError("invalid_value");
6342
6443
  };
6343
6444
  assertRoutineFields(value, ["step", "sizeBytes", "limitBytes", "summaryBytes", "dataBytes"]);
6344
6445
  let { step, sizeBytes, limitBytes, summaryBytes, dataBytes } = value;
6345
- return !isAppRoutineName(step) || ![sizeBytes, limitBytes, summaryBytes, dataBytes].every((bytes) => Number.isSafeInteger(bytes) && bytes > 0) || sizeBytes !== summaryBytes + dataBytes || limitBytes !== (summaryBytes > ROUTINE_STEP_SUMMARY_BYTES ? ROUTINE_STEP_SUMMARY_BYTES : ROUTINE_STEP_OUTPUT_BYTES) || (limitBytes === ROUTINE_STEP_SUMMARY_BYTES ? summaryBytes : sizeBytes) <= limitBytes ? invalid16() : freezeRoutineMetadata({ step, sizeBytes, limitBytes, summaryBytes, dataBytes });
6446
+ return !isAppRoutineName(step) || ![sizeBytes, limitBytes, summaryBytes, dataBytes].every((bytes) => Number.isSafeInteger(bytes) && bytes > 0) || sizeBytes !== summaryBytes + dataBytes || limitBytes !== (summaryBytes > ROUTINE_STEP_SUMMARY_BYTES ? ROUTINE_STEP_SUMMARY_BYTES : ROUTINE_STEP_OUTPUT_BYTES) || (limitBytes === ROUTINE_STEP_SUMMARY_BYTES ? summaryBytes : sizeBytes) <= limitBytes ? invalid18() : freezeRoutineMetadata({ step, sizeBytes, limitBytes, summaryBytes, dataBytes });
6346
6447
  }
6347
6448
  function routineStepOutputMessage(value) {
6348
6449
  let detail = parseRoutineStepOutputDetail(value), size = `${(detail.sizeBytes / (1024 * 1024)).toFixed(1)} MB`, bound = detail.limitBytes === ROUTINE_STEP_SUMMARY_BYTES ? `, including ${(detail.summaryBytes / 1024).toFixed(1)} KB of summary. Each step's summary can return up to 256 KB.` : ". Each step can return up to 1 MB across its summary and data.";
@@ -6627,7 +6728,7 @@ async function executeRoutineDefinition(definition, input, runtime2) {
6627
6728
  if (result2 !== void 0) return invalid3();
6628
6729
  }
6629
6730
 
6630
- var queueStates = ["pending", "running", "failed", "succeeded", "removed"], uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
6731
+ var queueStates = ["pending", "running", "waiting", "failed", "succeeded", "removed"], uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
6631
6732
  function object3(value) {
6632
6733
  if (!value || typeof value != "object" || Array.isArray(value)) throw new Error("Invalid queue result");
6633
6734
  return value;
@@ -6640,6 +6741,12 @@ function date(value) {
6640
6741
  if (typeof value != "string" || !Number.isFinite(Date.parse(value))) throw new Error("Invalid queue timestamp");
6641
6742
  return value;
6642
6743
  }
6744
+ function parseQueueAskWait(value) {
6745
+ let v = object3(value), ask = object3(v.ask);
6746
+ if (!Number.isSafeInteger(ask.number) || Number(ask.number) < 1 || typeof ask.title != "string" || !ask.title.trim())
6747
+ throw new Error("Invalid queue Ask wait");
6748
+ return { runId: id2(v.runId), ask: { id: id2(ask.id), number: ask.number, title: ask.title } };
6749
+ }
6643
6750
  function parseQueueSummary(value) {
6644
6751
  let v = object3(value), counts = object3(v.counts);
6645
6752
  if (typeof v.routineId != "string" || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(v.routineId) || typeof v.paused != "boolean" || queueStates.some((state) => !Number.isSafeInteger(counts[state]) || Number(counts[state]) < 0)) throw new Error("Invalid queue summary");
@@ -6655,15 +6762,18 @@ function parseQueueItem(value) {
6655
6762
  if (!Object.hasOwn(v, "input") || !queueStates.includes(v.state) || !Array.isArray(v.associatedRunIds) || v.idempotencyKey !== void 0 && typeof v.idempotencyKey != "string") throw new Error("Invalid queue item");
6656
6763
  let failure = v.failure === void 0 ? void 0 : object3(v.failure);
6657
6764
  if (failure && typeof failure.message != "string") throw new Error("Invalid queue failure");
6765
+ let associatedRunIds = v.associatedRunIds.map(id2), askWait = v.askWait === void 0 ? void 0 : parseQueueAskWait(v.askWait);
6766
+ if (askWait && !associatedRunIds.includes(askWait.runId)) throw new Error("Invalid queue Ask wait");
6658
6767
  return {
6659
6768
  id: id2(v.id),
6660
6769
  input: v.input,
6661
6770
  state: v.state,
6662
- associatedRunIds: v.associatedRunIds.map(id2),
6771
+ associatedRunIds,
6663
6772
  createdAt: date(v.createdAt),
6664
6773
  updatedAt: date(v.updatedAt),
6665
6774
  ...v.idempotencyKey === void 0 ? {} : { idempotencyKey: v.idempotencyKey },
6666
6775
  ...v.currentRunId === void 0 ? {} : { currentRunId: id2(v.currentRunId) },
6776
+ ...askWait === void 0 ? {} : { askWait },
6667
6777
  ...v.failureId === void 0 ? {} : { failureId: id2(v.failureId) },
6668
6778
  ...failure ? { failure: { message: failure.message } } : {}
6669
6779
  };
@@ -6876,20 +6986,20 @@ var localDataPath = (value, repository) => typeof value == "string" && value.len
6876
6986
  return Object.keys(row).sort().join(",") === "action,path" && ["created", "updated", "deleted"].includes(String(row.action)) && localDataPath(row.path, repository);
6877
6987
  };
6878
6988
  function parseDataFailureDetail(value) {
6879
- let invalid16 = () => {
6989
+ let invalid18 = () => {
6880
6990
  throw new Error("Invalid local Data failure detail");
6881
6991
  };
6882
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid16();
6992
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
6883
6993
  let row = value;
6884
- if (Object.keys(row).sort().join(",") !== "cause,code,files,nextAction,operation,repository" || !["local_data_read_failed", "local_data_write_failed", "local_data_write_partial"].includes(String(row.code)) || !["read", "write"].includes(String(row.operation)) || typeof row.repository != "string" || !/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(row.repository) || row.repository.includes("//") || row.repository.includes("..") || !["fix_failed_file_then_rerun", "review_resolve_then_rerun"].includes(String(row.nextAction))) return invalid16();
6994
+ if (Object.keys(row).sort().join(",") !== "cause,code,files,nextAction,operation,repository" || !["local_data_read_failed", "local_data_write_failed", "local_data_write_partial"].includes(String(row.code)) || !["read", "write"].includes(String(row.operation)) || typeof row.repository != "string" || !/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(row.repository) || row.repository.includes("//") || row.repository.includes("..") || !["fix_failed_file_then_rerun", "review_resolve_then_rerun"].includes(String(row.nextAction))) return invalid18();
6885
6995
  let repository = row.repository;
6886
- if (!row.cause || typeof row.cause != "object" || Array.isArray(row.cause)) return invalid16();
6996
+ if (!row.cause || typeof row.cause != "object" || Array.isArray(row.cause)) return invalid18();
6887
6997
  let cause = row.cause;
6888
- if (!["code,message", "code,message,path"].includes(Object.keys(cause).sort().join(",")) || !["schema_validation_failed", "invalid_record", "unsafe_record", "stale_record", "path_conflict", "filesystem_unavailable"].includes(String(cause.code)) || typeof cause.message != "string" || !cause.message || cause.message.length > 512 || /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(cause.message) || cause.path !== void 0 && !localDataPath(cause.path, repository) || !row.files || typeof row.files != "object" || Array.isArray(row.files)) return invalid16();
6998
+ if (!["code,message", "code,message,path"].includes(Object.keys(cause).sort().join(",")) || !["schema_validation_failed", "invalid_record", "unsafe_record", "stale_record", "path_conflict", "filesystem_unavailable"].includes(String(cause.code)) || typeof cause.message != "string" || !cause.message || cause.message.length > 512 || /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(cause.message) || cause.path !== void 0 && !localDataPath(cause.path, repository) || !row.files || typeof row.files != "object" || Array.isArray(row.files)) return invalid18();
6889
6999
  let files3 = row.files;
6890
- if (Object.keys(files3).some((key) => !["state", "saved", "failed", "notAttempted", "savedOmitted", "notAttemptedOmitted"].includes(key)) || !["none", "partial"].includes(String(files3.state)) || !Array.isArray(files3.saved) || files3.saved.length > 128 || !files3.saved.every((item) => localDataFile(item, repository)) || files3.failed !== void 0 && !localDataFile(files3.failed, repository) || !Array.isArray(files3.notAttempted) || files3.notAttempted.length > 128 || !files3.notAttempted.every((item) => localDataFile(item, repository))) return invalid16();
6891
- for (let key of ["savedOmitted", "notAttemptedOmitted"]) if (files3[key] !== void 0 && (!Number.isSafeInteger(files3[key]) || Number(files3[key]) < 1 || Number(files3[key]) > 1e4)) return invalid16();
6892
- return row.operation === "read" && (row.code !== "local_data_read_failed" || files3.state !== "none" || files3.saved.length || files3.failed !== void 0 || files3.notAttempted.length) || row.operation === "write" && row.code === "local_data_read_failed" || row.code === "local_data_write_partial" && (files3.state !== "partial" || !files3.saved.length) || row.code !== "local_data_write_partial" && files3.state === "partial" ? invalid16() : structuredClone(value);
7000
+ if (Object.keys(files3).some((key) => !["state", "saved", "failed", "notAttempted", "savedOmitted", "notAttemptedOmitted"].includes(key)) || !["none", "partial"].includes(String(files3.state)) || !Array.isArray(files3.saved) || files3.saved.length > 128 || !files3.saved.every((item) => localDataFile(item, repository)) || files3.failed !== void 0 && !localDataFile(files3.failed, repository) || !Array.isArray(files3.notAttempted) || files3.notAttempted.length > 128 || !files3.notAttempted.every((item) => localDataFile(item, repository))) return invalid18();
7001
+ for (let key of ["savedOmitted", "notAttemptedOmitted"]) if (files3[key] !== void 0 && (!Number.isSafeInteger(files3[key]) || Number(files3[key]) < 1 || Number(files3[key]) > 1e4)) return invalid18();
7002
+ return row.operation === "read" && (row.code !== "local_data_read_failed" || files3.state !== "none" || files3.saved.length || files3.failed !== void 0 || files3.notAttempted.length) || row.operation === "write" && row.code === "local_data_read_failed" || row.code === "local_data_write_partial" && (files3.state !== "partial" || !files3.saved.length) || row.code !== "local_data_write_partial" && files3.state === "partial" ? invalid18() : structuredClone(value);
6893
7003
  }
6894
7004
  function parseDataOperationDetail(value) {
6895
7005
  if (value && typeof value == "object" && !Array.isArray(value) && value.code === "publication_conflict")
@@ -7025,12 +7135,12 @@ var ConnectionOperationError = class extends Error {
7025
7135
 
7026
7136
  var ROUTINE_ERROR_CODE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
7027
7137
  function parseRoutineErrorDeclaration(value) {
7028
- let invalid16 = () => {
7138
+ let invalid18 = () => {
7029
7139
  throw new TypeError("Invalid RoutineError");
7030
7140
  };
7031
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid16();
7141
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
7032
7142
  let row = value;
7033
- return Object.keys(row).some((key) => !["code", "message", "retryable"].includes(key)) || !Object.hasOwn(row, "code") || !Object.hasOwn(row, "message") || typeof row.code != "string" || !ROUTINE_ERROR_CODE_PATTERN.test(row.code) || typeof row.message != "string" || !row.message || row.message.startsWith(" ") || row.message.endsWith(" ") || /[\u0000-\u001f\u007f\u0085\u2028\u2029]/.test(row.message) || /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF])/.test(row.message) || new TextEncoder().encode(row.message).byteLength > 512 || Object.hasOwn(row, "retryable") && typeof row.retryable != "boolean" ? invalid16() : { code: row.code, message: row.message, retryable: row.retryable === !0 };
7143
+ return Object.keys(row).some((key) => !["code", "message", "retryable"].includes(key)) || !Object.hasOwn(row, "code") || !Object.hasOwn(row, "message") || typeof row.code != "string" || !ROUTINE_ERROR_CODE_PATTERN.test(row.code) || typeof row.message != "string" || !row.message || row.message.startsWith(" ") || row.message.endsWith(" ") || /[\u0000-\u001f\u007f\u0085\u2028\u2029]/.test(row.message) || /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF])/.test(row.message) || new TextEncoder().encode(row.message).byteLength > 512 || Object.hasOwn(row, "retryable") && typeof row.retryable != "boolean" ? invalid18() : { code: row.code, message: row.message, retryable: row.retryable === !0 };
7034
7144
  }
7035
7145
  var RoutineError = class extends Error {
7036
7146
  code;
@@ -7047,17 +7157,17 @@ Anything the routine completed before stopping is safe.`, ROUTINE_RUN_UNCERTAIN_
7047
7157
 
7048
7158
  Some work may need review before you try again. Contact support.`;
7049
7159
  function parseRoutineAuthoredRunFailure(value) {
7050
- let invalid16 = () => {
7160
+ let invalid18 = () => {
7051
7161
  throw new Error("Invalid authored Run failure");
7052
7162
  };
7053
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid16();
7163
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
7054
7164
  let row = value;
7055
- if (Object.keys(row).sort().join(",") !== "code,message,retryable" || typeof row.message != "string" || typeof row.retryable != "boolean") return invalid16();
7165
+ if (Object.keys(row).sort().join(",") !== "code,message,retryable" || typeof row.message != "string" || typeof row.retryable != "boolean") return invalid18();
7056
7166
  let authored = row.message.endsWith(ROUTINE_RUN_UNCERTAIN_SUFFIX) ? row.message.slice(0, -ROUTINE_RUN_UNCERTAIN_SUFFIX.length) : row.message.endsWith(ROUTINE_RUN_COMPLETED_SUFFIX) ? row.message.slice(0, -ROUTINE_RUN_COMPLETED_SUFFIX.length) : row.message;
7057
7167
  try {
7058
7168
  parseRoutineErrorDeclaration({ code: row.code, message: authored, retryable: row.retryable });
7059
7169
  } catch {
7060
- return invalid16();
7170
+ return invalid18();
7061
7171
  }
7062
7172
  return { code: row.code, message: row.message, retryable: row.retryable };
7063
7173
  }
@@ -7084,7 +7194,7 @@ function progress(value) {
7084
7194
  }
7085
7195
  function parseRunStep(value, expected) {
7086
7196
  let v = record2(value);
7087
- if (typeof v.id != "string" || !name2.test(v.id) || expected !== void 0 && v.id !== expected || typeof v.title != "string" || !v.title.trim() || v.title.length > 256 || !["pending", "running", "completed", "failed", "skipped"].includes(v.status)) return invalid5();
7197
+ if (typeof v.id != "string" || !name2.test(v.id) || expected !== void 0 && v.id !== expected || typeof v.title != "string" || !v.title.trim() || v.title.length > 256 || !["pending", "running", "waiting", "completed", "failed", "skipped"].includes(v.status)) return invalid5();
7088
7198
  let output = captureRetainedStepOutput(v.id, {
7089
7199
  ...Object.hasOwn(v, "summary") ? { summary: v.summary } : {},
7090
7200
  ...Object.hasOwn(v, "data") ? { data: v.data } : {}
@@ -7101,7 +7211,7 @@ function parseRunStep(value, expected) {
7101
7211
  }
7102
7212
  function parseRemoteRun(value, expected = {}) {
7103
7213
  let v = record2(value);
7104
- if (typeof v.id != "string" || !uuid3.test(v.id) || expected.id !== void 0 && v.id !== expected.id || typeof v.routine != "string" || !name2.test(v.routine) || expected.routine !== void 0 && v.routine !== expected.routine || v.placement !== "remote" || !["queued", "running", "succeeded", "failed"].includes(v.status) || !Array.isArray(v.steps) || v.steps.length > 64) return invalid5();
7214
+ if (typeof v.id != "string" || !uuid3.test(v.id) || expected.id !== void 0 && v.id !== expected.id || typeof v.routine != "string" || !name2.test(v.routine) || expected.routine !== void 0 && v.routine !== expected.routine || v.placement !== "remote" || !["queued", "running", "waiting", "succeeded", "failed"].includes(v.status) || !Array.isArray(v.steps) || v.steps.length > 64) return invalid5();
7105
7215
  let steps = v.steps.map((value2) => {
7106
7216
  let step = record2(value2);
7107
7217
  return typeof step.detailAvailable != "boolean" || Object.hasOwn(step, "data") ? invalid5() : { ...parseRunStep(step), detailAvailable: step.detailAvailable };
@@ -7123,7 +7233,9 @@ function parseRemoteRun(value, expected = {}) {
7123
7233
  }
7124
7234
  else failure = { message: f.message };
7125
7235
  }
7126
- return Object.hasOwn(v, "result") && v.status !== "succeeded" ? invalid5() : {
7236
+ if (Object.hasOwn(v, "result") && v.status !== "succeeded") return invalid5();
7237
+ let askWait = v.askWait === void 0 ? void 0 : parseQueueAskWait(v.askWait);
7238
+ return askWait && askWait.runId !== v.id ? invalid5() : {
7127
7239
  id: v.id,
7128
7240
  routine: v.routine,
7129
7241
  placement: "remote",
@@ -7131,6 +7243,8 @@ function parseRemoteRun(value, expected = {}) {
7131
7243
  createdAt: time(v.createdAt),
7132
7244
  ...times(v),
7133
7245
  steps,
7246
+ ...v.queueItemId === void 0 ? {} : { queueItemId: typeof v.queueItemId == "string" && uuid3.test(v.queueItemId) ? v.queueItemId : invalid5() },
7247
+ ...askWait === void 0 ? {} : { askWait },
7134
7248
  ...Object.hasOwn(v, "result") ? { result: bounded(v.result) } : {},
7135
7249
  ...failure ? { failure } : {}
7136
7250
  };
@@ -7144,7 +7258,7 @@ function routineRunHandle(operations2) {
7144
7258
  let previous;
7145
7259
  for (; ; ) {
7146
7260
  let state = await operations2.current(), encoded = JSON.stringify(state);
7147
- if (encoded !== previous && (previous = encoded, yield state), state.status === "succeeded" || state.status === "failed" || state.status === "legacy") return;
7261
+ if (encoded !== previous && (previous = encoded, yield state), state.status === "waiting" || state.status === "succeeded" || state.status === "failed" || state.status === "legacy") return;
7148
7262
  await (operations2.wait?.() ?? new Promise((resolve) => setTimeout(resolve, 100)));
7149
7263
  }
7150
7264
  }
@@ -7175,29 +7289,41 @@ function dataArray(value) {
7175
7289
  var invalid7 = () => {
7176
7290
  throw new DataOperationError("invalid_query");
7177
7291
  };
7292
+ function captureRecordsBacklinksInput(ref, value) {
7293
+ if (!validRecordRef(ref)) return invalid7();
7294
+ if (value === void 0) return { ref, options: { limit: 100 } };
7295
+ let descriptors = dataProperties(value);
7296
+ if (Object.keys(descriptors).some((key) => !["limit", "after"].includes(key))) return invalid7();
7297
+ let options = Object.fromEntries(Object.entries(descriptors).map(([key, descriptor]) => [key, descriptor.value])), limit = Object.hasOwn(options, "limit") ? options.limit : 100;
7298
+ return !Number.isSafeInteger(limit) || limit < 1 || limit > 500 || Object.hasOwn(options, "after") && (!dataText(options.after) || !options.after.length || options.after.length > 16384) ? invalid7() : { ref, options: { limit, ...options.after === void 0 ? {} : { after: options.after } } };
7299
+ }
7300
+
7301
+ var invalid8 = () => {
7302
+ throw new DataOperationError("invalid_query");
7303
+ };
7178
7304
  function captureRecordsSearchInput(query, options) {
7179
- if (!dataText(query)) return invalid7();
7305
+ if (!dataText(query)) return invalid8();
7180
7306
  let length = [...query.trim()].length;
7181
- if (length < 1 || length > 256) return invalid7();
7307
+ if (length < 1 || length > 256) return invalid8();
7182
7308
  if (options === void 0) return { query };
7183
7309
  let descriptors = dataProperties(options);
7184
- if (Object.keys(descriptors).some((key) => !["collections", "limit"].includes(key))) return invalid7();
7310
+ if (Object.keys(descriptors).some((key) => !["collections", "limit"].includes(key))) return invalid8();
7185
7311
  let captured = {};
7186
7312
  if (Object.hasOwn(descriptors, "collections")) {
7187
7313
  let supplied = descriptors.collections.value;
7188
- if (!Array.isArray(supplied) || supplied.length < 1 || supplied.length > 16 || Reflect.ownKeys(supplied).length !== supplied.length + 1) return invalid7();
7314
+ if (!Array.isArray(supplied) || supplied.length < 1 || supplied.length > 16 || Reflect.ownKeys(supplied).length !== supplied.length + 1) return invalid8();
7189
7315
  let collections = [];
7190
7316
  for (let index = 0; index < supplied.length; index++) {
7191
7317
  let descriptor = Object.getOwnPropertyDescriptor(supplied, String(index));
7192
- if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value") || !dataText(descriptor.value)) return invalid7();
7318
+ if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value") || !dataText(descriptor.value)) return invalid8();
7193
7319
  collections.push(descriptor.value);
7194
7320
  }
7195
- if (new Set(collections).size !== collections.length) return invalid7();
7321
+ if (new Set(collections).size !== collections.length) return invalid8();
7196
7322
  captured.collections = collections;
7197
7323
  }
7198
7324
  if (Object.hasOwn(descriptors, "limit")) {
7199
7325
  let supplied = descriptors.limit.value;
7200
- if (!Number.isInteger(supplied) || supplied < 1 || supplied > 100) return invalid7();
7326
+ if (!Number.isInteger(supplied) || supplied < 1 || supplied > 100) return invalid8();
7201
7327
  captured.limit = supplied;
7202
7328
  }
7203
7329
  return { query, options: captured };
@@ -7237,21 +7363,21 @@ function captureRecordsQuery(query) {
7237
7363
  return capture3(query);
7238
7364
  }
7239
7365
  function captureRecordsAll(query, options) {
7240
- let invalid16 = () => {
7366
+ let invalid18 = () => {
7241
7367
  throw new DataOperationError("invalid_query");
7242
7368
  };
7243
7369
  try {
7244
7370
  let properties = dataProperties(options), maxRecords = properties.maxRecords?.value;
7245
- if (Object.keys(properties).join(",") !== "maxRecords" || !Number.isSafeInteger(maxRecords) || maxRecords < 1) return invalid16();
7371
+ if (Object.keys(properties).join(",") !== "maxRecords" || !Number.isSafeInteger(maxRecords) || maxRecords < 1) return invalid18();
7246
7372
  let detached = capture3(query), selections = dataProperties(detached);
7247
- if (Object.keys(selections).length < 1 || Object.keys(selections).length > 16) return invalid16();
7373
+ if (Object.keys(selections).length < 1 || Object.keys(selections).length > 16) return invalid18();
7248
7374
  for (let selection2 of Object.values(selections)) {
7249
7375
  let fields4 = dataProperties(selection2.value);
7250
- if (fields4.$ && Object.hasOwn(dataProperties(fields4.$.value), "after")) return invalid16();
7376
+ if (fields4.$ && Object.hasOwn(dataProperties(fields4.$.value), "after")) return invalid18();
7251
7377
  }
7252
7378
  return { query: detached, maxRecords };
7253
7379
  } catch {
7254
- return invalid16();
7380
+ return invalid18();
7255
7381
  }
7256
7382
  }
7257
7383
 
@@ -7489,10 +7615,10 @@ function parseStoredRecordLink(value) {
7489
7615
  return typeof value == "string" && value.startsWith("[[") && value.endsWith("]]") ? parseRecordLink(value.slice(2, -2)) : void 0;
7490
7616
  }
7491
7617
 
7492
- var NAME = /^[a-zA-Z][a-zA-Z0-9_-]*$/, invalid8 = (message2) => {
7618
+ var NAME = /^[a-zA-Z][a-zA-Z0-9_-]*$/, invalid9 = (message2) => {
7493
7619
  throw new Error(message2);
7494
7620
  };
7495
- function parseRecordDisplay(value, definitions3, fail9 = invalid8) {
7621
+ function parseRecordDisplay(value, definitions3, fail9 = invalid9) {
7496
7622
  if (value === void 0) return;
7497
7623
  if (!value || typeof value != "object" || Array.isArray(value)) return fail9("Expected a field mapping");
7498
7624
  let row = value;
@@ -7764,7 +7890,11 @@ function parseInboxCurrent(value) {
7764
7890
  }
7765
7891
  function parseInboxItem(value) {
7766
7892
  let item = object5(json(value));
7767
- return assert(id4(item.id) && id4(item.workspaceId) && integer(item.number) && integer(item.revision) && integer(item.activityVersion, 0) && ["ask", "digest"].includes(String(item.kind)) && ["open", "closed"].includes(String(item.lifecycle)) && text2(item.title) && text2(item.description, !0) && text2(item.author) && date3(item.publishedAt) && optionalDate(item.seenAt) && optionalDate(item.digestReadAt)), item.outcome !== null && assert(text2(object5(item.outcome).outcome)), "canonicalRoutineId" in item && assert(item.canonicalRoutineId === null || isAppRoutineName(item.canonicalRoutineId)), "apiClientId" in item && assert(item.apiClientId === null || id4(item.apiClientId) && item.kind === "digest"), item.kind === "ask" ? askMetadata(item) : assert(!("tags" in item) && !("recordRefs" in item)), array2(item.body).forEach(validateBlock), array2(item.views).forEach((value2) => {
7893
+ if (assert(id4(item.id) && id4(item.workspaceId) && integer(item.number) && integer(item.revision) && integer(item.activityVersion, 0) && ["ask", "digest"].includes(String(item.kind)) && ["open", "closed"].includes(String(item.lifecycle)) && text2(item.title) && text2(item.description, !0) && text2(item.author) && date3(item.publishedAt) && optionalDate(item.seenAt) && optionalDate(item.digestReadAt)), item.outcome !== null && assert(text2(object5(item.outcome).outcome)), "canonicalRoutineId" in item && assert(item.canonicalRoutineId === null || isAppRoutineName(item.canonicalRoutineId)), "apiClientId" in item && assert(item.apiClientId === null || id4(item.apiClientId) && item.kind === "digest"), "queueContinuation" in item) {
7894
+ let continuation2 = object5(item.queueContinuation);
7895
+ keys2(continuation2, ["routineId", "itemId", "runId"]), assert(item.kind === "ask" && isAppRoutineName(continuation2.routineId) && id4(continuation2.itemId) && id4(continuation2.runId));
7896
+ }
7897
+ return item.kind === "ask" ? askMetadata(item) : assert(!("tags" in item) && !("recordRefs" in item)), array2(item.body).forEach(validateBlock), array2(item.views).forEach((value2) => {
7768
7898
  let view = object5(value2);
7769
7899
  assert(text2(view.id) && text2(view.view) && text2(view.implementation)), json(view.input);
7770
7900
  }), array2(item.people).forEach((value2) => {
@@ -8627,16 +8757,16 @@ function inspectRoutineQueueReference(queue) {
8627
8757
  return id5;
8628
8758
  }
8629
8759
 
8630
- var definitions2 = /* @__PURE__ */ new WeakMap(), invalid9 = () => {
8760
+ var definitions2 = /* @__PURE__ */ new WeakMap(), invalid10 = () => {
8631
8761
  throw new AppRoutineContractError("invalid_contract");
8632
8762
  }, defineQuery = (definition) => {
8633
- if (assertRoutineFields(definition, ["id", "queue", "triggers", "access", "run"]), !isAppRoutineName(definition.id) || typeof definition.run != "function") return invalid9();
8763
+ if (assertRoutineFields(definition, ["id", "queue", "triggers", "access", "run"]), !isAppRoutineName(definition.id) || typeof definition.run != "function") return invalid10();
8634
8764
  let routineId = inspectRoutineQueueReference(definition.queue), triggers;
8635
8765
  try {
8636
- if (assertRoutineJson(definition.triggers), !Array.isArray(definition.triggers)) return invalid9();
8766
+ if (assertRoutineJson(definition.triggers), !Array.isArray(definition.triggers)) return invalid10();
8637
8767
  triggers = definition.triggers.map((trigger) => (assertRoutineFields(trigger, ["schedule"]), { schedule: parseRoutineSchedule(trigger.schedule) }));
8638
8768
  } catch {
8639
- return invalid9();
8769
+ return invalid10();
8640
8770
  }
8641
8771
  let access = parseRoutineAccess(definition.access), contract = freezeRoutineMetadata({ id: definition.id, routineId, access, triggers }), captured = Object.freeze({ ...definition, access, triggers: contract.triggers });
8642
8772
  return definitions2.set(captured, contract), captured;
@@ -8745,14 +8875,14 @@ function checked(workspace, endpoint, headers) {
8745
8875
  return { url: `${origin.origin}/api/data`, headers: { ...headers, "x-os-workspace": workspace } };
8746
8876
  }
8747
8877
 
8748
- var invalid10 = () => {
8878
+ var invalid11 = () => {
8749
8879
  throw new DataOperationError("invalid_query");
8750
8880
  }, unavailable = () => {
8751
8881
  throw new DataOperationError("unavailable");
8752
8882
  }, text3 = (value) => typeof value == "string" && value.length > 0;
8753
8883
  function capture4(value, ancestors = /* @__PURE__ */ new Set(), depth = 0) {
8754
8884
  if (value === null || typeof value == "string" || typeof value == "boolean" || typeof value == "number" && Number.isFinite(value)) return value;
8755
- if (!value || typeof value != "object" || ancestors.has(value) || depth > 32) return invalid10();
8885
+ if (!value || typeof value != "object" || ancestors.has(value) || depth > 32) return invalid11();
8756
8886
  ancestors.add(value);
8757
8887
  try {
8758
8888
  return Array.isArray(value) ? dataArray(value).map((item) => capture4(item, ancestors, depth + 1)) : Object.fromEntries(Object.entries(dataProperties(value)).map(([key, descriptor]) => [key, capture4(descriptor.value, ancestors, depth + 1)]));
@@ -8767,7 +8897,7 @@ function recordPagination(queryRecords) {
8767
8897
  let selection2 = dataProperties(captured[name4]);
8768
8898
  if (Object.hasOwn(selection2, "$")) {
8769
8899
  let options = dataProperties(selection2.$.value);
8770
- if (Object.hasOwn(options, "after")) return invalid10();
8900
+ if (Object.hasOwn(options, "after")) return invalid11();
8771
8901
  }
8772
8902
  }
8773
8903
  return iterate();
@@ -9053,6 +9183,60 @@ function scalarField(name4, schema2) {
9053
9183
  let field = schema2.fields.find((field2) => field2.name === name4);
9054
9184
  return !field || field.many || field.kind === "object" || field.kind === "map" ? fail5(`ineligible scalar field: ${name4}`) : field;
9055
9185
  }
9186
+ function linkPath(name4) {
9187
+ if (name4 === "$ref") return;
9188
+ let segments = [], segment = "";
9189
+ for (let index = 0; index < name4.length; index++) {
9190
+ let character = name4[index];
9191
+ if (character === "\\") {
9192
+ let escaped = name4[++index];
9193
+ if (escaped !== "." && escaped !== "\\") return fail5(`invalid link path: ${name4}`);
9194
+ segment += escaped;
9195
+ } else if (character === ".") {
9196
+ if (!segment) return fail5(`invalid link path: ${name4}`);
9197
+ segments.push(segment), segment = "";
9198
+ } else segment += character;
9199
+ }
9200
+ if (!segment) return fail5(`invalid link path: ${name4}`);
9201
+ if (segments.push(segment), segments.length === 1) return;
9202
+ if (segments.at(-1) !== "$ref" || segments.length < 2) return fail5(`invalid link path: ${name4}`);
9203
+ let path = segments.slice(0, -1);
9204
+ return path.length > 4 ? fail5("too many link levels") : path;
9205
+ }
9206
+ function linkCondition(name4, condition, path, schemas2, collections, collectionsByType, allowUnknownTerminalRefs) {
9207
+ let current2 = [...schemas2];
9208
+ for (let [index, part] of path.entries()) {
9209
+ let links = current2.map((schema2) => schema2.fields.find((field) => field.name === part)).filter((field) => !!field);
9210
+ if (links.length !== current2.length || links.some((field) => field.kind !== "link"))
9211
+ return fail5(`ineligible link path: ${name4}`);
9212
+ if (index < path.length - 1) {
9213
+ let targets2 = /* @__PURE__ */ new Map();
9214
+ for (let field of links) for (let type of field.kind === "link" ? field.to : []) {
9215
+ let candidates = collectionsByType.get(type) ?? fail5(`unknown link target type: ${type}`);
9216
+ for (let candidate of candidates) targets2.set(candidate.name, candidate.schema);
9217
+ }
9218
+ current2 = [...targets2.values()];
9219
+ } else {
9220
+ let values = [condition];
9221
+ if (condition !== null && typeof condition == "object") {
9222
+ let expression = mapping3(condition);
9223
+ if (Object.keys(expression).length !== 1 || !Object.hasOwn(expression, "$in") || !Array.isArray(expression.$in) || expression.$in.length < 1 || expression.$in.length > 100)
9224
+ return fail5("invalid link $in");
9225
+ values = expression.$in;
9226
+ }
9227
+ if (values.some((value) => !validRecordRef(value))) return fail5(`invalid reference: ${name4}`);
9228
+ let refs = values;
9229
+ if (new Set(refs).size !== refs.length) return fail5("duplicate $in value");
9230
+ for (let ref of refs) {
9231
+ let target = collections.filter((collection) => ref.startsWith(`${collection.name}/`)).sort((a, b) => b.name.length - a.name.length)[0];
9232
+ if (!target && !allowUnknownTerminalRefs || target && links.some((field) => field.kind !== "link" || !field.to.includes(target.schema.type)))
9233
+ return fail5(`incompatible reference: ${name4}`);
9234
+ }
9235
+ return { path, refs: [...refs] };
9236
+ }
9237
+ }
9238
+ return fail5(`invalid link path: ${name4}`);
9239
+ }
9056
9240
  function conditionValue(value, field) {
9057
9241
  return (field.kind === "link" || field.name === "$ref") && value !== null && !(field.kind === "link" ? parseRecordLink(value) : validRecordRef(value)) ? fail5(`invalid reference: ${field.name}`) : (validateRecordFields(
9058
9242
  { [field.name]: field.kind === "link" && typeof value == "string" ? `[[${value}]]` : value },
@@ -9076,13 +9260,13 @@ function preflightSelections(entries) {
9076
9260
  };
9077
9261
  for (let [, value] of entries) visit(value, 0);
9078
9262
  }
9079
- function selectionTree(value, schema2, collectionsByType, depth = 0, many = !1) {
9263
+ function selectionTree(value, schema2, collectionsByType, depth = 0, many = !1, allowUnknownTerminalRefs = !1) {
9080
9264
  let selection2 = mapping3(value), options = Object.hasOwn(selection2, "$") ? mapping3(selection2.$) : {}, allowed = depth === 0 ? ["where", "fields", "order", "limit", "count", "after"] : many ? ["where", "fields", "order", "limit"] : ["where", "fields"];
9081
9265
  if (allowed.push("timeline"), Object.keys(options).some((key) => !allowed.includes(key)))
9082
9266
  return fail5("unsupported option");
9083
9267
  let fields4 = Object.hasOwn(options, "fields") ? options.fields : schema2.fields.map((field) => field.name);
9084
9268
  if (!Array.isArray(fields4) || fields4.some((name4) => typeof name4 != "string" || !["$ref", "$version"].includes(name4) && !schema2.fields.some((field) => field.name === name4)) || new Set(fields4).size !== fields4.length) return fail5("invalid projection");
9085
- let conditions = [], signalConditions = [];
9269
+ let conditions = [], linkConditions = [], signalConditions = [];
9086
9270
  if (Object.hasOwn(options, "timeline") && options.timeline !== !0) return fail5("invalid timeline option");
9087
9271
  if (Object.hasOwn(options, "where")) for (let [name4, condition] of Object.entries(mapping3(options.where))) {
9088
9272
  if (name4 === "$signals") {
@@ -9102,6 +9286,19 @@ function selectionTree(value, schema2, collectionsByType, depth = 0, many = !1)
9102
9286
  }
9103
9287
  continue;
9104
9288
  }
9289
+ let path = linkPath(name4);
9290
+ if (path) {
9291
+ linkConditions.push(linkCondition(
9292
+ name4,
9293
+ condition,
9294
+ path,
9295
+ [schema2],
9296
+ [...collectionsByType.values()].flat(),
9297
+ collectionsByType,
9298
+ allowUnknownTerminalRefs
9299
+ ));
9300
+ continue;
9301
+ }
9105
9302
  let field = scalarField(name4, schema2), values = [condition];
9106
9303
  if (condition !== null && typeof condition == "object") {
9107
9304
  let expression = mapping3(condition);
@@ -9145,15 +9342,16 @@ function selectionTree(value, schema2, collectionsByType, depth = 0, many = !1)
9145
9342
  let field = schema2.fields.find((field2) => field2.name === name4);
9146
9343
  if (!field || field.kind !== "link") return fail5(`ineligible link field: ${name4}`);
9147
9344
  if (depth >= 4) return fail5("too many link levels");
9148
- let targets = new Map(field.to.flatMap((type) => (collectionsByType.get(type) ?? fail5(`unknown link target type: ${type}`)).map((target) => [
9345
+ let targets2 = new Map(field.to.flatMap((type) => (collectionsByType.get(type) ?? fail5(`unknown link target type: ${type}`)).map((target) => [
9149
9346
  target.name,
9150
- selectionTree(nested, target.schema, collectionsByType, depth + 1, field.many)
9347
+ selectionTree(nested, target.schema, collectionsByType, depth + 1, field.many, allowUnknownTerminalRefs)
9151
9348
  ])));
9152
- links.push({ name: name4, many: field.many, targets });
9349
+ links.push({ name: name4, many: field.many, targets: targets2 });
9153
9350
  }
9154
9351
  return {
9155
9352
  fields: fields4,
9156
9353
  conditions,
9354
+ linkConditions,
9157
9355
  ...signalConditions.length ? { signalConditions } : {},
9158
9356
  ...options.timeline === !0 ? { timeline: !0 } : {},
9159
9357
  order,
@@ -9169,6 +9367,7 @@ function selectionBinding(selection2, top = !0, many = !1) {
9169
9367
  return {
9170
9368
  fields: selection2.fields,
9171
9369
  conditions: [...selection2.conditions].sort(([a], [b]) => compare(a, b)),
9370
+ linkConditions: [...selection2.linkConditions].sort((a, b) => compare(a.path.join("\0"), b.path.join("\0"))),
9172
9371
  ...selection2.signalConditions ? { signalConditions: [...selection2.signalConditions].sort(([a], [b]) => compare(a, b)) } : {},
9173
9372
  ...selection2.timeline ? { timeline: !0 } : {},
9174
9373
  order: top || many && selection2.explicitOrder ? selection2.order : null,
@@ -9181,15 +9380,15 @@ function selectionBinding(selection2, top = !0, many = !1) {
9181
9380
  }))
9182
9381
  };
9183
9382
  }
9184
- function planIndexQuery(query, catalogue) {
9383
+ function planIndexQuery(query, catalogue, options = {}) {
9185
9384
  let entries = queryEntries(query), collections = new Map(catalogue.map((collection) => [collection.name, collection])), byType = /* @__PURE__ */ new Map();
9186
9385
  for (let collection of catalogue) {
9187
- let targets = byType.get(collection.schema.type) ?? [];
9188
- targets.push(collection), byType.set(collection.schema.type, targets);
9386
+ let targets2 = byType.get(collection.schema.type) ?? [];
9387
+ targets2.push(collection), byType.set(collection.schema.type, targets2);
9189
9388
  }
9190
9389
  return entries.map(([name4, value]) => {
9191
9390
  let target = collections.get(name4) ?? fail5(`unknown collection: ${name4}`);
9192
- return { name: name4, selection: selectionTree(value, target.schema, byType) };
9391
+ return { name: name4, selection: selectionTree(value, target.schema, byType, 0, !1, options.allowUnknownTerminalRefs === !0) };
9193
9392
  });
9194
9393
  }
9195
9394
  function indexSelectionBinding(context, collection, selection2) {
@@ -9206,9 +9405,9 @@ function cursorPosition(value, binding, limit) {
9206
9405
  return Object.keys(payload).length !== 4 || payload.format !== 1 || payload.binding !== binding || typeof position != "number" || !Number.isSafeInteger(position) || position <= 0 || position % limit !== 0 || typeof ref != "string" || !validRecordRef(ref) ? fail5("incompatible cursor") : { position, ref };
9207
9406
  }
9208
9407
 
9209
- var invalid11 = () => {
9408
+ var invalid12 = () => {
9210
9409
  throw new DataOperationError("unavailable", !0);
9211
- }, object7 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid11() : value, keys4 = (value, expected) => Object.keys(value).sort().join(",") === expected, hash = (value) => typeof value == "string" && /^[0-9a-f]{40}$/.test(value), time2 = (value) => typeof value == "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(value) && Number.isFinite(Date.parse(value)), sorted = (values) => values.every((value, i) => i === 0 || values[i - 1] < value);
9410
+ }, object7 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid12() : value, keys4 = (value, expected) => Object.keys(value).sort().join(",") === expected, hash = (value) => typeof value == "string" && /^[0-9a-f]{40}$/.test(value), time2 = (value) => typeof value == "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(value) && Number.isFinite(Date.parse(value)), sorted = (values) => values.every((value, i) => i === 0 || values[i - 1] < value);
9212
9411
  function json3(value) {
9213
9412
  if (!(value === null || typeof value == "boolean" || typeof value == "number" && Number.isFinite(value) || dataText(value))) {
9214
9413
  if (Array.isArray(value)) {
@@ -9216,7 +9415,7 @@ function json3(value) {
9216
9415
  return;
9217
9416
  }
9218
9417
  for (let [key, item] of Object.entries(object7(value))) {
9219
- if (!dataText(key)) return invalid11();
9418
+ if (!dataText(key)) return invalid12();
9220
9419
  json3(item);
9221
9420
  }
9222
9421
  }
@@ -9228,66 +9427,66 @@ var slot = (values, field) => Object.hasOwn(values, field) ? { present: !0, valu
9228
9427
  function apply(book, event) {
9229
9428
  let records = book.get(event.collection), prior = records.get(event.ref);
9230
9429
  if (event.kind === "create") {
9231
- if (prior) return invalid11();
9430
+ if (prior) return invalid12();
9232
9431
  records.set(event.ref, structuredClone(event.values));
9233
9432
  } else if (event.kind === "delete") {
9234
- if (!prior || stable(prior) !== stable(event.values)) return invalid11();
9433
+ if (!prior || stable(prior) !== stable(event.values)) return invalid12();
9235
9434
  records.delete(event.ref);
9236
9435
  } else if (event.kind === "rename") {
9237
9436
  let before = records.get(event.previousRef);
9238
- if (!before || prior) return invalid11();
9437
+ if (!before || prior) return invalid12();
9239
9438
  records.delete(event.previousRef), records.set(event.ref, before);
9240
9439
  } else if (event.kind === "update") {
9241
- if (!prior || stable(slot(prior, event.field)) !== stable(event.before) || stable(event.before) === stable(event.after)) return invalid11();
9440
+ if (!prior || stable(slot(prior, event.field)) !== stable(event.before) || stable(event.before) === stable(event.after)) return invalid12();
9242
9441
  event.after.present ? Object.defineProperty(prior, event.field, { value: structuredClone(event.after.value), enumerable: !0, configurable: !0, writable: !0 }) : delete prior[event.field];
9243
9442
  }
9244
9443
  }
9245
9444
  function validateSnapshotHistory(input, collections, version) {
9246
9445
  let row = object7(input), selections = object7(row.fields);
9247
- if (!keys4(row, "commits,fields,through") || !hash(row.through) || version !== `current-${row.through}` || !Array.isArray(row.commits) || !row.commits.length || !Object.keys(selections).length || !sorted(Object.keys(selections))) return invalid11();
9446
+ if (!keys4(row, "commits,fields,through") || !hash(row.through) || version !== `current-${row.through}` || !Array.isArray(row.commits) || !row.commits.length || !Object.keys(selections).length || !sorted(Object.keys(selections))) return invalid12();
9248
9447
  let book = /* @__PURE__ */ new Map();
9249
9448
  for (let [collection, selection2] of Object.entries(selections)) {
9250
9449
  let selected = object7(selection2), fields4 = selected.fields;
9251
- if (!Object.hasOwn(collections, collection) || !keys4(selected, "fields") || !Array.isArray(fields4) || !fields4.length || fields4.some((field) => typeof field != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(field)) || !sorted(fields4)) return invalid11();
9450
+ if (!Object.hasOwn(collections, collection) || !keys4(selected, "fields") || !Array.isArray(fields4) || !fields4.length || fields4.some((field) => typeof field != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(field)) || !sorted(fields4)) return invalid12();
9252
9451
  book.set(collection, /* @__PURE__ */ new Map());
9253
9452
  }
9254
9453
  let history = row, seen = /* @__PURE__ */ new Set(), parent = null;
9255
9454
  for (let group of history.commits) {
9256
- if (!keys4(object7(group), "authoredAt,commit,committedAt,events,firstParent") || !hash(group.commit) || seen.has(group.commit) || group.firstParent !== parent || !time2(group.authoredAt) || !time2(group.committedAt) || !Array.isArray(group.events)) return invalid11();
9455
+ if (!keys4(object7(group), "authoredAt,commit,committedAt,events,firstParent") || !hash(group.commit) || seen.has(group.commit) || group.firstParent !== parent || !time2(group.authoredAt) || !time2(group.committedAt) || !Array.isArray(group.events)) return invalid12();
9257
9456
  seen.add(group.commit), parent = group.commit;
9258
9457
  let previous, created = /* @__PURE__ */ new Set();
9259
9458
  for (let event of group.events) {
9260
- if (object7(event), !book.has(event.collection) || !validRecordRef(event.ref) || !event.ref.startsWith(`${event.collection}/`)) return invalid11();
9459
+ if (object7(event), !book.has(event.collection) || !validRecordRef(event.ref) || !event.ref.startsWith(`${event.collection}/`)) return invalid12();
9261
9460
  let fields4 = history.fields[event.collection].fields;
9262
9461
  if (event.kind === "create" || event.kind === "delete") {
9263
- if (!keys4(event, "collection,kind,ref,values") || Object.keys(object7(event.values)).some((field) => !fields4.includes(field))) return invalid11();
9462
+ if (!keys4(event, "collection,kind,ref,values") || Object.keys(object7(event.values)).some((field) => !fields4.includes(field))) return invalid12();
9264
9463
  json3(event.values), event.kind === "create" && created.add(event.ref);
9265
9464
  } else if (event.kind === "rename") {
9266
- if (!keys4(event, "collection,kind,previousRef,ref") || !validRecordRef(event.previousRef) || !event.previousRef.startsWith(`${event.collection}/`) || event.previousRef === event.ref) return invalid11();
9465
+ if (!keys4(event, "collection,kind,previousRef,ref") || !validRecordRef(event.previousRef) || !event.previousRef.startsWith(`${event.collection}/`) || event.previousRef === event.ref) return invalid12();
9267
9466
  } else if (event.kind === "update") {
9268
- if (!keys4(event, "after,before,collection,field,kind,ref") || !fields4.includes(event.field) || created.has(event.ref)) return invalid11();
9467
+ if (!keys4(event, "after,before,collection,field,kind,ref") || !fields4.includes(event.field) || created.has(event.ref)) return invalid12();
9269
9468
  for (let value of [event.before, event.after]) {
9270
- if (object7(value), value.present === !1 ? !keys4(value, "present") : value.present !== !0 || !keys4(value, "present,value")) return invalid11();
9469
+ if (object7(value), value.present === !1 ? !keys4(value, "present") : value.present !== !0 || !keys4(value, "present,value")) return invalid12();
9271
9470
  value.present && json3(value.value);
9272
9471
  }
9273
- } else return invalid11();
9472
+ } else return invalid12();
9274
9473
  let order = [event.kind === "delete" ? 0 : 1, event.ref, event.kind === "update" ? 1 : 0, event.kind === "update" ? event.field : ""];
9275
9474
  if (previous) {
9276
9475
  let index = order.findIndex((value, i) => value !== previous[i]);
9277
- if (index === -1 || order[index] < previous[index]) return invalid11();
9476
+ if (index === -1 || order[index] < previous[index]) return invalid12();
9278
9477
  }
9279
9478
  previous = order, apply(book, event);
9280
9479
  }
9281
9480
  let refs = /* @__PURE__ */ new Set();
9282
9481
  for (let records of book.values()) for (let ref of records.keys()) {
9283
- if (refs.has(ref)) return invalid11();
9482
+ if (refs.has(ref)) return invalid12();
9284
9483
  refs.add(ref);
9285
9484
  }
9286
9485
  }
9287
- if (parent !== history.through) return invalid11();
9486
+ if (parent !== history.through) return invalid12();
9288
9487
  for (let [collection, records] of book) {
9289
9488
  let expected = collections[collection].map((record4) => [record4.$ref, Object.fromEntries(history.fields[collection].fields.filter((field) => Object.hasOwn(record4, field)).map((field) => [field, record4[field]]))]);
9290
- if (stable([...records].sort(([a], [b]) => a < b ? -1 : 1)) !== stable(expected)) return invalid11();
9489
+ if (stable([...records].sort(([a], [b]) => a < b ? -1 : 1)) !== stable(expected)) return invalid12();
9291
9490
  }
9292
9491
  return history;
9293
9492
  }
@@ -9314,33 +9513,33 @@ function readSnapshotHistory(history, input, operation2) {
9314
9513
  };
9315
9514
  }
9316
9515
 
9317
- var snapshotCollection = (catalogue, ref) => catalogue.filter((c) => ref.startsWith(`${c.name}/`)).sort((a, b) => b.name.length - a.name.length)[0], invalid12 = () => {
9516
+ var snapshotCollection = (catalogue, ref) => catalogue.filter((c) => ref.startsWith(`${c.name}/`)).sort((a, b) => b.name.length - a.name.length)[0], invalid13 = () => {
9318
9517
  throw new DataOperationError("unavailable", !0);
9319
- }, object8 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid12() : value;
9518
+ }, object8 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid13() : value;
9320
9519
  function stable2(value) {
9321
9520
  return Array.isArray(value) ? `[${value.map(stable2).join(",")}]` : value && typeof value == "object" ? `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${stable2(entry)}`).join(",")}}` : JSON.stringify(value);
9322
9521
  }
9323
9522
  function schemaText(value) {
9324
- if (typeof value == "string" && !dataText(value)) return invalid12();
9523
+ if (typeof value == "string" && !dataText(value)) return invalid13();
9325
9524
  if (value && typeof value == "object") for (let [key, entry] of Object.entries(value)) {
9326
- if (!dataText(key)) return invalid12();
9525
+ if (!dataText(key)) return invalid13();
9327
9526
  schemaText(entry);
9328
9527
  }
9329
9528
  }
9330
9529
  function validateSnapshotEnvelope(input, repository, name4, bodies = [], timelines = []) {
9331
9530
  try {
9332
9531
  let row = object8(input), legacy = row.format === "data-snapshot.v1";
9333
- if (!["collections,format,name,repository,schemas,version", "collections,format,history,name,repository,schemas,version"].includes(Object.keys(row).sort().join(",")) || !legacy && row.format !== "data-snapshot.v2" || legacy && timelines.length > 0 || row.repository !== repository || row.name !== name4 || !dataVersion(row.version)) return invalid12();
9532
+ if (!["collections,format,name,repository,schemas,version", "collections,format,history,name,repository,schemas,version"].includes(Object.keys(row).sort().join(",")) || !legacy && row.format !== "data-snapshot.v2" || legacy && timelines.length > 0 || row.repository !== repository || row.name !== name4 || !dataVersion(row.version)) return invalid13();
9334
9533
  let schemas2 = object8(row.schemas), collections = object8(row.collections);
9335
9534
  schemaText(schemas2);
9336
9535
  let names = Object.keys(collections);
9337
- for (let subset of [bodies, timelines]) if (new Set(subset).size !== subset.length || subset.some((name5) => !names.includes(name5))) return invalid12();
9338
- if (!names.length || names.join("\0") !== [...names].sort().join("\0") || Object.keys(schemas2).join("\0") !== names.join("\0")) return invalid12();
9536
+ for (let subset of [bodies, timelines]) if (new Set(subset).size !== subset.length || subset.some((name5) => !names.includes(name5))) return invalid13();
9537
+ if (!names.length || names.join("\0") !== [...names].sort().join("\0") || Object.keys(schemas2).join("\0") !== names.join("\0")) return invalid13();
9339
9538
  let catalogue = names.map((name5) => {
9340
9539
  let schema2 = object8(schemas2[name5]);
9341
- if (!validRecordRef(`${name5}/example`) || schema2.name !== name5 || typeof schema2.type != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(schema2.type) || schema2.description !== void 0 && !dataText(schema2.description) || Object.keys(schema2).some((key) => !["name", "type", "description", "display", "fields"].includes(key))) return invalid12();
9540
+ if (!validRecordRef(`${name5}/example`) || schema2.name !== name5 || typeof schema2.type != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(schema2.type) || schema2.description !== void 0 && !dataText(schema2.description) || Object.keys(schema2).some((key) => !["name", "type", "description", "display", "fields"].includes(key))) return invalid13();
9342
9541
  let definitions3 = fields2(schema2.fields, 0, !0);
9343
- if (stable2(definitions3.map(publicField)) !== stable2(schema2.fields)) return invalid12();
9542
+ if (stable2(definitions3.map(publicField)) !== stable2(schema2.fields)) return invalid13();
9344
9543
  let display = parseRecordDisplay2(schema2.display, definitions3);
9345
9544
  return { name: name5, schema: {
9346
9545
  type: schema2.type,
@@ -9351,24 +9550,24 @@ function validateSnapshotEnvelope(input, repository, name4, bodies = [], timelin
9351
9550
  }), types = /* @__PURE__ */ new Map();
9352
9551
  for (let collection of catalogue) {
9353
9552
  let records = collections[collection.name];
9354
- if (!Array.isArray(records)) return invalid12();
9553
+ if (!Array.isArray(records)) return invalid13();
9355
9554
  let previous = "";
9356
9555
  for (let record4 of records) {
9357
9556
  let value = object8(record4);
9358
- if (!validRecordRef(value.$ref) || snapshotCollection(catalogue, value.$ref)?.name !== collection.name || value.$ref <= previous || types.has(value.$ref) || typeof value.$version != "string" || !/^record-v1:[0-9a-f]{64}$/.test(value.$version)) return invalid12();
9557
+ if (!validRecordRef(value.$ref) || snapshotCollection(catalogue, value.$ref)?.name !== collection.name || value.$ref <= previous || types.has(value.$ref) || typeof value.$version != "string" || !/^record-v1:[0-9a-f]{64}$/.test(value.$version)) return invalid13();
9359
9558
  types.set(value.$ref, collection.schema.type), previous = value.$ref;
9360
9559
  }
9361
9560
  }
9362
9561
  for (let collection of catalogue) for (let record4 of collections[collection.name]) {
9363
9562
  let { $ref: _ref, $version: _version, $body, $signals, $timeline, ...values } = record4;
9364
9563
  if (legacy) {
9365
- if (Object.hasOwn(record4, "$signals") || Object.hasOwn(record4, "$timeline")) return invalid12();
9564
+ if (Object.hasOwn(record4, "$signals") || Object.hasOwn(record4, "$timeline")) return invalid13();
9366
9565
  } else if (captureRecordSignals($signals), timelines.includes(collection.name)) {
9367
- if (!Array.isArray($timeline)) return invalid12();
9566
+ if (!Array.isArray($timeline)) return invalid13();
9368
9567
  $timeline.forEach((value) => captureTimeline(value));
9369
- } else if (Object.hasOwn(record4, "$timeline")) return invalid12();
9370
- if (Object.hasOwn(record4, "$body") && (!bodies.includes(collection.name) || typeof $body != "string")) return invalid12();
9371
- validateRecordFields(values, collection.schema.fields, (ref, targets) => types.get(ref) ?? targets[0], !0);
9568
+ } else if (Object.hasOwn(record4, "$timeline")) return invalid13();
9569
+ if (Object.hasOwn(record4, "$body") && (!bodies.includes(collection.name) || typeof $body != "string")) return invalid13();
9570
+ validateRecordFields(values, collection.schema.fields, (ref, targets2) => types.get(ref) ?? targets2[0], !0);
9372
9571
  }
9373
9572
  let normalized = legacy ? Object.fromEntries(Object.entries(collections).map(([collection, records]) => [
9374
9573
  collection,
@@ -9386,7 +9585,7 @@ function validateSnapshotEnvelope(input, repository, name4, bodies = [], timelin
9386
9585
  ...Object.hasOwn(row, "history") ? { history: validateSnapshotHistory(row.history, normalized, row.version) } : {}
9387
9586
  };
9388
9587
  } catch {
9389
- return invalid12();
9588
+ return invalid13();
9390
9589
  }
9391
9590
  }
9392
9591
 
@@ -9397,7 +9596,7 @@ function continuation(value, binding, matching, limit) {
9397
9596
  let { position, ref } = cursorPosition(value, binding, limit);
9398
9597
  return position >= matching.length || ref !== matching[position - 1]?.$ref ? fail6("incompatible cursor") : position;
9399
9598
  }
9400
- function matches(record4, selection2) {
9599
+ function matchesScalar(record4, selection2) {
9401
9600
  return (selection2.signalConditions ?? []).every(([key, statuses]) => {
9402
9601
  if (!Array.isArray(record4.$signals)) return fail6("Signals are unavailable");
9403
9602
  let signal = record4.$signals?.find((row) => row.key === key);
@@ -9420,14 +9619,45 @@ function matches(record4, selection2) {
9420
9619
  });
9421
9620
  });
9422
9621
  }
9622
+ function linkValues(record4, field) {
9623
+ if (!Object.hasOwn(record4, field) || record4[field] === null) return [];
9624
+ let value = record4[field];
9625
+ return Array.isArray(value) ? value.map((item) => typeof item != "string" ? fail6("invalid stored link") : item) : typeof value == "string" ? [value] : fail6("invalid stored link");
9626
+ }
9627
+ function* matches(record4, selection2) {
9628
+ if (!matchesScalar(record4, selection2)) return !1;
9629
+ for (let condition of selection2.linkConditions) {
9630
+ let records = [record4];
9631
+ for (let [index, field] of condition.path.entries()) {
9632
+ let refs = records.flatMap((record5) => linkValues(record5, field).map((value) => parseRecordLink(value) ?? fail6("invalid stored link")));
9633
+ if (index === condition.path.length - 1) {
9634
+ if (!refs.some(({ ref }) => condition.refs.includes(ref))) return !1;
9635
+ break;
9636
+ }
9637
+ let targets2 = [];
9638
+ for (let { ref } of refs) {
9639
+ let target = yield { operation: "lookup", ref };
9640
+ target && targets2.push(target.record);
9641
+ }
9642
+ if (records = targets2, !records.length) return !1;
9643
+ }
9644
+ }
9645
+ return !0;
9646
+ }
9423
9647
  function ordered(a, b, { field, direction }) {
9424
9648
  let left = a[field], right = b[field], missingLeft = left == null, missingRight = right == null, result2 = 0;
9425
9649
  return missingLeft !== missingRight ? missingLeft ? 1 : -1 : (!missingLeft && !missingRight && (result2 = typeof left == "number" && typeof right == "number" ? left - right : typeof left == "boolean" && typeof right == "boolean" ? Number(left) - Number(right) : compare2(left, right), direction === "desc" && (result2 = -result2)), result2 || compare2(a.$ref, b.$ref));
9426
9650
  }
9427
- function* evaluateRecordsQuery(query, catalogue, context, maxRecords, cloneValue, bodyCollections = []) {
9428
- let { version } = context, selections = planIndexQuery(query, catalogue), scanned = /* @__PURE__ */ new Map();
9651
+ function* evaluateRecordsQuery(query, catalogue, context, maxRecords, cloneValue, bodyCollections = [], allowUnknownTerminalRefs = !1) {
9652
+ let { version } = context, selections = planIndexQuery(query, catalogue, { allowUnknownTerminalRefs }), scanned = /* @__PURE__ */ new Map();
9429
9653
  for (let { name: name4 } of selections) scanned.set(name4, yield { operation: "scan", collection: name4 });
9430
- if (maxRecords !== void 0 && selections.reduce((sum, { name: name4, selection: selection2 }) => sum + scanned.get(name4).filter((record4) => matches(record4, selection2)).length, 0) > maxRecords)
9654
+ let selected = /* @__PURE__ */ new Map();
9655
+ for (let { name: name4, selection: selection2 } of selections) {
9656
+ let matching = [];
9657
+ for (let record4 of scanned.get(name4)) (yield* matches(record4, selection2)) && matching.push(record4);
9658
+ selected.set(name4, matching);
9659
+ }
9660
+ if (maxRecords !== void 0 && selections.reduce((sum, { name: name4 }) => sum + selected.get(name4).length, 0) > maxRecords)
9431
9661
  throw new DataOperationError(
9432
9662
  "capacity",
9433
9663
  !1,
@@ -9457,7 +9687,7 @@ function* evaluateRecordsQuery(query, catalogue, context, maxRecords, cloneValue
9457
9687
  let { ref, fragment: fragment2 } = parseRecordLink(value2) ?? fail6("invalid stored link"), target = yield { operation: "lookup", ref };
9458
9688
  if (!target) return fail6("unresolved stored link");
9459
9689
  let nested = link.targets.get(target.collection) ?? fail6("incompatible stored link");
9460
- matches(target.record, nested) && matching.push({ record: target.record, collection: target.collection, selection: nested, fragment: fragment2 });
9690
+ (yield* matches(target.record, nested)) && matching.push({ record: target.record, collection: target.collection, selection: nested, fragment: fragment2 });
9461
9691
  }
9462
9692
  let options = link.targets.values().next().value;
9463
9693
  if (options.explicitOrder && matching.sort((a, b) => ordered(a.record, b.record, options.order)), link.many && !options.explicitLimit && matching.length > 100) return fail6("too many matching linked Records");
@@ -9472,7 +9702,7 @@ function* evaluateRecordsQuery(query, catalogue, context, maxRecords, cloneValue
9472
9702
  }
9473
9703
  let metadata = { version, collections: {} }, results = [];
9474
9704
  for (let { name: name4, selection: selection2 } of selections) {
9475
- let matching = scanned.get(name4).filter((record4) => matches(record4, selection2)).sort((a, b) => ordered(a, b, selection2.order)), binding = indexSelectionBinding(context, name4, selection2), start = selection2.after === void 0 ? 0 : continuation(yield { operation: "open", token: selection2.after }, binding, matching, selection2.limit), end = maxRecords === void 0 ? Math.min(start + selection2.limit, matching.length) : matching.length, records = [];
9705
+ let matching = selected.get(name4).sort((a, b) => ordered(a, b, selection2.order)), binding = indexSelectionBinding(context, name4, selection2), start = selection2.after === void 0 ? 0 : continuation(yield { operation: "open", token: selection2.after }, binding, matching, selection2.limit), end = maxRecords === void 0 ? Math.min(start + selection2.limit, matching.length) : matching.length, records = [];
9476
9706
  for (let index = start; index < end; index++)
9477
9707
  maxRecords !== void 0 && (index - start) % selection2.limit === 0 && (occurrences = 0), records.push(yield* expand(matching[index], name4, selection2));
9478
9708
  let page = selection2.count ? { count: matching.length } : {};
@@ -9493,14 +9723,14 @@ function* evaluateRecordsQuery(query, catalogue, context, maxRecords, cloneValue
9493
9723
 
9494
9724
  var snapshotAcquisitionType = "application/vnd.os.data-snapshot.v2+json", snapshotAcquisitionFormat = "data-snapshot-acquisition.v2", snapshotPairHeader = "Snapshot-Pair", validSnapshotPairToken = (value) => typeof value == "string" && /^snapshot-pair-v1:[0-9a-f]{64}$/.test(value), snapshotArtifactHeader = "Snapshot-Artifact", validSnapshotArtifactToken = (value) => typeof value == "string" && /^snapshot-artifact-v1:[0-9a-f]{64}$/.test(value), snapshotUpdatesProtocol = "os.data-snapshot.updates.v1", snapshotUpdatesCredentialPrefix = "os.member.", snapshotUpdateHint = "update";
9495
9725
 
9496
- var invalid13 = () => {
9726
+ var invalid14 = () => {
9497
9727
  throw new DataOperationError("unavailable", !0);
9498
- }, object9 = (v) => v && typeof v == "object" && !Array.isArray(v) ? v : invalid13(), uuid5 = (v) => typeof v == "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v), time3 = (v) => typeof v == "string" && Number.isFinite(Date.parse(v)), recordVersion = (v) => typeof v == "string" && /^record-v1:[0-9a-f]{64}$/.test(v), keys5 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
9728
+ }, object9 = (v) => v && typeof v == "object" && !Array.isArray(v) ? v : invalid14(), uuid5 = (v) => typeof v == "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v), time3 = (v) => typeof v == "string" && Number.isFinite(Date.parse(v)), recordVersion = (v) => typeof v == "string" && /^record-v1:[0-9a-f]{64}$/.test(v), keys5 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
9499
9729
  function validateAcquisition(input, repository, name4) {
9500
9730
  let row = object9(input), snapshot = object9(row.snapshot);
9501
- if (Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== snapshotAcquisitionFormat || !keys5(snapshot, ["id", "name", "refreshedAt", "repository", "version", "collections", "bodies", "timelines"]) || !uuid5(snapshot.id) || snapshot.repository !== repository || snapshot.name !== name4 || !dataVersion(snapshot.version) || !time3(snapshot.refreshedAt) || !Array.isArray(snapshot.collections) || !snapshot.collections.length || !snapshot.collections.every((c) => typeof c == "string" && validRecordRef(`${c}/example`)) || snapshot.collections.join("\0") !== [...new Set(snapshot.collections)].sort().join("\0") || !Array.isArray(row.changes)) return invalid13();
9731
+ if (Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== snapshotAcquisitionFormat || !keys5(snapshot, ["id", "name", "refreshedAt", "repository", "version", "collections", "bodies", "timelines"]) || !uuid5(snapshot.id) || snapshot.repository !== repository || snapshot.name !== name4 || !dataVersion(snapshot.version) || !time3(snapshot.refreshedAt) || !Array.isArray(snapshot.collections) || !snapshot.collections.length || !snapshot.collections.every((c) => typeof c == "string" && validRecordRef(`${c}/example`)) || snapshot.collections.join("\0") !== [...new Set(snapshot.collections)].sort().join("\0") || !Array.isArray(row.changes)) return invalid14();
9502
9732
  let bodies = snapshot.bodies === void 0 ? [] : snapshot.bodies, timelines = snapshot.timelines === void 0 ? [] : snapshot.timelines;
9503
- for (let subset of [bodies, timelines]) if (!Array.isArray(subset) || subset.some((c) => !snapshot.collections.includes(c)) || subset.join("\0") !== [...new Set(subset)].sort().join("\0")) return invalid13();
9733
+ for (let subset of [bodies, timelines]) if (!Array.isArray(subset) || subset.some((c) => !snapshot.collections.includes(c)) || subset.join("\0") !== [...new Set(subset)].sort().join("\0")) return invalid14();
9504
9734
  return {
9505
9735
  snapshot: { ...snapshot, bodies, timelines },
9506
9736
  changes: validateSnapshotChanges(row.changes, snapshot.collections)
@@ -9508,47 +9738,47 @@ function validateAcquisition(input, repository, name4) {
9508
9738
  }
9509
9739
  function validateSnapshotChanges(input, collections) {
9510
9740
  try {
9511
- if (!Array.isArray(input)) return invalid13();
9741
+ if (!Array.isArray(input)) return invalid14();
9512
9742
  let ids = /* @__PURE__ */ new Set(), unpublished = !1;
9513
9743
  for (let value of input) {
9514
9744
  let c = object9(value), effect = object9(c.effect);
9515
- if (!keys5(c, ["id", "version", "ref", "recordVersion", "effect", "updatedAt", "person", "source", "publication"]) || !uuid5(c.id) || ids.has(c.id) || !dataVersion(c.version) || !validRecordRef(c.ref) || !collections.some((name4) => c.ref.startsWith(`${name4}/`)) || !recordVersion(c.recordVersion) || !time3(c.updatedAt)) return invalid13();
9745
+ if (!keys5(c, ["id", "version", "ref", "recordVersion", "effect", "updatedAt", "person", "source", "publication"]) || !uuid5(c.id) || ids.has(c.id) || !dataVersion(c.version) || !validRecordRef(c.ref) || !collections.some((name4) => c.ref.startsWith(`${name4}/`)) || !recordVersion(c.recordVersion) || !time3(c.updatedAt)) return invalid14();
9516
9746
  if (ids.add(c.id), c.person !== void 0) {
9517
9747
  let person = object9(c.person);
9518
- if (!keys5(person, ["id", "name", "email"]) || !uuid5(person.id) || person.name !== void 0 && !dataText(person.name) || person.email !== void 0 && !dataText(person.email)) return invalid13();
9748
+ if (!keys5(person, ["id", "name", "email"]) || !uuid5(person.id) || person.name !== void 0 && !dataText(person.name) || person.email !== void 0 && !dataText(person.email)) return invalid14();
9519
9749
  }
9520
9750
  if (c.source !== void 0) {
9521
9751
  let source2 = object9(c.source);
9522
- if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid13();
9752
+ if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid14();
9523
9753
  }
9524
9754
  if (c.publication !== void 0) {
9525
9755
  let publication = object9(c.publication);
9526
- if (unpublished || Object.keys(publication).sort().join(",") !== "commit,time" || typeof publication.commit != "string" || !/^[0-9a-f]{40}$/.test(publication.commit) || !time3(publication.time)) return invalid13();
9756
+ if (unpublished || Object.keys(publication).sort().join(",") !== "commit,time" || typeof publication.commit != "string" || !/^[0-9a-f]{40}$/.test(publication.commit) || !time3(publication.time)) return invalid14();
9527
9757
  } else unpublished = !0;
9528
9758
  if (effect.kind === "set") {
9529
- if (Object.keys(effect).sort().join(",") !== "field,kind,value" || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field)) return invalid13();
9759
+ if (Object.keys(effect).sort().join(",") !== "field,kind,value" || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field)) return invalid14();
9530
9760
  } else if (effect.kind === "link" || effect.kind === "unlink") {
9531
- if (!keys5(effect, ["kind", "field", "refs", ...effect.kind === "link" ? ["remove"] : []]) || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field) || !Array.isArray(effect.refs) || !effect.refs.length || effect.refs.length > 1e5 || effect.refs.some((ref) => !validRecordRef(ref)) || new Set(effect.refs).size !== effect.refs.length || effect.remove !== void 0 && (!Array.isArray(effect.remove) || !effect.remove.length || effect.remove.length > 1e5 || effect.remove.some((ref) => !validRecordRef(ref)) || new Set(effect.remove).size !== effect.remove.length)) return invalid13();
9761
+ if (!keys5(effect, ["kind", "field", "refs", ...effect.kind === "link" ? ["remove"] : []]) || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field) || !Array.isArray(effect.refs) || !effect.refs.length || effect.refs.length > 1e5 || effect.refs.some((ref) => !validRecordRef(ref)) || new Set(effect.refs).size !== effect.refs.length || effect.remove !== void 0 && (!Array.isArray(effect.remove) || !effect.remove.length || effect.remove.length > 1e5 || effect.remove.some((ref) => !validRecordRef(ref)) || new Set(effect.remove).size !== effect.remove.length)) return invalid14();
9532
9762
  } else if (effect.kind === "signal") {
9533
- if (Object.keys(effect).sort().join(",") !== "key,kind,value") return invalid13();
9763
+ if (Object.keys(effect).sort().join(",") !== "key,kind,value") return invalid14();
9534
9764
  let value2 = object9(effect.value);
9535
- if (!keys5(value2, ["label", "status", "reason", "related", "asOf", "number"])) return invalid13();
9765
+ if (!keys5(value2, ["label", "status", "reason", "related", "asOf", "number"])) return invalid14();
9536
9766
  let { number, ...assessment } = value2;
9537
9767
  captureSignal({ ...assessment, key: effect.key }), (c.publication || Object.hasOwn(value2, "number")) && captureRecordSignal({ ...value2, key: effect.key });
9538
9768
  } else if (effect.kind === "timeline") {
9539
- if (Object.keys(effect).sort().join(",") !== "entry,kind") return invalid13();
9769
+ if (Object.keys(effect).sort().join(",") !== "entry,kind") return invalid14();
9540
9770
  captureTimeline(effect.entry);
9541
9771
  } else if (effect.kind === "create" || effect.kind === "delete") {
9542
- if (!keys5(effect, ["fields", "kind", "signals", "timeline"])) return invalid13();
9772
+ if (!keys5(effect, ["fields", "kind", "signals", "timeline"])) return invalid14();
9543
9773
  if (object9(effect.fields), Object.hasOwn(effect, "signals") && captureRecordSignals(effect.signals), Object.hasOwn(effect, "timeline")) {
9544
- if (!Array.isArray(effect.timeline)) return invalid13();
9774
+ if (!Array.isArray(effect.timeline)) return invalid14();
9545
9775
  effect.timeline.forEach((value2) => captureTimeline(value2));
9546
9776
  }
9547
- } else return invalid13();
9777
+ } else return invalid14();
9548
9778
  }
9549
9779
  return input;
9550
9780
  } catch {
9551
- return invalid13();
9781
+ return invalid14();
9552
9782
  }
9553
9783
  }
9554
9784
  function materializeSnapshot(envelope, changes, version) {
@@ -9557,44 +9787,44 @@ function materializeSnapshot(envelope, changes, version) {
9557
9787
  let rows = new Map(Object.values(envelope.collections).flat().map((r) => [r.$ref, structuredClone(r)]));
9558
9788
  for (let c of changes) {
9559
9789
  let schema2 = snapshotCollection(envelope.catalogue, c.ref);
9560
- if (!schema2) return invalid13();
9790
+ if (!schema2) return invalid14();
9561
9791
  let effect = c.effect, definitions3 = "field" in effect ? schema2.schema.fields.filter((f) => f.name === effect.field) : schema2.schema.fields;
9562
- if ("field" in effect && !definitions3.length) return invalid13();
9792
+ if ("field" in effect && !definitions3.length) return invalid14();
9563
9793
  let values;
9564
9794
  if (effect.kind === "link" || effect.kind === "unlink") {
9565
9795
  let field = definitions3[0];
9566
- if (field.kind !== "link" || !field.many && effect.kind === "link" && effect.refs.length !== 1) return invalid13();
9567
- let targets = [...effect.refs, ...effect.kind === "link" ? effect.remove ?? [] : []];
9568
- for (let ref of targets) validateRecordFields({ [effect.field]: field.many ? [ref] : ref }, definitions3, (_ref, allowed) => allowed[0], !0);
9796
+ if (field.kind !== "link" || !field.many && effect.kind === "link" && effect.refs.length !== 1) return invalid14();
9797
+ let targets2 = [...effect.refs, ...effect.kind === "link" ? effect.remove ?? [] : []];
9798
+ for (let ref of targets2) validateRecordFields({ [effect.field]: field.many ? [ref] : ref }, definitions3, (_ref, allowed) => allowed[0], !0);
9569
9799
  values = { [effect.field]: field.many ? effect.refs : effect.refs[0] };
9570
9800
  } else values = effect.kind === "set" ? { [effect.field]: effect.value } : "fields" in effect ? effect.fields : {};
9571
9801
  if (effect.kind !== "signal" && effect.kind !== "timeline" && validateRecordFields(
9572
9802
  values,
9573
9803
  definitions3,
9574
- (_ref, targets) => targets[0],
9804
+ (_ref, targets2) => targets2[0],
9575
9805
  !0
9576
9806
  ), !c.publication) continue;
9577
9807
  let prior = rows.get(c.ref);
9578
9808
  if (effect.kind === "set") {
9579
- if (!prior) return invalid13();
9809
+ if (!prior) return invalid14();
9580
9810
  rows.set(c.ref, { ...prior, [effect.field]: effect.value, $version: c.recordVersion });
9581
9811
  } else if (effect.kind === "link" || effect.kind === "unlink") {
9582
- if (!prior) return invalid13();
9812
+ if (!prior) return invalid14();
9583
9813
  let field = definitions3[0], current2 = prior[effect.field], value = field.many ? effect.kind === "link" ? [.../* @__PURE__ */ new Set([...Array.isArray(current2) ? current2 : [], ...effect.refs])].filter((ref) => !effect.remove?.includes(String(ref))) : (Array.isArray(current2) ? current2 : []).filter((ref) => !effect.refs.includes(String(ref))) : effect.kind === "link" ? effect.remove?.includes(effect.refs[0]) ? null : effect.refs[0] : effect.refs.includes(String(current2)) ? null : current2;
9584
9814
  rows.set(c.ref, { ...prior, [effect.field]: value, $version: c.recordVersion });
9585
9815
  } else if (effect.kind === "signal") {
9586
- if (!prior || !effect.value.number) return invalid13();
9816
+ if (!prior || !effect.value.number) return invalid14();
9587
9817
  let signal = captureRecordSignal({ ...effect.value, key: effect.key }), signals = captureRecordSignals(prior.$signals), index = signals.findIndex((row) => row.key === effect.key);
9588
9818
  index < 0 ? signals.push(signal) : signals[index] = signal, rows.set(c.ref, { ...prior, $signals: captureRecordSignals(signals), $version: c.recordVersion });
9589
9819
  } else if (effect.kind === "timeline") {
9590
- if (!prior) return invalid13();
9820
+ if (!prior) return invalid14();
9591
9821
  rows.set(c.ref, {
9592
9822
  ...prior,
9593
9823
  $version: c.recordVersion,
9594
9824
  ...envelope.timelineCollections.includes(schema2.name) ? { $timeline: [...prior.$timeline, effect.entry] } : {}
9595
9825
  });
9596
9826
  } else if (effect.kind === "create") {
9597
- if (prior) return invalid13();
9827
+ if (prior) return invalid14();
9598
9828
  rows.set(c.ref, {
9599
9829
  ...effect.fields,
9600
9830
  $ref: c.ref,
@@ -9603,7 +9833,7 @@ function materializeSnapshot(envelope, changes, version) {
9603
9833
  ...envelope.timelineCollections.includes(schema2.name) ? { $timeline: effect.timeline ?? [] } : {}
9604
9834
  });
9605
9835
  } else {
9606
- if (!prior) return invalid13();
9836
+ if (!prior) return invalid14();
9607
9837
  rows.delete(c.ref);
9608
9838
  }
9609
9839
  }
@@ -9616,7 +9846,7 @@ function materializeSnapshot(envelope, changes, version) {
9616
9846
  collections: Object.fromEntries(envelope.catalogue.map((c) => [c.name, [...rows.values()].filter((r) => snapshotCollection(envelope.catalogue, r.$ref)?.name === c.name).sort((a, b) => a.$ref < b.$ref ? -1 : 1)]))
9617
9847
  }, envelope.repository, envelope.name, envelope.bodyCollections, envelope.timelineCollections), ...envelope.history ? { history: envelope.history } : {} };
9618
9848
  } catch {
9619
- return invalid13();
9849
+ return invalid14();
9620
9850
  }
9621
9851
  }
9622
9852
 
@@ -9672,6 +9902,47 @@ function applySnapshotMutation(envelope, prior, mutation, installation) {
9672
9902
  return { envelope, changes };
9673
9903
  }
9674
9904
 
9905
+ var invalid15 = () => {
9906
+ throw new DataOperationError("unavailable", !0, void 0, "snapshot_cache");
9907
+ };
9908
+ function targets(value, definition, found) {
9909
+ if (value != null) {
9910
+ if (definition.many) {
9911
+ if (!Array.isArray(value)) return invalid15();
9912
+ for (let item of value) targets(item, { ...definition, many: !1 }, found);
9913
+ } else if (definition.kind === "link") {
9914
+ let link = parseRecordLink(value);
9915
+ if (!link) return invalid15();
9916
+ found.add(link.ref);
9917
+ } else if (definition.kind === "object") {
9918
+ if (typeof value != "object" || Array.isArray(value)) return invalid15();
9919
+ for (let field of definition.fields) targets(value[field.name], field, found);
9920
+ } else if (definition.kind === "map") {
9921
+ if (typeof value != "object" || Array.isArray(value)) return invalid15();
9922
+ for (let item of Object.values(value)) targets(item, definition.value, found);
9923
+ }
9924
+ }
9925
+ }
9926
+ function snapshotBacklinkRows(installation, catalogue, collections) {
9927
+ let rows = [];
9928
+ for (let collection of catalogue) for (let record4 of collections[collection.name] ?? []) {
9929
+ let fieldsByTarget = /* @__PURE__ */ new Map();
9930
+ for (let field of collection.schema.fields) {
9931
+ let found = /* @__PURE__ */ new Set();
9932
+ targets(record4[field.name], field, found);
9933
+ for (let target of found) fieldsByTarget.set(target, [...fieldsByTarget.get(target) ?? [], field.name]);
9934
+ }
9935
+ for (let [target, fields4] of fieldsByTarget) rows.push({
9936
+ installation,
9937
+ target,
9938
+ source: record4.$ref,
9939
+ collection: collection.name,
9940
+ fields: fields4
9941
+ });
9942
+ }
9943
+ return rows.sort((left, right) => left.target < right.target ? -1 : left.target > right.target ? 1 : left.source < right.source ? -1 : left.source > right.source ? 1 : 0);
9944
+ }
9945
+
9675
9946
  var unavailable2 = () => {
9676
9947
  throw new DataOperationError("unavailable", !0);
9677
9948
  }, cacheUnavailable = () => new DataOperationError("unavailable", !0, void 0, "snapshot_cache");
@@ -9691,10 +9962,9 @@ function encode(bytes) {
9691
9962
  return btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""));
9692
9963
  }
9693
9964
  async function openSnapshotStore() {
9694
- let opening = indexedDB.open("oddington.data.snapshots.v2", 2);
9965
+ let opening = indexedDB.open("oddington.data.snapshots.v2", 3);
9695
9966
  opening.onupgradeneeded = () => {
9696
- if (opening.result.createObjectStore("bases"), opening.transaction.objectStoreNames.contains("current")) return;
9697
- opening.result.createObjectStore("current"), opening.result.createObjectStore("changes"), opening.result.createObjectStore("records", { keyPath: ["installation", "ref"] }).createIndex("collection", ["installation", "collection"]);
9967
+ opening.result.objectStoreNames.contains("bases") || opening.result.createObjectStore("bases"), opening.result.objectStoreNames.contains("current") || opening.result.createObjectStore("current"), opening.result.objectStoreNames.contains("changes") || opening.result.createObjectStore("changes"), opening.result.objectStoreNames.contains("records") || opening.result.createObjectStore("records", { keyPath: ["installation", "ref"] }).createIndex("collection", ["installation", "collection"]), opening.result.objectStoreNames.contains("backlinks") || opening.result.createObjectStore("backlinks", { keyPath: ["installation", "target", "source"] }).createIndex("installation", "installation");
9698
9968
  };
9699
9969
  let database = await request(opening);
9700
9970
  return database.onversionchange = () => database.close(), {
@@ -9702,7 +9972,7 @@ async function openSnapshotStore() {
9702
9972
  database.close();
9703
9973
  },
9704
9974
  async compact() {
9705
- let transaction = database.transaction(["current", "records", "changes", "bases"], "readwrite"), done = completed(transaction);
9975
+ let transaction = database.transaction(["current", "records", "backlinks", "changes", "bases"], "readwrite"), done = completed(transaction);
9706
9976
  try {
9707
9977
  let pointers = transaction.objectStore("current"), current2 = [];
9708
9978
  for (let key of await request(pointers.getAllKeys())) {
@@ -9711,7 +9981,7 @@ async function openSnapshotStore() {
9711
9981
  }
9712
9982
  let installationIds = new Set(current2.map((value) => value.id).filter(Boolean)), recordIds = new Set(current2.map((value) => value.recordsId ?? value.id).filter(Boolean)), artifactTokens = new Set(current2.map((value) => value.artifactToken).filter(Boolean)), changes = transaction.objectStore("changes"), stale2 = (await request(changes.getAllKeys())).filter((key) => typeof key == "string" && !installationIds.has(key));
9713
9983
  for (let id5 of stale2)
9714
- changes.delete(id5), recordIds.has(id5) || transaction.objectStore("records").delete(IDBKeyRange.bound([id5], [id5, []]));
9984
+ changes.delete(id5), recordIds.has(id5) || (transaction.objectStore("records").delete(IDBKeyRange.bound([id5], [id5, []])), transaction.objectStore("backlinks").delete(IDBKeyRange.bound([id5], [id5, []])));
9715
9985
  let bases = transaction.objectStore("bases");
9716
9986
  for (let key of await request(bases.getAllKeys()))
9717
9987
  typeof key == "string" && !artifactTokens.has(key) && bases.delete(key);
@@ -9726,27 +9996,27 @@ async function openSnapshotStore() {
9726
9996
  }
9727
9997
  },
9728
9998
  async current(partition) {
9729
- let transaction = database.transaction(["current", "records", "changes", "bases"], "readonly"), done = completed(transaction), value = await request(transaction.objectStore("current").get(partition));
9999
+ let transaction = database.transaction(["current", "records", "backlinks", "changes", "bases"], "readonly"), done = completed(transaction), value = await request(transaction.objectStore("current").get(partition));
9730
10000
  if (!value) {
9731
10001
  await done;
9732
10002
  return;
9733
10003
  }
9734
10004
  let recordsId = value.recordsId ?? value.id;
9735
- if (value.format !== "data-snapshot.v2" || !Array.isArray(value.timelineCollections) || value.partition !== partition || !value.id || !recordsId || !value.snapshotId || value.pairToken !== "" && !validSnapshotPairToken(value.pairToken) || !validSnapshotArtifactToken(value.artifactToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
10005
+ if (value.format !== "data-snapshot.v2" || !Array.isArray(value.timelineCollections) || value.partition !== partition || !value.id || !recordsId || !value.snapshotId || value.pairToken !== "" && !validSnapshotPairToken(value.pairToken) || !validSnapshotArtifactToken(value.artifactToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !Number.isSafeInteger(value.backlinkCount) || value.backlinkCount < 0 || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
9736
10006
  await done;
9737
10007
  return;
9738
10008
  }
9739
10009
  let changes = await request(transaction.objectStore("changes").get(value.id)), complete = !!await request(transaction.objectStore("bases").getKey(value.artifactToken)) && Array.isArray(changes) && changes.length === value.changeCount;
9740
10010
  for (let collection of value.catalogue)
9741
10011
  await request(transaction.objectStore("records").index("collection").count([recordsId, collection.name])) !== value.counts[collection.name] && (complete = !1);
9742
- return await done, complete ? { ...value, recordsId } : void 0;
10012
+ return await request(transaction.objectStore("backlinks").index("installation").count(recordsId)) !== value.backlinkCount && (complete = !1), await done, complete ? { ...value, recordsId } : void 0;
9743
10013
  },
9744
10014
  async base(installation) {
9745
10015
  let transaction = database.transaction("bases", "readonly"), done = completed(transaction), base = await request(transaction.objectStore("bases").get(installation.artifactToken));
9746
10016
  return await done, base;
9747
10017
  },
9748
10018
  async install(partition, pairToken, envelope, changes, assertCurrent, snapshotId, artifact, unchangedRecords) {
9749
- let id5 = crypto.randomUUID(), recordsId = unchangedRecords?.recordsId ?? id5, installation = {
10019
+ let id5 = crypto.randomUUID(), recordsId = unchangedRecords?.recordsId ?? id5, backlinkRows = unchangedRecords ? void 0 : snapshotBacklinkRows(recordsId, envelope.catalogue, envelope.collections), installation = {
9750
10020
  id: id5,
9751
10021
  recordsId,
9752
10022
  partition,
@@ -9760,16 +10030,18 @@ async function openSnapshotStore() {
9760
10030
  bodyCollections: envelope.bodyCollections,
9761
10031
  timelineCollections: envelope.timelineCollections,
9762
10032
  catalogue: envelope.catalogue,
10033
+ backlinkCount: unchangedRecords?.backlinkCount ?? backlinkRows.length,
9763
10034
  changeCount: changes.length,
9764
10035
  cursorKey: unchangedRecords?.cursorKey ?? crypto.getRandomValues(new Uint8Array(32)),
9765
10036
  ...unchangedRecords ? { queryIdentity: unchangedRecords.queryIdentity ?? unchangedRecords.id } : {},
9766
10037
  counts: Object.fromEntries(Object.entries(envelope.collections).map(([name4, rows]) => [name4, rows.length]))
9767
- }, transaction = database.transaction(["current", "records", "changes", "bases"], "readwrite"), done = completed(transaction);
10038
+ }, transaction = database.transaction(["current", "records", "backlinks", "changes", "bases"], "readwrite"), done = completed(transaction);
9768
10039
  try {
9769
10040
  assertCurrent(), transaction.objectStore("bases").put(artifact.base, artifact.token);
9770
10041
  let records = transaction.objectStore("records");
9771
10042
  if (!unchangedRecords) for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
9772
10043
  records.put({ installation: recordsId, collection, ref: record4.$ref, record: record4 });
10044
+ if (backlinkRows) for (let row of backlinkRows) transaction.objectStore("backlinks").put(row);
9773
10045
  return await request(transaction.objectStore("changes").put(changes, installation.id)), await request(transaction.objectStore("current").put(installation, partition)), assertCurrent(), await done, assertCurrent(), installation;
9774
10046
  } catch (error) {
9775
10047
  try {
@@ -9785,7 +10057,7 @@ async function openSnapshotStore() {
9785
10057
  transaction.objectStore("changes").delete(installation.id), (await request(transaction.objectStore("current").get(installation.partition)))?.id === installation.id && transaction.objectStore("current").delete(installation.partition), await done;
9786
10058
  },
9787
10059
  async mutate(installation, mutation, assertCurrent) {
9788
- let transaction = database.transaction(["current", "records", "changes"], "readwrite"), done = completed(transaction);
10060
+ let transaction = database.transaction(["current", "records", "backlinks", "changes"], "readwrite"), done = completed(transaction);
9789
10061
  try {
9790
10062
  assertCurrent();
9791
10063
  let records = transaction.objectStore("records"), collections = {}, prior = await request(transaction.objectStore("changes").get(installation.id));
@@ -9804,18 +10076,20 @@ async function openSnapshotStore() {
9804
10076
  timelineCollections: installation.timelineCollections,
9805
10077
  catalogue: installation.catalogue,
9806
10078
  collections
9807
- }, prior, mutation, installation), id5 = crypto.randomUUID(), recordsId = mutation.kind === "publish" ? id5 : installation.recordsId, next = {
10079
+ }, prior, mutation, installation), id5 = crypto.randomUUID(), recordsId = mutation.kind === "publish" ? id5 : installation.recordsId, backlinkRows = mutation.kind === "publish" ? snapshotBacklinkRows(recordsId, envelope.catalogue, envelope.collections) : void 0, next = {
9808
10080
  ...installation,
9809
10081
  id: id5,
9810
10082
  recordsId,
9811
10083
  pairToken: "",
9812
10084
  version: envelope.version,
9813
10085
  queryIdentity: mutation.kind === "publish" ? id5 : installation.queryIdentity ?? installation.id,
10086
+ backlinkCount: backlinkRows?.length ?? installation.backlinkCount,
9814
10087
  changeCount: changes.length,
9815
10088
  counts: Object.fromEntries(Object.entries(envelope.collections).map(([name4, rows]) => [name4, rows.length]))
9816
10089
  };
9817
10090
  if (mutation.kind === "publish") for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
9818
10091
  records.put({ installation: recordsId, collection, ref: record4.$ref, record: record4 });
10092
+ if (backlinkRows) for (let row of backlinkRows) transaction.objectStore("backlinks").put(row);
9819
10093
  return transaction.objectStore("changes").put(changes, id5), (await request(transaction.objectStore("current").get(installation.partition)))?.id === installation.id && transaction.objectStore("current").put(next, installation.partition), assertCurrent(), await done, assertCurrent(), next;
9820
10094
  } catch (error) {
9821
10095
  try {
@@ -9848,7 +10122,8 @@ async function openSnapshotStore() {
9848
10122
  },
9849
10123
  maxRecords,
9850
10124
  (value) => value,
9851
- body ? installation.bodyCollections : void 0
10125
+ body ? installation.bodyCollections : void 0,
10126
+ !0
9852
10127
  );
9853
10128
  try {
9854
10129
  let step = evaluation.next();
@@ -9886,6 +10161,62 @@ async function openSnapshotStore() {
9886
10161
  throw await done?.catch(() => {
9887
10162
  }), error;
9888
10163
  }
10164
+ },
10165
+ async backlinks(installation, ref, options) {
10166
+ let key = await crypto.subtle.importKey("raw", installation.cursorKey, "AES-GCM", !1, ["encrypt", "decrypt"]), factsTransaction = database.transaction("backlinks", "readonly"), factsDone = completed(factsTransaction), facts2 = factsTransaction.objectStore("backlinks"), rows = await request(facts2.getAll(IDBKeyRange.bound(
10167
+ [installation.recordsId, ref],
10168
+ [installation.recordsId, ref, []]
10169
+ ))), backlinkCount = await request(facts2.index("installation").count(installation.recordsId));
10170
+ if (await factsDone, backlinkCount !== installation.backlinkCount) return unavailable2();
10171
+ let binding = JSON.stringify({
10172
+ workspaceId: installation.partition,
10173
+ repository: installation.partition,
10174
+ identity: installation.queryIdentity ?? installation.id,
10175
+ version: installation.version,
10176
+ operation: "records.backlinks",
10177
+ ref,
10178
+ limit: options.limit
10179
+ }), start = 0;
10180
+ if (options.after !== void 0) {
10181
+ let payload;
10182
+ try {
10183
+ let bytes = Uint8Array.from(atob(options.after), (c) => c.charCodeAt(0)), opened = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12) }, key, bytes.slice(12));
10184
+ payload = JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(opened));
10185
+ } catch {
10186
+ throw new DataOperationError("invalid_query");
10187
+ }
10188
+ let cursor = cursorPosition(payload, binding, options.limit);
10189
+ if (cursor.position >= rows.length || rows[cursor.position - 1]?.source !== cursor.ref)
10190
+ throw new RecordValidationError("Invalid Records query: incompatible cursor");
10191
+ start = cursor.position;
10192
+ }
10193
+ let end = Math.min(start + options.limit, rows.length), page = rows.slice(start, end), recordsTransaction = database.transaction("records", "readonly"), recordsDone = completed(recordsTransaction), records = recordsTransaction.objectStore("records"), found = await Promise.all(page.map((row) => request(records.get([installation.recordsId, row.source]))));
10194
+ if (await recordsDone, found.some((row, index) => !row || row.collection !== page[index].collection || row.ref !== page[index].source))
10195
+ return unavailable2();
10196
+ let result2 = found.map((row, index) => {
10197
+ let {
10198
+ $body: _body,
10199
+ $path: _path,
10200
+ $timeline: _timeline,
10201
+ $fragment: _fragment,
10202
+ $backlinks: _backlinks,
10203
+ ...structured
10204
+ } = row.record;
10205
+ return {
10206
+ ...structured,
10207
+ $signals: Array.isArray(structured.$signals) ? structured.$signals : [],
10208
+ $backlinks: [...page[index].fields]
10209
+ };
10210
+ }), metadata = { version: installation.version };
10211
+ if (end < rows.length) {
10212
+ let iv = crypto.getRandomValues(new Uint8Array(12)), payload = { format: 1, binding, position: end, ref: rows[end - 1].source }, sealed = new Uint8Array(await crypto.subtle.encrypt(
10213
+ { name: "AES-GCM", iv },
10214
+ key,
10215
+ new TextEncoder().encode(JSON.stringify(payload))
10216
+ ));
10217
+ metadata.next = encode(new Uint8Array([...iv, ...sealed]));
10218
+ }
10219
+ return { $meta: metadata, records: result2 };
9889
10220
  }
9890
10221
  };
9891
10222
  }
@@ -10156,19 +10487,19 @@ function captureSelection(input) {
10156
10487
  }
10157
10488
  }
10158
10489
 
10159
- var invalid14 = () => {
10490
+ var invalid16 = () => {
10160
10491
  throw new DataOperationError("invalid_query");
10161
10492
  };
10162
10493
  function captureSnapshotAll(query, options) {
10163
10494
  let properties = dataProperties(options);
10164
- return Object.keys(properties).some((key) => !["maxRecords", "body", "timeline"].includes(key)) || properties.body && properties.body.value !== !0 || properties.timeline && properties.timeline.value !== !0 ? invalid14() : { ...captureRecordsAll(query, { maxRecords: properties.maxRecords?.value }), body: properties.body?.value === !0, timeline: properties.timeline?.value === !0 };
10495
+ return Object.keys(properties).some((key) => !["maxRecords", "body", "timeline"].includes(key)) || properties.body && properties.body.value !== !0 || properties.timeline && properties.timeline.value !== !0 ? invalid16() : { ...captureRecordsAll(query, { maxRecords: properties.maxRecords?.value }), body: properties.body?.value === !0, timeline: properties.timeline?.value === !0 };
10165
10496
  }
10166
10497
  var safeName = (value) => typeof value == "string" && /^[a-z0-9][a-z0-9._-]{0,127}$/.test(value) && !value.includes("..");
10167
10498
  function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore, connect = (url, protocols) => new WebSocket(url, protocols)) {
10168
10499
  let pending = /* @__PURE__ */ new WeakMap(), maintenance = /* @__PURE__ */ new WeakMap();
10169
10500
  return async function(input) {
10170
10501
  let properties = dataProperties(input), repository = properties.repository?.value, snapshot = properties.snapshot?.value;
10171
- if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid14();
10502
+ if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid16();
10172
10503
  let authority2 = await resolve(), invalidated = !1, stopLive, assertCurrent = () => {
10173
10504
  if (invalidated || authority2.signal.aborted || !authority2.isCurrent() || !authority2.refresh && authority2.expiresAt <= Date.now())
10174
10505
  throw invalidated = !0, stopLive?.(), new DataOperationError("context_unavailable");
@@ -10339,8 +10670,8 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
10339
10670
  });
10340
10671
  let store;
10341
10672
  try {
10342
- let selections = planIndexQuery(captured, pinned.catalogue), checkTimeline = (collection, selection2) => {
10343
- if ((timeline || selection2.timeline) && !pinned.timelineCollections.includes(collection)) return invalid14();
10673
+ let selections = planIndexQuery(captured, pinned.catalogue, { allowUnknownTerminalRefs: !0 }), checkTimeline = (collection, selection2) => {
10674
+ if ((timeline || selection2.timeline) && !pinned.timelineCollections.includes(collection)) return invalid16();
10344
10675
  for (let link of selection2.links) for (let [name4, nested] of link.targets) checkTimeline(name4, nested);
10345
10676
  };
10346
10677
  for (let { name: name4, selection: selection2 } of selections) checkTimeline(name4, selection2);
@@ -10412,13 +10743,20 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
10412
10743
  publication || (publication = { id: crypto.randomUUID() }, publications.set(key, publication)), await write(() => mutate("publish", { selected, ...metadata, publicationId: publication.id }, selected, publication));
10413
10744
  }
10414
10745
  }, records: {
10746
+ backlinks: async (ref, options) => {
10747
+ let captured = captureRecordsBacklinksInput(ref, options);
10748
+ return checkDataRequestSize({ repository, operation: "records.backlinks", ref: captured.ref, options: captured.options }), writes.then(() => {
10749
+ let pinned = installation;
10750
+ return localRead((store) => store.backlinks(pinned, captured.ref, captured.options));
10751
+ });
10752
+ },
10415
10753
  read: async (ref, ...extra) => {
10416
10754
  if (typeof ref != "string" || extra.length > 1) return Promise.reject(new DataOperationError("invalid_query"));
10417
10755
  let { body, timeline } = captureRecordsReadOptions(extra[0]), [captured] = captureRecordsReadRefs([ref]);
10418
10756
  return snapshotCollection(installation.catalogue, captured) ? writes.then(() => {
10419
10757
  let pinned = installation;
10420
10758
  return localRead(async (store) => {
10421
- if (timeline && !pinned.timelineCollections.includes(snapshotCollection(pinned.catalogue, captured).name)) return invalid14();
10759
+ if (timeline && !pinned.timelineCollections.includes(snapshotCollection(pinned.catalogue, captured).name)) return invalid16();
10422
10760
  let record4 = await store.read(pinned, captured);
10423
10761
  if (!record4) return record4;
10424
10762
  let { $body, $timeline, ...structured } = record4;
@@ -10473,6 +10811,14 @@ var genericData = {
10473
10811
  query: queryRecords,
10474
10812
  ...recordPagination(queryRecords),
10475
10813
  all: async (query, options) => send3({ operation: "records.all", ...captureRecordsAll(query, options) }),
10814
+ backlinks: async (ref, options) => {
10815
+ let captured = captureRecordsBacklinksInput(ref, options);
10816
+ return send3({
10817
+ operation: "records.backlinks",
10818
+ ref: captured.ref,
10819
+ ...options === void 0 ? {} : { options: captured.options }
10820
+ });
10821
+ },
10476
10822
  search: async (query, options) => send3({ operation: "records.search", ...captureRecordsSearchInput(query, options) })
10477
10823
  },
10478
10824
  changes(options) {
@@ -10547,7 +10893,7 @@ var genericData = {
10547
10893
  }
10548
10894
  }, data = genericData;
10549
10895
 
10550
- var MAX_BYTES = 16 * 1024 * 1024, PART_BYTES = 8 * 1024 * 1024, METADATA_BYTES = 4096, RESULT_BYTES = 16 * 1024, CONTROL_RESULT_BYTES = 128 * 1024, TIMEOUT_MS = 3e4, MAX_ACTIVE = 4, ATTEMPTS = 2, active = 0, waiters = [], invalid15 = () => new FileOperationError("invalid_input", 400), unavailable4 = () => new FileOperationError("unavailable", 503, !0), failures = {
10896
+ var MAX_BYTES = 16 * 1024 * 1024, PART_BYTES = 8 * 1024 * 1024, METADATA_BYTES = 4096, RESULT_BYTES = 16 * 1024, CONTROL_RESULT_BYTES = 128 * 1024, TIMEOUT_MS = 3e4, MAX_ACTIVE = 4, ATTEMPTS = 2, active = 0, waiters = [], invalid17 = () => new FileOperationError("invalid_input", 400), unavailable4 = () => new FileOperationError("unavailable", 503, !0), failures = {
10551
10897
  400: ["invalid_input", "unsupported_context"],
10552
10898
  401: ["unauthenticated"],
10553
10899
  403: ["access_denied"],
@@ -10703,7 +11049,7 @@ async function send(suffix, init2, descriptor, initial, parent) {
10703
11049
  throw unavailable4();
10704
11050
  }
10705
11051
  function idPath(id5) {
10706
- if (typeof id5 != "string" || !FILE_ID_PATTERN.test(id5)) throw invalid15();
11052
+ if (typeof id5 != "string" || !FILE_ID_PATTERN.test(id5)) throw invalid17();
10707
11053
  return `/${id5}`;
10708
11054
  }
10709
11055
  async function multipartCreate(input, metadata, exchange, release, upload, expectedSha256) {
@@ -10746,18 +11092,18 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
10746
11092
  if (!chunk || offset === chunk.byteLength) {
10747
11093
  chunk = void 0, offset = 0;
10748
11094
  let value2 = await next();
10749
- if (value2.done || !(value2.value instanceof Uint8Array) || (chunk = value2.value, chunk.byteLength > metadata.size - sent - filled)) throw invalid15();
11095
+ if (value2.done || !(value2.value instanceof Uint8Array) || (chunk = value2.value, chunk.byteLength > metadata.size - sent - filled)) throw invalid17();
10750
11096
  }
10751
11097
  let take = Math.min(length - filled, chunk.byteLength - offset);
10752
11098
  part.set(chunk.subarray(offset, offset + take), filled), filled += take, offset += take, offset === chunk.byteLength && (chunk = void 0, offset = 0);
10753
11099
  }
10754
11100
  }
10755
- if (part.byteLength !== length) throw invalid15();
11101
+ if (part.byteLength !== length) throw invalid17();
10756
11102
  if (reader && sent + length === metadata.size)
10757
11103
  for (lastProgress = Date.now(); ; ) {
10758
11104
  let value2 = await next();
10759
11105
  if (value2.done) break;
10760
- if (!(value2.value instanceof Uint8Array) || value2.value.byteLength) throw invalid15();
11106
+ if (!(value2.value instanceof Uint8Array) || value2.value.byteLength) throw invalid17();
10761
11107
  }
10762
11108
  let value = await request3((signal) => exchange(`${route}/part`, {
10763
11109
  method: "POST",
@@ -10771,7 +11117,7 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
10771
11117
  }
10772
11118
  if (upload) for (let name4 of Object.keys(upload.file.enrichments)) {
10773
11119
  let bytes = await request3(() => upload.enrichment(name4));
10774
- if (bytes.byteLength !== upload.file.enrichments[name4].size || bytes.byteLength > MAX_BYTES) throw invalid15();
11120
+ if (bytes.byteLength !== upload.file.enrichments[name4].size || bytes.byteLength > MAX_BYTES) throw invalid17();
10775
11121
  await request3((signal) => exchange(`${route}/enrichments/${encodeURIComponent(name4)}`, {
10776
11122
  method: "POST",
10777
11123
  headers: { "content-type": "application/octet-stream", "x-os-transfer": ticket },
@@ -10813,7 +11159,7 @@ async function operation(work, initial, parent) {
10813
11159
  function contentPath(id5, name4) {
10814
11160
  let path = idPath(id5);
10815
11161
  if (name4 === void 0) return `${path}/content`;
10816
- if (!safeEnrichmentName(name4)) throw invalid15();
11162
+ if (!safeEnrichmentName(name4)) throw invalid17();
10817
11163
  return `${path}/enrichments/${encodeURIComponent(name4)}/content`;
10818
11164
  }
10819
11165
  async function read(id5, names) {
@@ -10822,12 +11168,12 @@ async function read(id5, names) {
10822
11168
  let path = contentPath(id5, names);
10823
11169
  return operation((context2, signal) => send(path, { method: "GET" }, !1, context2, signal), context);
10824
11170
  }
10825
- if (!Array.isArray(names)) throw invalid15();
11171
+ if (!Array.isArray(names)) throw invalid17();
10826
11172
  let distinct = [], seen = /* @__PURE__ */ new Set();
10827
11173
  for (let name4 of names) {
10828
- if (typeof name4 != "string" || !safeEnrichmentName(name4)) throw invalid15();
11174
+ if (typeof name4 != "string" || !safeEnrichmentName(name4)) throw invalid17();
10829
11175
  if (!seen.has(name4)) {
10830
- if (seen.size === 16) throw invalid15();
11176
+ if (seen.size === 16) throw invalid17();
10831
11177
  seen.add(name4), distinct.push(name4);
10832
11178
  }
10833
11179
  }
@@ -10867,9 +11213,9 @@ var files = {
10867
11213
  async create(input, options) {
10868
11214
  let context = await resolveFilesContext();
10869
11215
  if (!input || typeof input != "object" || Array.isArray(input) || Object.keys(input).some((key) => !["file", "size", "path", "name", "storage", "mediaType"].includes(key)) || options !== void 0 && (!options || typeof options != "object" || Array.isArray(options) || Object.keys(options).some((key) => key !== "requestKey")))
10870
- throw invalid15();
11216
+ throw invalid17();
10871
11217
  let blob = input.file instanceof Blob, array3 = input.file instanceof Uint8Array, stream = input.file instanceof ReadableStream;
10872
- if (!blob && !array3 && !stream) throw invalid15();
11218
+ if (!blob && !array3 && !stream) throw invalid17();
10873
11219
  let intrinsic = blob ? input.file.size : array3 ? input.file.byteLength : void 0;
10874
11220
  if (intrinsic !== void 0 && input.size !== void 0 && input.size !== intrinsic)
10875
11221
  throw !Number.isSafeInteger(input.size) || input.size < 0 ? new FileOperationError("invalid_input", 400, !1, { reason: "invalid_size" }) : new FileOperationError(
@@ -10890,7 +11236,7 @@ var files = {
10890
11236
  }, FILE_ORIGINAL_MAX_BYTES);
10891
11237
  if (!context.local && !context.localFiles && metadata.storage === "local") throw new FileOperationError("unsupported_context", 400);
10892
11238
  let header = encodeURIComponent(JSON.stringify(metadata));
10893
- if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid15();
11239
+ if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid17();
10894
11240
  let release = await acquireSlot(context.signal);
10895
11241
  if (context.localFiles && !routineTransport() && metadata.size > MAX_BYTES)
10896
11242
  try {
@@ -10941,7 +11287,7 @@ var files = {
10941
11287
  },
10942
11288
  async enrich(input) {
10943
11289
  let context = await resolveFilesContext();
10944
- if (!input || typeof input != "object" || Array.isArray(input) || Object.keys(input).some((key) => !["file", "name", "content", "mediaType", "replace"].includes(key)) || typeof input.content != "string" && !(input.content instanceof Uint8Array)) throw invalid15();
11290
+ if (!input || typeof input != "object" || Array.isArray(input) || Object.keys(input).some((key) => !["file", "name", "content", "mediaType", "replace"].includes(key)) || typeof input.content != "string" && !(input.content instanceof Uint8Array)) throw invalid17();
10945
11291
  let path = `${idPath(input.file)}/enrichments`;
10946
11292
  if (typeof input.content == "string" ? input.content.length > MAX_BYTES : input.content.byteLength > MAX_BYTES)
10947
11293
  throw new FileOperationError("request_too_large", 413);
@@ -10958,7 +11304,7 @@ var files = {
10958
11304
  ...input.mediaType === void 0 ? {} : { mediaType: input.mediaType },
10959
11305
  ...input.replace === void 0 ? {} : { replace: input.replace }
10960
11306
  }, MAX_BYTES), header = encodeURIComponent(JSON.stringify(metadata));
10961
- if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid15();
11307
+ if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid17();
10962
11308
  let result2 = await send(path, { method: "POST", headers: {
10963
11309
  "content-type": "application/octet-stream",
10964
11310
  "x-os-enrichment": header
@@ -13106,15 +13452,19 @@ function routinePublicationClient2(options = {}) {
13106
13452
  if (!response2.ok) throw new InboxPublicationError(result2.error);
13107
13453
  return result2;
13108
13454
  }
13455
+ let transport = {
13456
+ async publish(body) {
13457
+ return await send3("publish", body);
13458
+ },
13459
+ ...installed2 ? { async wait(body) {
13460
+ return await send3("publish", body);
13461
+ } } : {},
13462
+ async resolve(body) {
13463
+ await send3("resolve", body);
13464
+ }
13465
+ };
13109
13466
  return {
13110
- ...createInboxPublisher({
13111
- async publish(body) {
13112
- return await send3("publish", body);
13113
- },
13114
- async resolve(body) {
13115
- await send3("resolve", body);
13116
- }
13117
- }),
13467
+ ...createInboxPublisher(transport),
13118
13468
  async check(body) {
13119
13469
  await send3("check", { requestKey: body.requestKey, item: enforcePublicationSize(validatePublication(body.item)) });
13120
13470
  }