@oddington/sdk 0.1.74 → 0.1.76

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 invalid13 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
2101
+ let invalid14 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
2102
2102
  if (Settings.throwOnInvalid)
2103
- throw new InvalidDurationError(invalid13);
2103
+ throw new InvalidDurationError(invalid14);
2104
2104
  return new _Duration({
2105
- invalid: invalid13
2105
+ invalid: invalid14
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 invalid13 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
2372
+ let invalid14 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
2373
2373
  if (Settings.throwOnInvalid)
2374
- throw new InvalidIntervalError(invalid13);
2374
+ throw new InvalidIntervalError(invalid14);
2375
2375
  return new _Interval({
2376
- invalid: invalid13
2376
+ invalid: invalid14
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 invalid13 = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
3234
- if (invalid13)
3235
- return DateTime.invalid(invalid13);
3233
+ let invalid14 = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
3234
+ if (invalid14)
3235
+ return DateTime.invalid(invalid14);
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, invalid13 = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (zone.isValid ? null : unsupportedZone(zone));
3263
+ let zone = config.zone || Settings.defaultZone, invalid14 = 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 (!invalid13)
3266
+ if (!invalid14)
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), invalid13 = Number.isNaN(c.year) ? new Invalid("invalid input") : null, c = invalid13 ? null : c, o = invalid13 ? null : ot;
3271
+ c = tsToObj(this.ts, ot), invalid14 = Number.isNaN(c.year) ? new Invalid("invalid input") : null, c = invalid14 ? null : c, o = invalid14 ? null : ot;
3272
3272
  }
3273
- this._zone = zone, this.loc = config.loc || Locale.create(), this.invalid = invalid13, 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 = invalid14, 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), invalid13 = higherOrderInvalid || hasInvalidTimeData(normalized);
3353
- if (invalid13)
3354
- return _DateTime.invalid(invalid13);
3352
+ let higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid14 = higherOrderInvalid || hasInvalidTimeData(normalized);
3353
+ if (invalid14)
3354
+ return _DateTime.invalid(invalid14);
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, invalid13] = parseFromTokens(localeToUse, text5, fmt);
3386
- return invalid13 ? _DateTime.invalid(invalid13) : parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text5, specificOffset);
3385
+ }), [vals, parsedZone, specificOffset, invalid14] = parseFromTokens(localeToUse, text5, fmt);
3386
+ return invalid14 ? _DateTime.invalid(invalid14) : 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 invalid13 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
3398
+ let invalid14 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
3399
3399
  if (Settings.throwOnInvalid)
3400
- throw new InvalidDateTimeError(invalid13);
3400
+ throw new InvalidDateTimeError(invalid14);
3401
3401
  return new _DateTime({
3402
- invalid: invalid13
3402
+ invalid: invalid14
3403
3403
  });
3404
3404
  }
3405
3405
  static isDateTime(o) {
@@ -5039,40 +5039,40 @@ var FileOperationError = class extends Error {
5039
5039
  };
5040
5040
  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;
5041
5041
  function parseFileDescriptor(value) {
5042
- let invalid13 = () => {
5042
+ let invalid14 = () => {
5043
5043
  throw new FileOperationError("unavailable", 503, !0);
5044
5044
  };
5045
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid13();
5045
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid14();
5046
5046
  let f = value;
5047
- 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 invalid13();
5047
+ 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 invalid14();
5048
5048
  for (let [name2, descriptor] of Object.entries(f.enrichments)) {
5049
- if (!safeEnrichmentName(name2)) return invalid13();
5049
+ if (!safeEnrichmentName(name2)) return invalid14();
5050
5050
  parseEnrichmentDescriptor(descriptor);
5051
5051
  }
5052
- return new TextEncoder().encode(JSON.stringify(f)).byteLength > 16 * 1024 ? invalid13() : f;
5052
+ return new TextEncoder().encode(JSON.stringify(f)).byteLength > 16 * 1024 ? invalid14() : f;
5053
5053
  }
5054
5054
  function parseEnrichmentDescriptor(value) {
5055
- let invalid13 = () => {
5055
+ let invalid14 = () => {
5056
5056
  throw new FileOperationError("unavailable", 503, !0);
5057
5057
  };
5058
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid13();
5058
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid14();
5059
5059
  let d = value;
5060
- 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) ? invalid13() : d;
5060
+ 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) ? invalid14() : d;
5061
5061
  }
5062
5062
  function safeEnrichmentName(value) {
5063
5063
  return safeFileName(value) && !/^original(?:\.|$)/i.test(value);
5064
5064
  }
5065
5065
  function parseFileEnrichMetadata(value, maxBytes) {
5066
- let invalid13 = (reason = "invalid_metadata") => {
5066
+ let invalid14 = (reason = "invalid_metadata") => {
5067
5067
  throw new FileOperationError("invalid_input", 400, !1, { reason });
5068
5068
  };
5069
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid13();
5069
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid14();
5070
5070
  let d = value;
5071
- if (Object.keys(d).some((key) => !["name", "size", "mediaType", "replace"].includes(key))) return invalid13();
5072
- if (!safeEnrichmentName(d.name)) return invalid13("invalid_enrichment_name");
5073
- if (!Number.isSafeInteger(d.size) || d.size < 0) return invalid13("invalid_size");
5074
- if (d.mediaType !== void 0 && (typeof d.mediaType != "string" || d.mediaType.length > 255 || /[\u0000-\u001f\u007f]/.test(d.mediaType))) return invalid13("invalid_media_type");
5075
- if (d.replace !== void 0 && (typeof d.replace != "string" || !/^[0-9a-f]{64}$/.test(d.replace))) return invalid13("invalid_replacement");
5071
+ if (Object.keys(d).some((key) => !["name", "size", "mediaType", "replace"].includes(key))) return invalid14();
5072
+ if (!safeEnrichmentName(d.name)) return invalid14("invalid_enrichment_name");
5073
+ if (!Number.isSafeInteger(d.size) || d.size < 0) return invalid14("invalid_size");
5074
+ if (d.mediaType !== void 0 && (typeof d.mediaType != "string" || d.mediaType.length > 255 || /[\u0000-\u001f\u007f]/.test(d.mediaType))) return invalid14("invalid_media_type");
5075
+ if (d.replace !== void 0 && (typeof d.replace != "string" || !/^[0-9a-f]{64}$/.test(d.replace))) return invalid14("invalid_replacement");
5076
5076
  if (d.size > maxBytes) throw new FileOperationError(
5077
5077
  "request_too_large",
5078
5078
  413,
@@ -5105,42 +5105,42 @@ function isCanonicalOriginalMediaType(value) {
5105
5105
  }
5106
5106
  }
5107
5107
  function parseFileUpdate(value) {
5108
- let invalid13 = (reason = "invalid_metadata") => {
5108
+ let invalid14 = (reason = "invalid_metadata") => {
5109
5109
  throw new FileOperationError("invalid_input", 400, !1, { reason });
5110
5110
  };
5111
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid13();
5111
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid14();
5112
5112
  let input = value, update = {};
5113
- if (!Object.keys(input).length || Object.keys(input).some((key) => !["name", "path", "mediaType"].includes(key))) return invalid13();
5113
+ if (!Object.keys(input).length || Object.keys(input).some((key) => !["name", "path", "mediaType"].includes(key))) return invalid14();
5114
5114
  if (Object.hasOwn(input, "name")) {
5115
- if (!safeFileName(input.name)) return invalid13("invalid_name");
5115
+ if (!safeFileName(input.name)) return invalid14("invalid_name");
5116
5116
  update.name = input.name;
5117
5117
  }
5118
5118
  if (Object.hasOwn(input, "path")) {
5119
- if (!safeManagedFilePath(input.path)) return invalid13("invalid_path");
5119
+ if (!safeManagedFilePath(input.path)) return invalid14("invalid_path");
5120
5120
  update.path = input.path;
5121
5121
  }
5122
5122
  return Object.hasOwn(input, "mediaType") && (update.mediaType = declaredOriginalMediaType(input.mediaType)), update;
5123
5123
  }
5124
5124
  function parseFileCreateMetadata(value, maxBytes) {
5125
- let invalid13 = (reason = "invalid_metadata") => {
5125
+ let invalid14 = (reason = "invalid_metadata") => {
5126
5126
  throw new FileOperationError("invalid_input", 400, !1, { reason });
5127
5127
  };
5128
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid13();
5128
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid14();
5129
5129
  let input = value;
5130
- if (Object.keys(input).some((key) => !["name", "path", "storage", "mediaType", "size", "requestKey"].includes(key))) return invalid13();
5130
+ if (Object.keys(input).some((key) => !["name", "path", "storage", "mediaType", "size", "requestKey"].includes(key))) return invalid14();
5131
5131
  let path = input.path === void 0 ? "Files" : input.path;
5132
- if (!safeFileName(input.name)) return invalid13("invalid_name");
5133
- if (!safeManagedFilePath(path)) return invalid13("invalid_path");
5134
- if (input.storage !== void 0 && input.storage !== "remote" && input.storage !== "local") return invalid13("invalid_storage");
5132
+ if (!safeFileName(input.name)) return invalid14("invalid_name");
5133
+ if (!safeManagedFilePath(path)) return invalid14("invalid_path");
5134
+ if (input.storage !== void 0 && input.storage !== "remote" && input.storage !== "local") return invalid14("invalid_storage");
5135
5135
  let mediaType = input.mediaType === void 0 ? "application/octet-stream" : declaredOriginalMediaType(input.mediaType);
5136
- if (!Number.isSafeInteger(input.size) || input.size < 0) return invalid13("invalid_size");
5136
+ if (!Number.isSafeInteger(input.size) || input.size < 0) return invalid14("invalid_size");
5137
5137
  if (input.size > maxBytes) throw new FileOperationError(
5138
5138
  "request_too_large",
5139
5139
  413,
5140
5140
  !1,
5141
5141
  { reason: "size_limit", limitBytes: maxBytes, receivedBytes: input.size }
5142
5142
  );
5143
- return typeof input.requestKey != "string" || input.requestKey.length < 1 || input.requestKey.length > 256 || input.requestKey !== input.requestKey.trim() || /[\u0000-\u001f\u007f]/.test(input.requestKey) ? invalid13("invalid_request_key") : {
5143
+ return typeof input.requestKey != "string" || input.requestKey.length < 1 || input.requestKey.length > 256 || input.requestKey !== input.requestKey.trim() || /[\u0000-\u001f\u007f]/.test(input.requestKey) ? invalid14("invalid_request_key") : {
5144
5144
  name: input.name,
5145
5145
  path,
5146
5146
  ...input.storage ? { storage: input.storage } : {},
@@ -5302,26 +5302,27 @@ function asksBlock(value) {
5302
5302
  }
5303
5303
  function selection(value) {
5304
5304
  let input = object(value, "selection");
5305
- return keys(input, ["source"], "selection"), validateResponseDefinition({ type: "selection", source: input.source });
5305
+ return keys(input, ["source", "options"], "selection"), validateResponseDefinition({ type: "selection", ...input });
5306
+ }
5307
+ function validateChoice(entry) {
5308
+ let option = object(entry, "choice");
5309
+ keys(option, ["value", "label", "description", "note"], "choice");
5310
+ let note;
5311
+ if (option.note !== void 0) {
5312
+ let declaration2 = object(option.note, "choice note");
5313
+ keys(declaration2, ["placeholder"], "choice note"), note = { placeholder: text(declaration2.placeholder, "note placeholder") };
5314
+ }
5315
+ return {
5316
+ value: id(option.value, "choice value"),
5317
+ label: text(option.label, "choice label"),
5318
+ ...option.description === void 0 ? {} : { description: text(option.description, "choice description") },
5319
+ ...note ? { note } : {}
5320
+ };
5306
5321
  }
5307
5322
  function validateAuthoredSource(value) {
5308
5323
  let source2 = object(value, "response definition");
5309
5324
  keys(source2, ["type", "options", "suggestions", "search"], "response definition"), source2.type !== "authored" && fail("Expected authored options");
5310
- let options = array(source2.options, "options").map((entry) => {
5311
- let option = object(entry, "choice");
5312
- keys(option, ["value", "label", "description", "note"], "choice");
5313
- let note;
5314
- if (option.note !== void 0) {
5315
- let declaration2 = object(option.note, "choice note");
5316
- keys(declaration2, ["placeholder"], "choice note"), note = { placeholder: text(declaration2.placeholder, "note placeholder") };
5317
- }
5318
- return {
5319
- value: id(option.value, "choice value"),
5320
- label: text(option.label, "choice label"),
5321
- ...option.description === void 0 ? {} : { description: text(option.description, "choice description") },
5322
- ...note ? { note } : {}
5323
- };
5324
- });
5325
+ let options = array(source2.options, "options").map(validateChoice);
5325
5326
  if (options.length || fail("Choices require at least one option"), new Set(options.map((option) => option.value)).size !== options.length && fail("Duplicate choice value"), Object.hasOwn(source2, "search") || Object.hasOwn(source2, "suggestions")) {
5326
5327
  let labels = object(source2.search, "choice search");
5327
5328
  keys(labels, ["triggerLabel", "placeholder", "emptyLabel"], "choice search");
@@ -5340,10 +5341,8 @@ function validateRecordReference(value) {
5340
5341
  let repository = id(row.repository, "repository"), ref = id(row.ref, "Record reference");
5341
5342
  return (!/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(repository) || /\.\.|\/\//.test(repository) || ref.length > 512 || !/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(ref)) && fail("Invalid Record identity"), { repository, ref };
5342
5343
  }
5343
- function validateRecordSource(value) {
5344
- let source2 = object(value, "Record selection");
5345
- keys(source2, ["type", "collection", "refPrefix", "where", "display", "suggestions"], "Record selection"), source2.type !== "records" && fail("Expected Record options");
5346
- let collection = object(source2.collection, "collection");
5344
+ function recordPickerSource(value) {
5345
+ let source2 = object(value, "Record selection"), collection = object(source2.collection, "collection");
5347
5346
  keys(collection, ["repository", "name"], "collection");
5348
5347
  let repository = validateRecordReference({ repository: collection.repository, ref: "records/example" }).repository, name2 = id(collection.name, "collection name");
5349
5348
  /^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(name2) || fail("Invalid collection name");
@@ -5352,10 +5351,23 @@ function validateRecordSource(value) {
5352
5351
  let where = object(source2.where ?? {}, "Record filter"), fieldName = (name3) => /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name3) && !["constructor", "prototype"].includes(name3);
5353
5352
  for (let [name3, value2] of Object.entries(where))
5354
5353
  (!fieldName(name3) || !(value2 === null || ["string", "number", "boolean"].includes(typeof value2)) || typeof value2 == "number" && !Number.isFinite(value2)) && fail("Record filters require scalar equality");
5355
- let display = object(source2.display, "Record display");
5354
+ return {
5355
+ collection: { repository, name: name2 },
5356
+ ...refPrefix ? { refPrefix } : {},
5357
+ ...source2.where === void 0 ? {} : { where: { ...where } }
5358
+ };
5359
+ }
5360
+ function validateRecordPickerSource(value) {
5361
+ let source2 = object(value, "Record picker source");
5362
+ return keys(source2, ["collection", "refPrefix", "where"], "Record picker source"), Object.hasOwn(source2, "where") && object(source2.where, "Record filter"), recordPickerSource(source2);
5363
+ }
5364
+ function validateRecordSource(value) {
5365
+ let source2 = object(value, "Record selection");
5366
+ keys(source2, ["type", "collection", "refPrefix", "where", "display", "suggestions"], "Record selection"), source2.type !== "records" && fail("Expected Record options");
5367
+ let bounded3 = recordPickerSource(source2), { repository } = bounded3.collection, fieldName = (name2) => /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name2) && !["constructor", "prototype"].includes(name2), display = object(source2.display, "Record display");
5356
5368
  keys(display, ["labelFields"], "Record display");
5357
5369
  let labelFields = distinctIds(display.labelFields, "label fields");
5358
- (labelFields.length > 2 || labelFields.some((name3) => !fieldName(name3))) && fail("Select one or two scalar label fields");
5370
+ (labelFields.length > 2 || labelFields.some((name2) => !fieldName(name2))) && fail("Select one or two scalar label fields");
5359
5371
  let suggestions = array(source2.suggestions ?? [], "suggestions").map((value2) => {
5360
5372
  let entry = object(value2, "suggestion");
5361
5373
  keys(entry, ["record", "reason"], "suggestion");
@@ -5364,14 +5376,13 @@ function validateRecordSource(value) {
5364
5376
  });
5365
5377
  return (suggestions.length > 8 || new Set(suggestions.map((entry) => entry.record.ref)).size !== suggestions.length) && fail("Record selection permits at most eight unique suggestions"), {
5366
5378
  type: "records",
5367
- collection: { repository, name: name2 },
5368
- ...refPrefix ? { refPrefix } : {},
5369
- where: { ...where },
5379
+ ...bounded3,
5380
+ where: bounded3.where ?? {},
5370
5381
  display: { labelFields },
5371
5382
  suggestions
5372
5383
  };
5373
5384
  }
5374
- function validateResponseDefinition(value) {
5385
+ function validateLegacyResponseDefinition(value) {
5375
5386
  let definition = object(value, "response definition");
5376
5387
  keys(definition, ["type", "source"], "response definition"), definition.type !== "selection" && fail("Expected a selection definition");
5377
5388
  let source2 = object(definition.source, "option source");
@@ -5384,6 +5395,41 @@ function validateResponseDefinition(value) {
5384
5395
  return fail("Unsupported option source");
5385
5396
  }
5386
5397
  }
5398
+ function selectionOptions(value, published) {
5399
+ let options = array(value, "options");
5400
+ return (!options.length || options.length > 9) && fail("Selections require one to nine options"), options.map((value2, index) => {
5401
+ let option = object(value2, "option"), common = published ? ["type", "id"] : ["type"];
5402
+ published && option.id !== index + 1 && fail("Published option IDs must be consecutive from one");
5403
+ let numbered = published ? { id: index + 1 } : {};
5404
+ switch (option.type) {
5405
+ case "choice":
5406
+ return keys(option, [...common, "value", "label", "description", "note"], "choice"), { type: "choice", ...validateChoice(
5407
+ Object.fromEntries(Object.entries(option).filter(([key]) => !["type", "id"].includes(key)))
5408
+ ), ...numbered };
5409
+ case "record":
5410
+ return keys(option, [...common, "value", "label", "description"], "Record option"), {
5411
+ type: "record",
5412
+ value: validateRecordReference(option.value),
5413
+ label: text(option.label, "Record label"),
5414
+ ...option.description === void 0 ? {} : { description: text(option.description, "Record description") },
5415
+ ...numbered
5416
+ };
5417
+ case "record-picker":
5418
+ return keys(option, [...common, "label", "source"], "Record picker option"), {
5419
+ type: "record-picker",
5420
+ label: text(option.label, "picker label"),
5421
+ source: validateRecordPickerSource(option.source),
5422
+ ...numbered
5423
+ };
5424
+ default:
5425
+ return fail("Unsupported option kind");
5426
+ }
5427
+ });
5428
+ }
5429
+ function validateResponseDefinition(value) {
5430
+ let definition = object(value, "response definition");
5431
+ 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);
5432
+ }
5387
5433
  function handlerReference(value) {
5388
5434
  let source2 = object(value, "handler reference");
5389
5435
  return keys(source2, ["id", "input"], "handler reference"), { id: id(source2.id, "handler ID"), input: serializable(source2.input) };
@@ -5520,16 +5566,19 @@ function createInboxPublisher(transport) {
5520
5566
  };
5521
5567
  }
5522
5568
 
5569
+ var recordOptionCatalogueByteLimit = 7e6;
5570
+ function normalizeRecordOptionSearch(text5) {
5571
+ return text5.toLowerCase().replace(/\s+/gu, " ").trim();
5572
+ }
5523
5573
  var RecordSelectionError = class extends InboxContractError {
5524
5574
  constructor(problem, source2) {
5525
5575
  let collection = `${source2.collection.repository}/${source2.collection.name}`, messages = {
5526
5576
  collection_unavailable: `The ${collection} collection is unavailable. Check the collection name and its schema.`,
5527
- display_fields_invalid: `The label fields for ${collection} must be scalar fields in its schema. Check display.labelFields.`,
5577
+ display_fields_invalid: "display" in source2 ? `The label fields for ${collection} must be scalar fields in its schema. Check display.labelFields.` : `The ${collection} schema must declare one or two scalar title fields. Check display.title.`,
5528
5578
  filter_fields_invalid: `The filters for ${collection} must use scalar schema fields and matching values. Check the Question\u2019s where fields.`,
5529
5579
  ref_prefix_invalid: `The record reference prefix does not belong to ${collection}. Check refPrefix against the collection\u2019s record references.`,
5530
5580
  suggestion_unavailable: `A suggested record is missing or isn\u2019t eligible for ${collection}. Update the suggestions and try again.`,
5531
- selected_record_unavailable: `The selected record is no longer available in ${collection}. Search again and choose a current record.`,
5532
- label_unavailable: `A record in ${collection} has no value in the configured label fields. Update display.labelFields or the record.`
5581
+ label_unavailable: "display" in source2 ? `A record in ${collection} has no value in the configured label fields. Update display.labelFields or the record.` : `A record in ${collection} has no value in the declared title fields. Update display.title or the record.`
5533
5582
  };
5534
5583
  super(messages[problem]);
5535
5584
  this.problem = problem;
@@ -5790,7 +5839,6 @@ function safeInboxPublicationMessage(value) {
5790
5839
  "filter_fields_invalid",
5791
5840
  "ref_prefix_invalid",
5792
5841
  "suggestion_unavailable",
5793
- "selected_record_unavailable",
5794
5842
  "label_unavailable"
5795
5843
  ])
5796
5844
  if (new RecordSelectionError(problem, source2).message === message2) return message2;
@@ -6188,14 +6236,14 @@ var AIError = class extends Error {
6188
6236
  code;
6189
6237
  detail;
6190
6238
  };
6191
- function capture(value, invalid13, oversized, limit = ROUTINE_AI_VALUE_BYTES) {
6239
+ function capture(value, invalid14, oversized, limit = ROUTINE_AI_VALUE_BYTES) {
6192
6240
  try {
6193
6241
  assertRoutineJson(value);
6194
6242
  let encoded = JSON.stringify(value);
6195
6243
  if (new TextEncoder().encode(encoded).byteLength > limit) throw new AIError(oversized);
6196
6244
  return freezeRoutineMetadata(JSON.parse(encoded));
6197
6245
  } catch (error) {
6198
- throw error instanceof AIError ? error : new AIError(invalid13);
6246
+ throw error instanceof AIError ? error : new AIError(invalid14);
6199
6247
  }
6200
6248
  }
6201
6249
  function parseRoutineAIRequest(value) {
@@ -6260,12 +6308,12 @@ function acceptText(request3, text5) {
6260
6308
 
6261
6309
  var ROUTINE_STEP_SUMMARY_BYTES = 256 * 1024, ROUTINE_STEP_OUTPUT_BYTES = 1024 * 1024;
6262
6310
  function parseRoutineStepOutputDetail(value) {
6263
- let invalid13 = () => {
6311
+ let invalid14 = () => {
6264
6312
  throw new AppRoutineContractError("invalid_value");
6265
6313
  };
6266
6314
  assertRoutineFields(value, ["step", "sizeBytes", "limitBytes", "summaryBytes", "dataBytes"]);
6267
6315
  let { step, sizeBytes, limitBytes, summaryBytes, dataBytes } = value;
6268
- 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 ? invalid13() : freezeRoutineMetadata({ step, sizeBytes, limitBytes, summaryBytes, dataBytes });
6316
+ 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 ? invalid14() : freezeRoutineMetadata({ step, sizeBytes, limitBytes, summaryBytes, dataBytes });
6269
6317
  }
6270
6318
  function routineStepOutputMessage(value) {
6271
6319
  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.";
@@ -6279,9 +6327,9 @@ var RoutineStepOutputError = class extends Error {
6279
6327
  super(routineStepOutputMessage(captured)), this.detail = captured, Object.freeze(this);
6280
6328
  }
6281
6329
  };
6282
- function captureRoutineStepOutput(step, summary2, data3) {
6283
- assertRoutineJson(summary2), assertRoutineJson(data3);
6284
- let summaryJson = JSON.stringify(summary2), dataJson = JSON.stringify(data3), summaryBytes = new TextEncoder().encode(summaryJson).byteLength, dataBytes = new TextEncoder().encode(dataJson).byteLength, sizeBytes = summaryBytes + dataBytes, limitBytes = summaryBytes > ROUTINE_STEP_SUMMARY_BYTES ? ROUTINE_STEP_SUMMARY_BYTES : ROUTINE_STEP_OUTPUT_BYTES;
6330
+ function captureRoutineStepOutput(step, summary3, data3) {
6331
+ assertRoutineJson(summary3), assertRoutineJson(data3);
6332
+ let summaryJson = JSON.stringify(summary3), dataJson = JSON.stringify(data3), summaryBytes = new TextEncoder().encode(summaryJson).byteLength, dataBytes = new TextEncoder().encode(dataJson).byteLength, sizeBytes = summaryBytes + dataBytes, limitBytes = summaryBytes > ROUTINE_STEP_SUMMARY_BYTES ? ROUTINE_STEP_SUMMARY_BYTES : ROUTINE_STEP_OUTPUT_BYTES;
6285
6333
  if (summaryBytes > ROUTINE_STEP_SUMMARY_BYTES || sizeBytes > ROUTINE_STEP_OUTPUT_BYTES)
6286
6334
  throw new RoutineStepOutputError({ step, sizeBytes, limitBytes, summaryBytes, dataBytes });
6287
6335
  return freezeRoutineMetadata({ summary: JSON.parse(summaryJson), data: JSON.parse(dataJson) });
@@ -6516,8 +6564,8 @@ async function executeRoutineDefinition(definition, input, runtime) {
6516
6564
  await runtime.step(id3, { status: "running" }), activeStep = id3;
6517
6565
  let output = await steps[id3].run(saved, os2);
6518
6566
  if (assertRoutineFields(output, ["summary", "data"]), !Object.hasOwn(output, "summary") || !Object.hasOwn(output, "data")) return invalid3();
6519
- let { summary: summary2, data: data3 } = captureRoutineStepOutput(id3, output.summary, output.data);
6520
- return await runtime.step(id3, { status: "completed", summary: summary2, data: data3 }), activeStep = void 0, freezeRoutineMetadata({ summary: summary2, data: data3 });
6567
+ let { summary: summary3, data: data3 } = captureRoutineStepOutput(id3, output.summary, output.data);
6568
+ return await runtime.step(id3, { status: "completed", summary: summary3, data: data3 }), activeStep = void 0, freezeRoutineMetadata({ summary: summary3, data: data3 });
6521
6569
  } catch (error) {
6522
6570
  throw error instanceof RoutineStepOutputError && (outputFailure ??= error), broken = !0, activeStep = void 0, await runtime.step(id3, { status: "failed" }), error;
6523
6571
  }
@@ -6638,7 +6686,26 @@ function safeRecordFieldMessage(value) {
6638
6686
  let expected = parseExpectation(/\. (Expected .+) Check its definition in /.exec(value)?.[1]);
6639
6687
  return fieldProblems.map((problem) => recordFieldMessage(parts[1], field, problem, schemaPath, expected)).find((message2) => message2 === value);
6640
6688
  }
6689
+ function parsePublicationConflict(value) {
6690
+ if (!value || typeof value != "object" || Array.isArray(value)) throw new Error("Invalid publication conflict");
6691
+ let row = value;
6692
+ if (Object.keys(row).sort().join(",") !== "code,conflict,record" || row.code !== "publication_conflict" || !["record_version_changed", "record_missing", "create_identity_conflict", "filing_conflict", "schema_changed"].includes(String(row.conflict)) || typeof row.record != "string" || !validRecordRef(row.record)) throw new Error("Invalid publication conflict");
6693
+ return structuredClone(value);
6694
+ }
6641
6695
  function dataValidationMessageFacts(error) {
6696
+ if (["invalid_change", "conflict"].includes(error.code) && error.detail && typeof error.detail == "object" && "code" in error.detail && error.detail.code === "publication_conflict")
6697
+ try {
6698
+ let detail = parsePublicationConflict(error.detail), descriptions = {
6699
+ record_version_changed: "changed after it was reviewed",
6700
+ record_missing: "is missing",
6701
+ create_identity_conflict: "already exists",
6702
+ filing_conflict: "has a conflicting filing path",
6703
+ schema_changed: "has an unavailable or incompatible schema"
6704
+ };
6705
+ return { detail, message: `Record "${detail.record}" ${descriptions[detail.conflict]}. No changes were saved.` };
6706
+ } catch {
6707
+ return {};
6708
+ }
6642
6709
  if (error.code === "invalid_change") {
6643
6710
  let detail = parseDataValidationDetail(error.detail);
6644
6711
  if (detail) {
@@ -6668,22 +6735,24 @@ var localDataPath = (value, repository) => typeof value == "string" && value.len
6668
6735
  return Object.keys(row).sort().join(",") === "action,path" && ["created", "updated", "deleted"].includes(String(row.action)) && localDataPath(row.path, repository);
6669
6736
  };
6670
6737
  function parseDataFailureDetail(value) {
6671
- let invalid13 = () => {
6738
+ let invalid14 = () => {
6672
6739
  throw new Error("Invalid local Data failure detail");
6673
6740
  };
6674
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid13();
6741
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid14();
6675
6742
  let row = value;
6676
- 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 invalid13();
6743
+ 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 invalid14();
6677
6744
  let repository = row.repository;
6678
- if (!row.cause || typeof row.cause != "object" || Array.isArray(row.cause)) return invalid13();
6745
+ if (!row.cause || typeof row.cause != "object" || Array.isArray(row.cause)) return invalid14();
6679
6746
  let cause = row.cause;
6680
- 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 invalid13();
6747
+ 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 invalid14();
6681
6748
  let files3 = row.files;
6682
- 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 invalid13();
6683
- for (let key of ["savedOmitted", "notAttemptedOmitted"]) if (files3[key] !== void 0 && (!Number.isSafeInteger(files3[key]) || Number(files3[key]) < 1 || Number(files3[key]) > 1e4)) return invalid13();
6684
- 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" ? invalid13() : structuredClone(value);
6749
+ 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 invalid14();
6750
+ for (let key of ["savedOmitted", "notAttemptedOmitted"]) if (files3[key] !== void 0 && (!Number.isSafeInteger(files3[key]) || Number(files3[key]) < 1 || Number(files3[key]) > 1e4)) return invalid14();
6751
+ 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" ? invalid14() : structuredClone(value);
6685
6752
  }
6686
6753
  function parseDataOperationDetail(value) {
6754
+ if (value && typeof value == "object" && !Array.isArray(value) && value.code === "publication_conflict")
6755
+ return parsePublicationConflict(value);
6687
6756
  let validation = parseDataValidationDetail(value);
6688
6757
  if (validation) return validation;
6689
6758
  if (value && typeof value == "object" && !Array.isArray(value) && value.code === "record_limit_exceeded") {
@@ -6721,7 +6790,7 @@ function dataErrorMessage(code, effect) {
6721
6790
  var DataOperationError = class extends Error {
6722
6791
  constructor(code, retryable = !1, effect, component, detail) {
6723
6792
  let parsed = detail === void 0 ? void 0 : parseDataOperationDetail(detail);
6724
- if (parsed && ("reason" in parsed ? code !== "invalid_change" : parsed.code === "record_limit_exceeded" && code !== "capacity"))
6793
+ if (parsed && ("reason" in parsed ? code !== "invalid_change" : parsed.code === "publication_conflict" ? !["invalid_change", "conflict"].includes(code) : parsed.code === "record_limit_exceeded" && code !== "capacity"))
6725
6794
  throw new Error("Invalid Data operation detail");
6726
6795
  super(parsed && "code" in parsed && parsed.code === "local_data_publication_failed" ? dataPublicationFailureMessage(parsed) : code === "capacity" && parsed && "code" in parsed && parsed.code === "record_limit_exceeded" ? dataRecordLimitMessage(parsed) : dataErrorMessage(code, effect));
6727
6796
  this.code = code;
@@ -6824,21 +6893,21 @@ function captureRecordsQuery(query) {
6824
6893
  return capture3(query);
6825
6894
  }
6826
6895
  function captureRecordsAll(query, options) {
6827
- let invalid13 = () => {
6896
+ let invalid14 = () => {
6828
6897
  throw new DataOperationError("invalid_query");
6829
6898
  };
6830
6899
  try {
6831
6900
  let properties = dataProperties(options), maxRecords = properties.maxRecords?.value;
6832
- if (Object.keys(properties).join(",") !== "maxRecords" || !Number.isSafeInteger(maxRecords) || maxRecords < 1) return invalid13();
6901
+ if (Object.keys(properties).join(",") !== "maxRecords" || !Number.isSafeInteger(maxRecords) || maxRecords < 1) return invalid14();
6833
6902
  let detached = capture3(query), selections = dataProperties(detached);
6834
- if (Object.keys(selections).length < 1 || Object.keys(selections).length > 16) return invalid13();
6903
+ if (Object.keys(selections).length < 1 || Object.keys(selections).length > 16) return invalid14();
6835
6904
  for (let selection2 of Object.values(selections)) {
6836
6905
  let fields4 = dataProperties(selection2.value);
6837
- if (fields4.$ && Object.hasOwn(dataProperties(fields4.$.value), "after")) return invalid13();
6906
+ if (fields4.$ && Object.hasOwn(dataProperties(fields4.$.value), "after")) return invalid14();
6838
6907
  }
6839
6908
  return { query: detached, maxRecords };
6840
6909
  } catch {
6841
- return invalid13();
6910
+ return invalid14();
6842
6911
  }
6843
6912
  }
6844
6913
 
@@ -7046,11 +7115,11 @@ function dataTransportError(status, value) {
7046
7115
  detail = row?.detail === void 0 ? void 0 : parseDataOperationDetail(row.detail);
7047
7116
  } catch {
7048
7117
  }
7049
- return detail && "reason" in detail && code !== "invalid_change" && (detail = void 0), explainDataValidation(new DataOperationError(
7118
+ return detail && ("reason" in detail && code !== "invalid_change" || "code" in detail && detail.code === "publication_conflict" && !["invalid_change", "conflict"].includes(code)) && (detail = void 0), explainDataValidation(new DataOperationError(
7050
7119
  code,
7051
7120
  typeof row?.retryable == "boolean" ? row.retryable : ["capacity", "unavailable", "apply_pending"].includes(code),
7052
7121
  code === "conflict" ? "unapplied" : effect,
7053
- code === "invalid_change" && typeof row?.component == "string" && /^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/.test(row.component) ? row.component : void 0,
7122
+ (["invalid_change", "conflict"].includes(code) || code === "unavailable" && row?.component === "deletion_waits_for_current_data") && typeof row?.component == "string" && /^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/.test(row.component) ? row.component : void 0,
7054
7123
  detail
7055
7124
  ), row?.message, row?.detail);
7056
7125
  }
@@ -7319,6 +7388,21 @@ function parseStoredRecordLink(value) {
7319
7388
  return typeof value == "string" && value.startsWith("[[") && value.endsWith("]]") ? parseRecordLink(value.slice(2, -2)) : void 0;
7320
7389
  }
7321
7390
 
7391
+ var NAME = /^[a-zA-Z][a-zA-Z0-9_-]*$/, invalid7 = (message2) => {
7392
+ throw new Error(message2);
7393
+ };
7394
+ function parseRecordDisplay(value, definitions2, fail8 = invalid7) {
7395
+ if (value === void 0) return;
7396
+ if (!value || typeof value != "object" || Array.isArray(value)) return fail8("Expected a field mapping");
7397
+ let row = value;
7398
+ if (Object.keys(row).some((key) => key !== "title") || !Object.hasOwn(row, "title") || !Array.isArray(row.title) || row.title.length < 1 || row.title.length > 2 || row.title.some((name2) => typeof name2 != "string" || !NAME.test(name2)) || new Set(row.title).size !== row.title.length) return fail8("Display title requires one or two distinct scalar fields");
7399
+ let title = row.title;
7400
+ return title.some((name2) => {
7401
+ let field = definitions2.find((candidate) => candidate.name === name2);
7402
+ return !field || field.many || ["link", "object", "map"].includes(field.kind);
7403
+ }) ? fail8("Display title requires one or two distinct scalar fields") : { title };
7404
+ }
7405
+
7322
7406
  var RecordValidationError = class extends Error {
7323
7407
  constructor(message2, path) {
7324
7408
  super(message2);
@@ -7351,7 +7435,7 @@ function fieldExpectation(field) {
7351
7435
  ...field.kind === "date" && field.format ? { format: field.format } : {}
7352
7436
  };
7353
7437
  }
7354
- var NAME = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
7438
+ var NAME2 = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
7355
7439
  function fail3(message2) {
7356
7440
  throw new RecordValidationError(message2);
7357
7441
  }
@@ -7364,6 +7448,9 @@ function object3(value) {
7364
7448
  function keys2(row, allowed, required) {
7365
7449
  (Object.keys(row).some((key) => !allowed.includes(key)) || required.some((key) => !Object.hasOwn(row, key))) && fail3("Unsupported or missing schema/record fields");
7366
7450
  }
7451
+ function parseRecordDisplay2(value, definitions2) {
7452
+ return parseRecordDisplay(value, definitions2, fail3);
7453
+ }
7367
7454
  function valueDefinition(value, depth, native, named = !1) {
7368
7455
  depth > 8 && fail3("Invalid field definitions");
7369
7456
  let row = { ...object3(value) };
@@ -7421,7 +7508,7 @@ function valueDefinition(value, depth, native, named = !1) {
7421
7508
  let property = row.kind === "enum" ? "values" : "to";
7422
7509
  check([property]);
7423
7510
  let list2 = row.kind === "link" && typeof row.to == "string" ? [row.to] : row[property];
7424
- return (!Array.isArray(list2) || !list2.length || list2.length > 1e5 || new Set(list2).size !== list2.length || list2.some((item) => typeof item != "string" || !item || row.kind === "link" && !NAME.test(item))) && fail3("Invalid enum/link definition"), row.kind === "enum" ? { ...base, kind: "enum", values: list2 } : { ...base, kind: "link", to: list2 };
7511
+ return (!Array.isArray(list2) || !list2.length || list2.length > 1e5 || new Set(list2).size !== list2.length || list2.some((item) => typeof item != "string" || !item || row.kind === "link" && !NAME2.test(item))) && fail3("Invalid enum/link definition"), row.kind === "enum" ? { ...base, kind: "enum", values: list2 } : { ...base, kind: "link", to: list2 };
7425
7512
  }
7426
7513
  case "object":
7427
7514
  return check(["fields"]), { ...base, kind: "object", fields: fields2(row.fields, depth + 1, native) };
@@ -7439,7 +7526,7 @@ function fields2(value, depth = 0, native = !1) {
7439
7526
  let names = /* @__PURE__ */ new Set();
7440
7527
  return value.map((definition) => {
7441
7528
  let row = object3(definition);
7442
- return (typeof row.name != "string" || !NAME.test(row.name) || ["constructor", "prototype"].includes(row.name) || names.has(row.name)) && fail3("Invalid or duplicate field name"), names.add(row.name), { name: row.name, ...valueDefinition(row, depth, native, !0) };
7529
+ return (typeof row.name != "string" || !NAME2.test(row.name) || ["constructor", "prototype"].includes(row.name) || names.has(row.name)) && fail3("Invalid or duplicate field name"), names.add(row.name), { name: row.name, ...valueDefinition(row, depth, native, !0) };
7443
7530
  });
7444
7531
  }
7445
7532
  function validateRecordFields(value, definitions2, resolveLink, canonical = !1) {
@@ -7538,6 +7625,16 @@ function publicDefinition(field) {
7538
7625
  function publicField(field) {
7539
7626
  return { ...publicDefinition(field), name: field.name };
7540
7627
  }
7628
+ function summary({ name: name2, schema: schema2 }) {
7629
+ return { name: name2, type: schema2.type, ...schema2.description === void 0 ? {} : { description: schema2.description } };
7630
+ }
7631
+ function publicCollectionSchema(collection) {
7632
+ return {
7633
+ ...summary(collection),
7634
+ ...collection.schema.display ? { display: { title: [...collection.schema.display.title] } } : {},
7635
+ fields: collection.schema.fields.map(publicField)
7636
+ };
7637
+ }
7541
7638
  function scalarField(name2, schema2) {
7542
7639
  if (name2 === "$ref") return { name: name2, kind: "string", nullable: !1, many: !1 };
7543
7640
  let field = schema2.fields.find((field2) => field2.name === name2);
@@ -7696,9 +7793,9 @@ function cursorPosition(value, binding, limit) {
7696
7793
  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) ? fail4("incompatible cursor") : { position, ref };
7697
7794
  }
7698
7795
 
7699
- var invalid7 = () => {
7796
+ var invalid8 = () => {
7700
7797
  throw new DataOperationError("unavailable", !0);
7701
- }, object4 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid7() : value, keys3 = (value, expected) => Object.keys(value).sort().join(",") === expected, hash = (value) => typeof value == "string" && /^[0-9a-f]{40}$/.test(value), time = (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);
7798
+ }, object4 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid8() : value, keys3 = (value, expected) => Object.keys(value).sort().join(",") === expected, hash = (value) => typeof value == "string" && /^[0-9a-f]{40}$/.test(value), time = (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);
7702
7799
  function json(value) {
7703
7800
  if (!(value === null || typeof value == "boolean" || typeof value == "number" && Number.isFinite(value) || dataText(value))) {
7704
7801
  if (Array.isArray(value)) {
@@ -7706,7 +7803,7 @@ function json(value) {
7706
7803
  return;
7707
7804
  }
7708
7805
  for (let [key, item] of Object.entries(object4(value))) {
7709
- if (!dataText(key)) return invalid7();
7806
+ if (!dataText(key)) return invalid8();
7710
7807
  json(item);
7711
7808
  }
7712
7809
  }
@@ -7718,66 +7815,66 @@ var slot = (values, field) => Object.hasOwn(values, field) ? { present: !0, valu
7718
7815
  function apply(book, event) {
7719
7816
  let records = book.get(event.collection), prior = records.get(event.ref);
7720
7817
  if (event.kind === "create") {
7721
- if (prior) return invalid7();
7818
+ if (prior) return invalid8();
7722
7819
  records.set(event.ref, structuredClone(event.values));
7723
7820
  } else if (event.kind === "delete") {
7724
- if (!prior || stable(prior) !== stable(event.values)) return invalid7();
7821
+ if (!prior || stable(prior) !== stable(event.values)) return invalid8();
7725
7822
  records.delete(event.ref);
7726
7823
  } else if (event.kind === "rename") {
7727
7824
  let before = records.get(event.previousRef);
7728
- if (!before || prior) return invalid7();
7825
+ if (!before || prior) return invalid8();
7729
7826
  records.delete(event.previousRef), records.set(event.ref, before);
7730
7827
  } else if (event.kind === "update") {
7731
- if (!prior || stable(slot(prior, event.field)) !== stable(event.before) || stable(event.before) === stable(event.after)) return invalid7();
7828
+ if (!prior || stable(slot(prior, event.field)) !== stable(event.before) || stable(event.before) === stable(event.after)) return invalid8();
7732
7829
  event.after.present ? Object.defineProperty(prior, event.field, { value: structuredClone(event.after.value), enumerable: !0, configurable: !0, writable: !0 }) : delete prior[event.field];
7733
7830
  }
7734
7831
  }
7735
7832
  function validateSnapshotHistory(input, collections, version) {
7736
7833
  let row = object4(input), selections = object4(row.fields);
7737
- if (!keys3(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 invalid7();
7834
+ if (!keys3(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 invalid8();
7738
7835
  let book = /* @__PURE__ */ new Map();
7739
7836
  for (let [collection, selection2] of Object.entries(selections)) {
7740
7837
  let selected = object4(selection2), fields4 = selected.fields;
7741
- if (!Object.hasOwn(collections, collection) || !keys3(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 invalid7();
7838
+ if (!Object.hasOwn(collections, collection) || !keys3(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 invalid8();
7742
7839
  book.set(collection, /* @__PURE__ */ new Map());
7743
7840
  }
7744
7841
  let history = row, seen = /* @__PURE__ */ new Set(), parent = null;
7745
7842
  for (let group of history.commits) {
7746
- if (!keys3(object4(group), "authoredAt,commit,committedAt,events,firstParent") || !hash(group.commit) || seen.has(group.commit) || group.firstParent !== parent || !time(group.authoredAt) || !time(group.committedAt) || !Array.isArray(group.events)) return invalid7();
7843
+ if (!keys3(object4(group), "authoredAt,commit,committedAt,events,firstParent") || !hash(group.commit) || seen.has(group.commit) || group.firstParent !== parent || !time(group.authoredAt) || !time(group.committedAt) || !Array.isArray(group.events)) return invalid8();
7747
7844
  seen.add(group.commit), parent = group.commit;
7748
7845
  let previous, created = /* @__PURE__ */ new Set();
7749
7846
  for (let event of group.events) {
7750
- if (object4(event), !book.has(event.collection) || !validRecordRef(event.ref) || !event.ref.startsWith(`${event.collection}/`)) return invalid7();
7847
+ if (object4(event), !book.has(event.collection) || !validRecordRef(event.ref) || !event.ref.startsWith(`${event.collection}/`)) return invalid8();
7751
7848
  let fields4 = history.fields[event.collection].fields;
7752
7849
  if (event.kind === "create" || event.kind === "delete") {
7753
- if (!keys3(event, "collection,kind,ref,values") || Object.keys(object4(event.values)).some((field) => !fields4.includes(field))) return invalid7();
7850
+ if (!keys3(event, "collection,kind,ref,values") || Object.keys(object4(event.values)).some((field) => !fields4.includes(field))) return invalid8();
7754
7851
  json(event.values), event.kind === "create" && created.add(event.ref);
7755
7852
  } else if (event.kind === "rename") {
7756
- if (!keys3(event, "collection,kind,previousRef,ref") || !validRecordRef(event.previousRef) || !event.previousRef.startsWith(`${event.collection}/`) || event.previousRef === event.ref) return invalid7();
7853
+ if (!keys3(event, "collection,kind,previousRef,ref") || !validRecordRef(event.previousRef) || !event.previousRef.startsWith(`${event.collection}/`) || event.previousRef === event.ref) return invalid8();
7757
7854
  } else if (event.kind === "update") {
7758
- if (!keys3(event, "after,before,collection,field,kind,ref") || !fields4.includes(event.field) || created.has(event.ref)) return invalid7();
7855
+ if (!keys3(event, "after,before,collection,field,kind,ref") || !fields4.includes(event.field) || created.has(event.ref)) return invalid8();
7759
7856
  for (let value of [event.before, event.after]) {
7760
- if (object4(value), value.present === !1 ? !keys3(value, "present") : value.present !== !0 || !keys3(value, "present,value")) return invalid7();
7857
+ if (object4(value), value.present === !1 ? !keys3(value, "present") : value.present !== !0 || !keys3(value, "present,value")) return invalid8();
7761
7858
  value.present && json(value.value);
7762
7859
  }
7763
- } else return invalid7();
7860
+ } else return invalid8();
7764
7861
  let order = [event.kind === "delete" ? 0 : 1, event.ref, event.kind === "update" ? 1 : 0, event.kind === "update" ? event.field : ""];
7765
7862
  if (previous) {
7766
7863
  let index = order.findIndex((value, i) => value !== previous[i]);
7767
- if (index === -1 || order[index] < previous[index]) return invalid7();
7864
+ if (index === -1 || order[index] < previous[index]) return invalid8();
7768
7865
  }
7769
7866
  previous = order, apply(book, event);
7770
7867
  }
7771
7868
  let refs = /* @__PURE__ */ new Set();
7772
7869
  for (let records of book.values()) for (let ref of records.keys()) {
7773
- if (refs.has(ref)) return invalid7();
7870
+ if (refs.has(ref)) return invalid8();
7774
7871
  refs.add(ref);
7775
7872
  }
7776
7873
  }
7777
- if (parent !== history.through) return invalid7();
7874
+ if (parent !== history.through) return invalid8();
7778
7875
  for (let [collection, records] of book) {
7779
7876
  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]]))]);
7780
- if (stable([...records].sort(([a], [b]) => a < b ? -1 : 1)) !== stable(expected)) return invalid7();
7877
+ if (stable([...records].sort(([a], [b]) => a < b ? -1 : 1)) !== stable(expected)) return invalid8();
7781
7878
  }
7782
7879
  return history;
7783
7880
  }
@@ -7804,57 +7901,60 @@ function readSnapshotHistory(history, input, operation2) {
7804
7901
  };
7805
7902
  }
7806
7903
 
7807
- var snapshotCollection = (catalogue, ref) => catalogue.filter((c) => ref.startsWith(`${c.name}/`)).sort((a, b) => b.name.length - a.name.length)[0], invalid8 = () => {
7904
+ var snapshotCollection = (catalogue, ref) => catalogue.filter((c) => ref.startsWith(`${c.name}/`)).sort((a, b) => b.name.length - a.name.length)[0], invalid9 = () => {
7808
7905
  throw new DataOperationError("unavailable", !0);
7809
- }, object5 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid8() : value;
7906
+ }, object5 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid9() : value;
7810
7907
  function stable2(value) {
7811
7908
  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);
7812
7909
  }
7813
7910
  function schemaText(value) {
7814
- if (typeof value == "string" && !dataText(value)) return invalid8();
7911
+ if (typeof value == "string" && !dataText(value)) return invalid9();
7815
7912
  if (value && typeof value == "object") for (let [key, entry] of Object.entries(value)) {
7816
- if (!dataText(key)) return invalid8();
7913
+ if (!dataText(key)) return invalid9();
7817
7914
  schemaText(entry);
7818
7915
  }
7819
7916
  }
7820
7917
  function validateSnapshotEnvelope(input, repository, name2, bodies = [], timelines = []) {
7821
7918
  try {
7822
7919
  let row = object5(input), legacy = row.format === "data-snapshot.v1";
7823
- 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 !== name2 || !dataVersion(row.version)) return invalid8();
7920
+ 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 !== name2 || !dataVersion(row.version)) return invalid9();
7824
7921
  let schemas2 = object5(row.schemas), collections = object5(row.collections);
7825
7922
  schemaText(schemas2);
7826
7923
  let names = Object.keys(collections);
7827
- for (let subset of [bodies, timelines]) if (new Set(subset).size !== subset.length || subset.some((name3) => !names.includes(name3))) return invalid8();
7828
- if (!names.length || names.join("\0") !== [...names].sort().join("\0") || Object.keys(schemas2).join("\0") !== names.join("\0")) return invalid8();
7924
+ for (let subset of [bodies, timelines]) if (new Set(subset).size !== subset.length || subset.some((name3) => !names.includes(name3))) return invalid9();
7925
+ if (!names.length || names.join("\0") !== [...names].sort().join("\0") || Object.keys(schemas2).join("\0") !== names.join("\0")) return invalid9();
7829
7926
  let catalogue = names.map((name3) => {
7830
7927
  let schema2 = object5(schemas2[name3]);
7831
- if (!validRecordRef(`${name3}/example`) || schema2.name !== name3 || 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", "fields"].includes(key))) return invalid8();
7928
+ if (!validRecordRef(`${name3}/example`) || schema2.name !== name3 || 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 invalid9();
7832
7929
  let definitions2 = fields2(schema2.fields, 0, !0);
7833
- return stable2(definitions2.map(publicField)) !== stable2(schema2.fields) ? invalid8() : { name: name3, schema: {
7930
+ if (stable2(definitions2.map(publicField)) !== stable2(schema2.fields)) return invalid9();
7931
+ let display = parseRecordDisplay2(schema2.display, definitions2);
7932
+ return { name: name3, schema: {
7834
7933
  type: schema2.type,
7835
7934
  fields: definitions2,
7935
+ ...display ? { display } : {},
7836
7936
  ...schema2.description === void 0 ? {} : { description: schema2.description }
7837
7937
  } };
7838
7938
  }), types = /* @__PURE__ */ new Map();
7839
7939
  for (let collection of catalogue) {
7840
7940
  let records = collections[collection.name];
7841
- if (!Array.isArray(records)) return invalid8();
7941
+ if (!Array.isArray(records)) return invalid9();
7842
7942
  let previous = "";
7843
7943
  for (let record4 of records) {
7844
7944
  let value = object5(record4);
7845
- 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 invalid8();
7945
+ 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 invalid9();
7846
7946
  types.set(value.$ref, collection.schema.type), previous = value.$ref;
7847
7947
  }
7848
7948
  }
7849
7949
  for (let collection of catalogue) for (let record4 of collections[collection.name]) {
7850
7950
  let { $ref: _ref, $version: _version, $body, $signals, $timeline, ...values } = record4;
7851
7951
  if (legacy) {
7852
- if (Object.hasOwn(record4, "$signals") || Object.hasOwn(record4, "$timeline")) return invalid8();
7952
+ if (Object.hasOwn(record4, "$signals") || Object.hasOwn(record4, "$timeline")) return invalid9();
7853
7953
  } else if (captureRecordSignals($signals), timelines.includes(collection.name)) {
7854
- if (!Array.isArray($timeline)) return invalid8();
7954
+ if (!Array.isArray($timeline)) return invalid9();
7855
7955
  $timeline.forEach((value) => captureTimeline(value));
7856
- } else if (Object.hasOwn(record4, "$timeline")) return invalid8();
7857
- if (Object.hasOwn(record4, "$body") && (!bodies.includes(collection.name) || typeof $body != "string")) return invalid8();
7956
+ } else if (Object.hasOwn(record4, "$timeline")) return invalid9();
7957
+ if (Object.hasOwn(record4, "$body") && (!bodies.includes(collection.name) || typeof $body != "string")) return invalid9();
7858
7958
  validateRecordFields(values, collection.schema.fields, (ref, targets) => types.get(ref) ?? targets[0], !0);
7859
7959
  }
7860
7960
  let normalized = legacy ? Object.fromEntries(Object.entries(collections).map(([collection, records]) => [
@@ -7873,7 +7973,7 @@ function validateSnapshotEnvelope(input, repository, name2, bodies = [], timelin
7873
7973
  ...Object.hasOwn(row, "history") ? { history: validateSnapshotHistory(row.history, normalized, row.version) } : {}
7874
7974
  };
7875
7975
  } catch {
7876
- return invalid8();
7976
+ return invalid9();
7877
7977
  }
7878
7978
  }
7879
7979
 
@@ -7980,14 +8080,14 @@ function* evaluateRecordsQuery(query, catalogue, context, maxRecords, cloneValue
7980
8080
 
7981
8081
  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";
7982
8082
 
7983
- var invalid9 = () => {
8083
+ var invalid10 = () => {
7984
8084
  throw new DataOperationError("unavailable", !0);
7985
- }, object6 = (v) => v && typeof v == "object" && !Array.isArray(v) ? v : invalid9(), uuid = (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), time2 = (v) => typeof v == "string" && Number.isFinite(Date.parse(v)), recordVersion = (v) => typeof v == "string" && /^record-v1:[0-9a-f]{64}$/.test(v), keys4 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
8085
+ }, object6 = (v) => v && typeof v == "object" && !Array.isArray(v) ? v : invalid10(), uuid = (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), time2 = (v) => typeof v == "string" && Number.isFinite(Date.parse(v)), recordVersion = (v) => typeof v == "string" && /^record-v1:[0-9a-f]{64}$/.test(v), keys4 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
7986
8086
  function validateAcquisition(input, repository, name2) {
7987
8087
  let row = object6(input), snapshot = object6(row.snapshot);
7988
- if (Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== snapshotAcquisitionFormat || !keys4(snapshot, ["id", "name", "refreshedAt", "repository", "version", "collections", "bodies", "timelines"]) || !uuid(snapshot.id) || snapshot.repository !== repository || snapshot.name !== name2 || !dataVersion(snapshot.version) || !time2(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 invalid9();
8088
+ if (Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== snapshotAcquisitionFormat || !keys4(snapshot, ["id", "name", "refreshedAt", "repository", "version", "collections", "bodies", "timelines"]) || !uuid(snapshot.id) || snapshot.repository !== repository || snapshot.name !== name2 || !dataVersion(snapshot.version) || !time2(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 invalid10();
7989
8089
  let bodies = snapshot.bodies === void 0 ? [] : snapshot.bodies, timelines = snapshot.timelines === void 0 ? [] : snapshot.timelines;
7990
- 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 invalid9();
8090
+ 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 invalid10();
7991
8091
  return {
7992
8092
  snapshot: { ...snapshot, bodies, timelines },
7993
8093
  changes: validateSnapshotChanges(row.changes, snapshot.collections)
@@ -7995,47 +8095,47 @@ function validateAcquisition(input, repository, name2) {
7995
8095
  }
7996
8096
  function validateSnapshotChanges(input, collections) {
7997
8097
  try {
7998
- if (!Array.isArray(input)) return invalid9();
8098
+ if (!Array.isArray(input)) return invalid10();
7999
8099
  let ids = /* @__PURE__ */ new Set(), unpublished = !1;
8000
8100
  for (let value of input) {
8001
8101
  let c = object6(value), effect = object6(c.effect);
8002
- if (!keys4(c, ["id", "version", "ref", "recordVersion", "effect", "updatedAt", "person", "source", "publication"]) || !uuid(c.id) || ids.has(c.id) || !dataVersion(c.version) || !validRecordRef(c.ref) || !collections.some((name2) => c.ref.startsWith(`${name2}/`)) || !recordVersion(c.recordVersion) || !time2(c.updatedAt)) return invalid9();
8102
+ if (!keys4(c, ["id", "version", "ref", "recordVersion", "effect", "updatedAt", "person", "source", "publication"]) || !uuid(c.id) || ids.has(c.id) || !dataVersion(c.version) || !validRecordRef(c.ref) || !collections.some((name2) => c.ref.startsWith(`${name2}/`)) || !recordVersion(c.recordVersion) || !time2(c.updatedAt)) return invalid10();
8003
8103
  if (ids.add(c.id), c.person !== void 0) {
8004
8104
  let person = object6(c.person);
8005
- if (!keys4(person, ["id", "name", "email"]) || !uuid(person.id) || person.name !== void 0 && !dataText(person.name) || person.email !== void 0 && !dataText(person.email)) return invalid9();
8105
+ if (!keys4(person, ["id", "name", "email"]) || !uuid(person.id) || person.name !== void 0 && !dataText(person.name) || person.email !== void 0 && !dataText(person.email)) return invalid10();
8006
8106
  }
8007
8107
  if (c.source !== void 0) {
8008
8108
  let source2 = object6(c.source);
8009
- if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid9();
8109
+ if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid10();
8010
8110
  }
8011
8111
  if (c.publication !== void 0) {
8012
8112
  let publication = object6(c.publication);
8013
- if (unpublished || Object.keys(publication).sort().join(",") !== "commit,time" || typeof publication.commit != "string" || !/^[0-9a-f]{40}$/.test(publication.commit) || !time2(publication.time)) return invalid9();
8113
+ if (unpublished || Object.keys(publication).sort().join(",") !== "commit,time" || typeof publication.commit != "string" || !/^[0-9a-f]{40}$/.test(publication.commit) || !time2(publication.time)) return invalid10();
8014
8114
  } else unpublished = !0;
8015
8115
  if (effect.kind === "set") {
8016
- if (Object.keys(effect).sort().join(",") !== "field,kind,value" || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field)) return invalid9();
8116
+ if (Object.keys(effect).sort().join(",") !== "field,kind,value" || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field)) return invalid10();
8017
8117
  } else if (effect.kind === "link" || effect.kind === "unlink") {
8018
- if (!keys4(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 invalid9();
8118
+ if (!keys4(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 invalid10();
8019
8119
  } else if (effect.kind === "signal") {
8020
- if (Object.keys(effect).sort().join(",") !== "key,kind,value") return invalid9();
8120
+ if (Object.keys(effect).sort().join(",") !== "key,kind,value") return invalid10();
8021
8121
  let value2 = object6(effect.value);
8022
- if (!keys4(value2, ["label", "status", "reason", "related", "asOf", "number"])) return invalid9();
8122
+ if (!keys4(value2, ["label", "status", "reason", "related", "asOf", "number"])) return invalid10();
8023
8123
  let { number, ...assessment } = value2;
8024
8124
  captureSignal({ ...assessment, key: effect.key }), (c.publication || Object.hasOwn(value2, "number")) && captureRecordSignal({ ...value2, key: effect.key });
8025
8125
  } else if (effect.kind === "timeline") {
8026
- if (Object.keys(effect).sort().join(",") !== "entry,kind") return invalid9();
8126
+ if (Object.keys(effect).sort().join(",") !== "entry,kind") return invalid10();
8027
8127
  captureTimeline(effect.entry);
8028
8128
  } else if (effect.kind === "create" || effect.kind === "delete") {
8029
- if (!keys4(effect, ["fields", "kind", "signals", "timeline"])) return invalid9();
8129
+ if (!keys4(effect, ["fields", "kind", "signals", "timeline"])) return invalid10();
8030
8130
  if (object6(effect.fields), Object.hasOwn(effect, "signals") && captureRecordSignals(effect.signals), Object.hasOwn(effect, "timeline")) {
8031
- if (!Array.isArray(effect.timeline)) return invalid9();
8131
+ if (!Array.isArray(effect.timeline)) return invalid10();
8032
8132
  effect.timeline.forEach((value2) => captureTimeline(value2));
8033
8133
  }
8034
- } else return invalid9();
8134
+ } else return invalid10();
8035
8135
  }
8036
8136
  return input;
8037
8137
  } catch {
8038
- return invalid9();
8138
+ return invalid10();
8039
8139
  }
8040
8140
  }
8041
8141
  function materializeSnapshot(envelope, changes, version) {
@@ -8044,13 +8144,13 @@ function materializeSnapshot(envelope, changes, version) {
8044
8144
  let rows = new Map(Object.values(envelope.collections).flat().map((r) => [r.$ref, structuredClone(r)]));
8045
8145
  for (let c of changes) {
8046
8146
  let schema2 = snapshotCollection(envelope.catalogue, c.ref);
8047
- if (!schema2) return invalid9();
8147
+ if (!schema2) return invalid10();
8048
8148
  let effect = c.effect, definitions2 = "field" in effect ? schema2.schema.fields.filter((f) => f.name === effect.field) : schema2.schema.fields;
8049
- if ("field" in effect && !definitions2.length) return invalid9();
8149
+ if ("field" in effect && !definitions2.length) return invalid10();
8050
8150
  let values;
8051
8151
  if (effect.kind === "link" || effect.kind === "unlink") {
8052
8152
  let field = definitions2[0];
8053
- if (field.kind !== "link" || !field.many && effect.kind === "link" && effect.refs.length !== 1) return invalid9();
8153
+ if (field.kind !== "link" || !field.many && effect.kind === "link" && effect.refs.length !== 1) return invalid10();
8054
8154
  let targets = [...effect.refs, ...effect.kind === "link" ? effect.remove ?? [] : []];
8055
8155
  for (let ref of targets) validateRecordFields({ [effect.field]: field.many ? [ref] : ref }, definitions2, (_ref, allowed) => allowed[0], !0);
8056
8156
  values = { [effect.field]: field.many ? effect.refs : effect.refs[0] };
@@ -8063,25 +8163,25 @@ function materializeSnapshot(envelope, changes, version) {
8063
8163
  ), !c.publication) continue;
8064
8164
  let prior = rows.get(c.ref);
8065
8165
  if (effect.kind === "set") {
8066
- if (!prior) return invalid9();
8166
+ if (!prior) return invalid10();
8067
8167
  rows.set(c.ref, { ...prior, [effect.field]: effect.value, $version: c.recordVersion });
8068
8168
  } else if (effect.kind === "link" || effect.kind === "unlink") {
8069
- if (!prior) return invalid9();
8169
+ if (!prior) return invalid10();
8070
8170
  let field = definitions2[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;
8071
8171
  rows.set(c.ref, { ...prior, [effect.field]: value, $version: c.recordVersion });
8072
8172
  } else if (effect.kind === "signal") {
8073
- if (!prior || !effect.value.number) return invalid9();
8173
+ if (!prior || !effect.value.number) return invalid10();
8074
8174
  let signal = captureRecordSignal({ ...effect.value, key: effect.key }), signals = captureRecordSignals(prior.$signals), index = signals.findIndex((row) => row.key === effect.key);
8075
8175
  index < 0 ? signals.push(signal) : signals[index] = signal, rows.set(c.ref, { ...prior, $signals: captureRecordSignals(signals), $version: c.recordVersion });
8076
8176
  } else if (effect.kind === "timeline") {
8077
- if (!prior) return invalid9();
8177
+ if (!prior) return invalid10();
8078
8178
  rows.set(c.ref, {
8079
8179
  ...prior,
8080
8180
  $version: c.recordVersion,
8081
8181
  ...envelope.timelineCollections.includes(schema2.name) ? { $timeline: [...prior.$timeline, effect.entry] } : {}
8082
8182
  });
8083
8183
  } else if (effect.kind === "create") {
8084
- if (prior) return invalid9();
8184
+ if (prior) return invalid10();
8085
8185
  rows.set(c.ref, {
8086
8186
  ...effect.fields,
8087
8187
  $ref: c.ref,
@@ -8090,7 +8190,7 @@ function materializeSnapshot(envelope, changes, version) {
8090
8190
  ...envelope.timelineCollections.includes(schema2.name) ? { $timeline: effect.timeline ?? [] } : {}
8091
8191
  });
8092
8192
  } else {
8093
- if (!prior) return invalid9();
8193
+ if (!prior) return invalid10();
8094
8194
  rows.delete(c.ref);
8095
8195
  }
8096
8196
  }
@@ -8099,16 +8199,11 @@ function materializeSnapshot(envelope, changes, version) {
8099
8199
  repository: envelope.repository,
8100
8200
  name: envelope.name,
8101
8201
  version,
8102
- schemas: Object.fromEntries(envelope.catalogue.map((c) => [c.name, {
8103
- name: c.name,
8104
- type: c.schema.type,
8105
- ...c.schema.description === void 0 ? {} : { description: c.schema.description },
8106
- fields: c.schema.fields.map(publicField)
8107
- }])),
8202
+ schemas: Object.fromEntries(envelope.catalogue.map((c) => [c.name, publicCollectionSchema(c)])),
8108
8203
  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)]))
8109
8204
  }, envelope.repository, envelope.name, envelope.bodyCollections, envelope.timelineCollections), ...envelope.history ? { history: envelope.history } : {} };
8110
8205
  } catch {
8111
- return invalid9();
8206
+ return invalid10();
8112
8207
  }
8113
8208
  }
8114
8209
 
@@ -8150,12 +8245,7 @@ function applySnapshotMutation(envelope, prior, mutation, installation) {
8150
8245
  repository: envelope.repository,
8151
8246
  name: envelope.name,
8152
8247
  version: `snapshot-${crypto.randomUUID()}`,
8153
- schemas: Object.fromEntries(envelope.catalogue.map((c) => [c.name, {
8154
- name: c.name,
8155
- type: c.schema.type,
8156
- ...c.schema.description === void 0 ? {} : { description: c.schema.description },
8157
- fields: c.schema.fields.map(publicField)
8158
- }])),
8248
+ schemas: Object.fromEntries(envelope.catalogue.map((c) => [c.name, publicCollectionSchema(c)])),
8159
8249
  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)]))
8160
8250
  }, envelope.repository, envelope.name, envelope.bodyCollections, envelope.timelineCollections), { envelope, changes };
8161
8251
  }
@@ -8602,19 +8692,19 @@ function captureSelection(input) {
8602
8692
  }
8603
8693
  }
8604
8694
 
8605
- var invalid10 = () => {
8695
+ var invalid11 = () => {
8606
8696
  throw new DataOperationError("invalid_query");
8607
8697
  };
8608
8698
  function captureSnapshotAll(query, options) {
8609
8699
  let properties = dataProperties(options);
8610
- return Object.keys(properties).some((key) => !["maxRecords", "body", "timeline"].includes(key)) || properties.body && properties.body.value !== !0 || properties.timeline && properties.timeline.value !== !0 ? invalid10() : { ...captureRecordsAll(query, { maxRecords: properties.maxRecords?.value }), body: properties.body?.value === !0, timeline: properties.timeline?.value === !0 };
8700
+ return Object.keys(properties).some((key) => !["maxRecords", "body", "timeline"].includes(key)) || properties.body && properties.body.value !== !0 || properties.timeline && properties.timeline.value !== !0 ? invalid11() : { ...captureRecordsAll(query, { maxRecords: properties.maxRecords?.value }), body: properties.body?.value === !0, timeline: properties.timeline?.value === !0 };
8611
8701
  }
8612
8702
  var safeName = (value) => typeof value == "string" && /^[a-z0-9][a-z0-9._-]{0,127}$/.test(value) && !value.includes("..");
8613
8703
  function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore, connect = (url, protocols) => new WebSocket(url, protocols)) {
8614
8704
  let pending = /* @__PURE__ */ new WeakMap();
8615
8705
  return async function(input) {
8616
8706
  let properties = dataProperties(input), repository = properties.repository?.value, snapshot = properties.snapshot?.value;
8617
- if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid10();
8707
+ if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid11();
8618
8708
  let authority2 = await resolve(), invalidated = !1, stopLive, assertCurrent = () => {
8619
8709
  if (invalidated || authority2.signal.aborted || !authority2.isCurrent() || !authority2.refresh && authority2.expiresAt <= Date.now())
8620
8710
  throw invalidated = !0, stopLive?.(), new DataOperationError("context_unavailable");
@@ -8725,7 +8815,10 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8725
8815
  headers: { ...authority2.headers, "content-type": "application/json" },
8726
8816
  body: JSON.stringify(body)
8727
8817
  });
8728
- if (!response2.ok) throw dataTransportError(response2.status, await response2.json());
8818
+ if (!response2.ok) {
8819
+ let failure = dataTransportError(response2.status, await response2.json());
8820
+ throw publication && failure.effect === "unapplied" && (publication.id = crypto.randomUUID()), failure;
8821
+ }
8729
8822
  applied = !0;
8730
8823
  let value = await response2.json(), mutation;
8731
8824
  if (kind === "discard") {
@@ -8747,15 +8840,15 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8747
8840
  let update = snapshotDifference(before, await store.changes(installation));
8748
8841
  return kind === "publish" && (update.records = !0), assertAccess(), publication && (publication.complete = !0), live2.notify(update), assertAccess(), structuredClone(mutation.changes ?? []);
8749
8842
  } catch (error) {
8750
- let failure = error instanceof DataOperationError ? error : new DataOperationError("unavailable"), effect = applied ? "applied" : dispatched ? failure.effect ?? "uncertain" : "unapplied";
8843
+ let failure = error instanceof DataOperationError ? error : new DataOperationError("unavailable", dispatched && kind === "publish"), effect = applied ? "applied" : dispatched ? failure.effect ?? "uncertain" : "unapplied";
8751
8844
  throw effect !== "unapplied" && (kind !== "publish" || effect === "applied") && (invalidated = !0, live2.stop(), await store?.invalidate(installation).catch(() => {
8752
- })), new DataOperationError(
8845
+ })), explainDataValidation(new DataOperationError(
8753
8846
  failure.code,
8754
- effect === "uncertain" ? kind === "publish" : effect === "applied" ? !1 : failure.retryable,
8847
+ effect === "uncertain" ? kind === "publish" && failure.retryable : effect === "applied" ? !1 : failure.retryable,
8755
8848
  effect,
8756
8849
  failure.component,
8757
8850
  failure.detail
8758
- );
8851
+ ), failure.message, failure.detail);
8759
8852
  } finally {
8760
8853
  store?.close();
8761
8854
  }
@@ -8772,7 +8865,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8772
8865
  let store;
8773
8866
  try {
8774
8867
  let selections = planIndexQuery(captured, pinned.catalogue), checkTimeline = (collection, selection2) => {
8775
- if ((timeline || selection2.timeline) && !pinned.timelineCollections.includes(collection)) return invalid10();
8868
+ if ((timeline || selection2.timeline) && !pinned.timelineCollections.includes(collection)) return invalid11();
8776
8869
  for (let link of selection2.links) for (let [name2, nested] of link.targets) checkTimeline(name2, nested);
8777
8870
  };
8778
8871
  for (let { name: name2, selection: selection2 } of selections) checkTimeline(name2, selection2);
@@ -8850,7 +8943,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8850
8943
  return snapshotCollection(installation.catalogue, captured) ? writes.then(() => {
8851
8944
  let pinned = installation;
8852
8945
  return localRead(async (store) => {
8853
- if (timeline && !pinned.timelineCollections.includes(snapshotCollection(pinned.catalogue, captured).name)) return invalid10();
8946
+ if (timeline && !pinned.timelineCollections.includes(snapshotCollection(pinned.catalogue, captured).name)) return invalid11();
8854
8947
  let record4 = await store.read(pinned, captured);
8855
8948
  if (!record4) return record4;
8856
8949
  let { $body, $timeline, ...structured } = record4;
@@ -9037,7 +9130,7 @@ async function hostedContent(url, init2, parent, upstream = fetch, check = async
9037
9130
  }
9038
9131
  }
9039
9132
 
9040
- 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 = [], invalid11 = () => new FileOperationError("invalid_input", 400), unavailable4 = () => new FileOperationError("unavailable", 503, !0), failures = {
9133
+ 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 = [], invalid12 = () => new FileOperationError("invalid_input", 400), unavailable4 = () => new FileOperationError("unavailable", 503, !0), failures = {
9041
9134
  400: ["invalid_input", "unsupported_context"],
9042
9135
  401: ["unauthenticated"],
9043
9136
  403: ["access_denied"],
@@ -9193,7 +9286,7 @@ async function send(suffix, init2, descriptor, initial, parent) {
9193
9286
  throw unavailable4();
9194
9287
  }
9195
9288
  function idPath(id3) {
9196
- if (typeof id3 != "string" || !FILE_ID_PATTERN.test(id3)) throw invalid11();
9289
+ if (typeof id3 != "string" || !FILE_ID_PATTERN.test(id3)) throw invalid12();
9197
9290
  return `/${id3}`;
9198
9291
  }
9199
9292
  async function multipartCreate(input, metadata, exchange, release, upload, expectedSha256) {
@@ -9236,18 +9329,18 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
9236
9329
  if (!chunk || offset === chunk.byteLength) {
9237
9330
  chunk = void 0, offset = 0;
9238
9331
  let value2 = await next();
9239
- if (value2.done || !(value2.value instanceof Uint8Array) || (chunk = value2.value, chunk.byteLength > metadata.size - sent - filled)) throw invalid11();
9332
+ if (value2.done || !(value2.value instanceof Uint8Array) || (chunk = value2.value, chunk.byteLength > metadata.size - sent - filled)) throw invalid12();
9240
9333
  }
9241
9334
  let take = Math.min(length - filled, chunk.byteLength - offset);
9242
9335
  part.set(chunk.subarray(offset, offset + take), filled), filled += take, offset += take, offset === chunk.byteLength && (chunk = void 0, offset = 0);
9243
9336
  }
9244
9337
  }
9245
- if (part.byteLength !== length) throw invalid11();
9338
+ if (part.byteLength !== length) throw invalid12();
9246
9339
  if (reader && sent + length === metadata.size)
9247
9340
  for (lastProgress = Date.now(); ; ) {
9248
9341
  let value2 = await next();
9249
9342
  if (value2.done) break;
9250
- if (!(value2.value instanceof Uint8Array) || value2.value.byteLength) throw invalid11();
9343
+ if (!(value2.value instanceof Uint8Array) || value2.value.byteLength) throw invalid12();
9251
9344
  }
9252
9345
  let value = await request3((signal) => exchange(`${route}/part`, {
9253
9346
  method: "POST",
@@ -9261,7 +9354,7 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
9261
9354
  }
9262
9355
  if (upload) for (let name2 of Object.keys(upload.file.enrichments)) {
9263
9356
  let bytes = await request3(() => upload.enrichment(name2));
9264
- if (bytes.byteLength !== upload.file.enrichments[name2].size || bytes.byteLength > MAX_BYTES) throw invalid11();
9357
+ if (bytes.byteLength !== upload.file.enrichments[name2].size || bytes.byteLength > MAX_BYTES) throw invalid12();
9265
9358
  await request3((signal) => exchange(`${route}/enrichments/${encodeURIComponent(name2)}`, {
9266
9359
  method: "POST",
9267
9360
  headers: { "content-type": "application/octet-stream", "x-os-transfer": ticket },
@@ -9303,7 +9396,7 @@ async function operation(work, initial, parent) {
9303
9396
  function contentPath(id3, name2) {
9304
9397
  let path = idPath(id3);
9305
9398
  if (name2 === void 0) return `${path}/content`;
9306
- if (!safeEnrichmentName(name2)) throw invalid11();
9399
+ if (!safeEnrichmentName(name2)) throw invalid12();
9307
9400
  return `${path}/enrichments/${encodeURIComponent(name2)}/content`;
9308
9401
  }
9309
9402
  async function read(id3, names) {
@@ -9312,12 +9405,12 @@ async function read(id3, names) {
9312
9405
  let path = contentPath(id3, names);
9313
9406
  return operation((context2, signal) => send(path, { method: "GET" }, !1, context2, signal), context);
9314
9407
  }
9315
- if (!Array.isArray(names)) throw invalid11();
9408
+ if (!Array.isArray(names)) throw invalid12();
9316
9409
  let distinct = [], seen = /* @__PURE__ */ new Set();
9317
9410
  for (let name2 of names) {
9318
- if (typeof name2 != "string" || !safeEnrichmentName(name2)) throw invalid11();
9411
+ if (typeof name2 != "string" || !safeEnrichmentName(name2)) throw invalid12();
9319
9412
  if (!seen.has(name2)) {
9320
- if (seen.size === 16) throw invalid11();
9413
+ if (seen.size === 16) throw invalid12();
9321
9414
  seen.add(name2), distinct.push(name2);
9322
9415
  }
9323
9416
  }
@@ -9357,9 +9450,9 @@ var files = {
9357
9450
  async create(input, options) {
9358
9451
  let context = await resolveFilesContext();
9359
9452
  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")))
9360
- throw invalid11();
9453
+ throw invalid12();
9361
9454
  let blob = input.file instanceof Blob, array3 = input.file instanceof Uint8Array, stream = input.file instanceof ReadableStream;
9362
- if (!blob && !array3 && !stream) throw invalid11();
9455
+ if (!blob && !array3 && !stream) throw invalid12();
9363
9456
  let intrinsic = blob ? input.file.size : array3 ? input.file.byteLength : void 0;
9364
9457
  if (intrinsic !== void 0 && input.size !== void 0 && input.size !== intrinsic)
9365
9458
  throw !Number.isSafeInteger(input.size) || input.size < 0 ? new FileOperationError("invalid_input", 400, !1, { reason: "invalid_size" }) : new FileOperationError(
@@ -9380,7 +9473,7 @@ var files = {
9380
9473
  }, FILE_ORIGINAL_MAX_BYTES);
9381
9474
  if (!context.local && !context.localFiles && metadata.storage === "local") throw new FileOperationError("unsupported_context", 400);
9382
9475
  let header = encodeURIComponent(JSON.stringify(metadata));
9383
- if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid11();
9476
+ if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid12();
9384
9477
  let release = await acquireSlot(context.signal);
9385
9478
  if (context.localFiles && !routineTransport() && metadata.size > MAX_BYTES)
9386
9479
  try {
@@ -9401,7 +9494,8 @@ var files = {
9401
9494
  } finally {
9402
9495
  release();
9403
9496
  }
9404
- return metadata.size > MAX_BYTES ? multipartCreate(input, metadata, (suffix, init2, kind, signal) => kind === !0 ? send(suffix, init2, !0, context, signal) : send(suffix, init2, "control", context, signal), release) : timed(async (signal) => {
9497
+ if (metadata.size > MAX_BYTES) return multipartCreate(input, metadata, (suffix, init2, kind, signal) => kind === !0 ? send(suffix, init2, !0, context, signal) : send(suffix, init2, "control", context, signal), release);
9498
+ let execute = async (signal) => {
9405
9499
  try {
9406
9500
  let bytes = array3 ? new Uint8Array(input.file) : await boundedBytes(
9407
9501
  blob ? input.file.stream() : input.file,
@@ -9423,13 +9517,14 @@ var files = {
9423
9517
  } finally {
9424
9518
  release();
9425
9519
  }
9426
- }, context.signal).catch((error) => {
9520
+ };
9521
+ return (context.localFiles ? execute(context.signal ?? new AbortController().signal) : timed(execute, context.signal)).catch((error) => {
9427
9522
  throw error instanceof FileOperationError ? error : unavailable4();
9428
9523
  });
9429
9524
  },
9430
9525
  async enrich(input) {
9431
9526
  let context = await resolveFilesContext();
9432
- 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 invalid11();
9527
+ 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 invalid12();
9433
9528
  let path = `${idPath(input.file)}/enrichments`;
9434
9529
  if (typeof input.content == "string" ? input.content.length > MAX_BYTES : input.content.byteLength > MAX_BYTES)
9435
9530
  throw new FileOperationError("request_too_large", 413);
@@ -9446,7 +9541,7 @@ var files = {
9446
9541
  ...input.mediaType === void 0 ? {} : { mediaType: input.mediaType },
9447
9542
  ...input.replace === void 0 ? {} : { replace: input.replace }
9448
9543
  }, MAX_BYTES), header = encodeURIComponent(JSON.stringify(metadata));
9449
- if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid11();
9544
+ if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid12();
9450
9545
  let result2 = await send(path, { method: "POST", headers: {
9451
9546
  "content-type": "application/octet-stream",
9452
9547
  "x-os-enrichment": header
@@ -9993,13 +10088,29 @@ function parseInboxRecordRefs(value) {
9993
10088
  }
9994
10089
  var recordKey = ({ repository, ref }) => JSON.stringify([repository, ref]);
9995
10090
  function parseInboxRecords(value) {
9996
- let result2 = serializable(value);
9997
- if (!result2 || Object.keys(result2).join() !== "records" || !Array.isArray(result2.records) || result2.records.length > 100) throw new Error("Invalid Record result");
9998
- for (let entry of result2.records)
10091
+ let result2 = serializable(value), keys7 = result2 ? Object.keys(result2).sort().join() : "";
10092
+ if (!result2 || !["records", "links,records"].includes(keys7) || !Array.isArray(result2.records) || result2.records.length > 100) throw new Error("Invalid Record result");
10093
+ for (let entry of result2.records) {
10094
+ if (!entry || typeof entry != "object") throw new Error("Invalid current Record");
9999
10095
  if (validateQualifiedRecordRef({ repository: entry.repository, ref: entry.ref }), Object.keys(entry).sort().join() !== "record,ref,repository,schema" || (entry.record === null ? entry.schema !== null : !entry.schema || entry.record.$ref !== entry.ref || typeof entry.record.$version != "string" || !Array.isArray(entry.schema.fields) || typeof entry.schema.name != "string"))
10000
10096
  throw new Error("Invalid current Record");
10097
+ if (entry.schema)
10098
+ try {
10099
+ if (JSON.stringify(parseRecordDisplay(entry.schema.display, entry.schema.fields)) !== JSON.stringify(entry.schema.display))
10100
+ throw new Error("Invalid current Record");
10101
+ } catch {
10102
+ throw new Error("Invalid current Record");
10103
+ }
10104
+ }
10001
10105
  if (new Set(result2.records.map(recordKey)).size !== result2.records.length) throw new Error("Duplicate current Record");
10002
- return result2;
10106
+ let links = keys7 === "records" ? [] : result2.links;
10107
+ if (!Array.isArray(links)) throw new Error("Invalid Record links");
10108
+ for (let link of links) {
10109
+ if (!link || typeof link != "object" || Object.keys(link).sort().join() !== "ref,repository,title" || typeof link.title != "string" || !link.title.trim()) throw new Error("Invalid Record link");
10110
+ validateQualifiedRecordRef({ repository: link.repository, ref: link.ref });
10111
+ }
10112
+ if (new Set(links.map(recordKey)).size !== links.length) throw new Error("Duplicate Record link");
10113
+ return { records: result2.records, links };
10003
10114
  }
10004
10115
 
10005
10116
  var InboxOperationError = class extends Error {
@@ -10044,9 +10155,9 @@ function parseInboxUnavailableFailure(value, status) {
10044
10155
  return;
10045
10156
  }
10046
10157
  }
10047
- var INBOX_RESULT_BYTES = 8 * 1024 * 1024, INBOX_INPUT_BYTES = 8192, INBOX_LOCAL_INPUT_BYTES = 256 * 1024, INBOX_QUESTION_CONTRACT = "question-work-v1", INBOX_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
10158
+ var INBOX_RESULT_BYTES = 8 * 1024 * 1024, INBOX_INPUT_BYTES = 8192, INBOX_LOCAL_INPUT_BYTES = 256 * 1024, INBOX_QUESTION_CONTRACT = "question-work-v2", INBOX_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
10048
10159
  function isAppQuestionOperation(operation2) {
10049
- return operation2 === "questions.list" || operation2 === "questions.answer" || operation2 === "questions.searchRecords";
10160
+ return operation2 === "questions.list" || operation2 === "questions.answer" || operation2 === "questions.listRecordOptions";
10050
10161
  }
10051
10162
  var operations = {
10052
10163
  current: [],
@@ -10061,7 +10172,7 @@ var operations = {
10061
10172
  "items.listRecipientCandidates": ["itemId"],
10062
10173
  "items.addRecipient": ["itemId", "personId"],
10063
10174
  "questions.answer": ["itemId", "revision", "questionId", "response", "submissionKey"],
10064
- "questions.searchRecords": ["itemId", "revision", "questionId", "query"]
10175
+ "questions.listRecordOptions": ["itemId", "revision", "questionId"]
10065
10176
  };
10066
10177
  function assert(value) {
10067
10178
  if (!value) throw new Error("Invalid Inbox result");
@@ -10109,21 +10220,58 @@ function recordReference(value) {
10109
10220
  let record4 = object8(value);
10110
10221
  return keys6(record4, ["repository", "ref"]), assert(text4(record4.repository) && record4.repository === record4.repository.trim() && /^[a-z0-9][a-z0-9._/-]{0,127}$/.test(record4.repository) && !/\.\.|\/\//.test(record4.repository) && text4(record4.ref) && record4.ref === record4.ref.trim() && record4.ref.length <= 512 && /^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(record4.ref)), record4;
10111
10222
  }
10223
+ function choiceValue(value) {
10224
+ assert(text4(value) && value === value.trim());
10225
+ }
10226
+ function choiceDetails(option) {
10227
+ if ("description" in option && assert(text4(option.description)), "note" in option) {
10228
+ let note = object8(option.note);
10229
+ keys6(note, ["placeholder"]), assert(text4(note.placeholder));
10230
+ }
10231
+ }
10232
+ function pickerSource(value) {
10233
+ let source2 = object8(value), collection = object8(source2.collection);
10234
+ keys6(collection, ["repository", "name"]), recordReference({ repository: collection.repository, ref: "records/example" }), assert(text4(collection.name) && /^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(collection.name)), "refPrefix" in source2 && assert(text4(source2.refPrefix) && source2.refPrefix.length <= 512 && /^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)*\/$/.test(source2.refPrefix));
10235
+ let where = object8(source2.where ?? {});
10236
+ return assert(Object.entries(where).every(([name2, value2]) => /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name2) && !["constructor", "prototype"].includes(name2) && (value2 === null || typeof value2 == "string" || typeof value2 == "boolean" || typeof value2 == "number" && Number.isFinite(value2)))), collection;
10237
+ }
10112
10238
  function responseDefinition(value) {
10113
10239
  let definition = object8(value);
10114
- keys6(definition, ["type", "source"]), assert(definition.type === "selection");
10240
+ if (assert(definition.type === "selection"), "options" in definition) {
10241
+ keys6(definition, ["type", "options"]);
10242
+ let options = array2(definition.options);
10243
+ assert(options.length > 0 && options.length <= 9), options.forEach((value2, index) => {
10244
+ let option = object8(value2);
10245
+ switch (assert(option.id === index + 1 && text4(option.label)), option.type) {
10246
+ case "choice":
10247
+ case "record":
10248
+ keys6(
10249
+ option,
10250
+ ["id", "type", "value", "label", "description", ...option.type === "choice" ? ["note"] : []],
10251
+ []
10252
+ ), option.type === "choice" ? choiceValue(option.value) : recordReference(option.value), choiceDetails(option);
10253
+ break;
10254
+ case "record-picker": {
10255
+ keys6(option, ["id", "type", "label", "source"]);
10256
+ let source3 = object8(option.source);
10257
+ keys6(source3, ["collection", "where", "refPrefix"], []), "where" in source3 && object8(source3.where), pickerSource(source3);
10258
+ break;
10259
+ }
10260
+ default:
10261
+ assert(!1);
10262
+ }
10263
+ });
10264
+ return;
10265
+ }
10266
+ keys6(definition, ["type", "source"]);
10115
10267
  let source2 = object8(definition.source);
10116
10268
  if (source2.type === "authored") {
10117
- keys6(source2, ["type", "options", "suggestions", "search"], ["type", "options"]);
10269
+ keys6(source2, ["type", "options", "suggestions", "search"], []);
10118
10270
  let options = array2(source2.options);
10119
10271
  assert(options.length > 0);
10120
10272
  let values = options.map((value2) => {
10121
10273
  let option = object8(value2);
10122
- if (keys6(option, ["value", "label", "description", "note"], ["value", "label"]), assert(text4(option.value) && option.value === option.value.trim() && text4(option.label)), "description" in option && assert(text4(option.description)), "note" in option) {
10123
- let note = object8(option.note);
10124
- keys6(note, ["placeholder"]), assert(text4(note.placeholder));
10125
- }
10126
- return option.value;
10274
+ return keys6(option, ["value", "label", "description", "note"], []), choiceValue(option.value), assert(text4(option.label)), choiceDetails(option), option.value;
10127
10275
  });
10128
10276
  if (assert(new Set(values).size === values.length), "search" in source2 || "suggestions" in source2) {
10129
10277
  let search = object8(source2.search);
@@ -10134,11 +10282,7 @@ function responseDefinition(value) {
10134
10282
  return;
10135
10283
  }
10136
10284
  assert(source2.type === "records"), keys6(source2, ["type", "collection", "refPrefix", "where", "display", "suggestions"], ["type", "collection", "display"]);
10137
- let collection = object8(source2.collection);
10138
- keys6(collection, ["repository", "name"]), recordReference({ repository: collection.repository, ref: "records/example" }), assert(text4(collection.name) && /^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(collection.name)), "refPrefix" in source2 && assert(text4(source2.refPrefix) && source2.refPrefix.length <= 512 && /^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)*\/$/.test(source2.refPrefix));
10139
- let where = object8(source2.where ?? {});
10140
- assert(Object.entries(where).every(([name2, value2]) => /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name2) && !["constructor", "prototype"].includes(name2) && (value2 === null || typeof value2 == "string" || typeof value2 == "boolean" || typeof value2 == "number" && Number.isFinite(value2))));
10141
- let display = object8(source2.display);
10285
+ let collection = pickerSource(source2), display = object8(source2.display);
10142
10286
  keys6(display, ["labelFields"]);
10143
10287
  let labels = array2(display.labelFields);
10144
10288
  assert(labels.length > 0 && labels.length <= 2 && new Set(labels).size === labels.length && labels.every((value2) => text4(value2) && /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(value2)));
@@ -10150,22 +10294,32 @@ function responseDefinition(value) {
10150
10294
  });
10151
10295
  assert(suggestions.length <= 8 && new Set(refs).size === refs.length);
10152
10296
  }
10153
- function response(value) {
10154
- let answer = object8(value);
10155
- return assert(Object.keys(answer).every((key) => ["selection", "note"].includes(key))), typeof answer.selection == "string" ? assert(text4(answer.selection) && answer.selection === answer.selection.trim()) : recordReference(answer.selection), Object.hasOwn(answer, "note") && assert(text4(answer.note)), answer;
10297
+ function response(value, definition, numbered = !1) {
10298
+ let answer = object8(value), options = definition && "options" in definition ? array2(definition.options) : void 0, selected = options || numbered ? answer.value : answer.selection;
10299
+ if (typeof selected == "string" ? choiceValue(selected) : recordReference(selected), options || numbered) {
10300
+ if (keys6(answer, ["option", "value", "note"], []), assert(integer(answer.option) && answer.option <= (options?.length ?? 9)), options) {
10301
+ let option = object8(options[answer.option - 1]);
10302
+ assert(option.type === "choice" == (typeof selected == "string")), assert("note" in answer == (option.type === "choice" && "note" in option));
10303
+ }
10304
+ } else assert(Object.keys(answer).every((key) => ["selection", "note"].includes(key)));
10305
+ return Object.hasOwn(answer, "note") && assert(text4(answer.note)), answer;
10156
10306
  }
10157
10307
  function parseInboxRequest(value) {
10158
10308
  try {
10159
10309
  let envelope = object8(value);
10160
10310
  assert(typeof envelope.operation == "string" && Object.hasOwn(operations, envelope.operation));
10161
10311
  let operation2 = envelope.operation, questionOperation = isAppQuestionOperation(operation2);
10162
- if (questionOperation && envelope.contract !== INBOX_QUESTION_CONTRACT)
10312
+ if (questionOperation && envelope.contract !== INBOX_QUESTION_CONTRACT && envelope.contract !== "question-work-v1")
10163
10313
  throw new InboxOperationError(426, "client_update_required");
10164
10314
  keys6(envelope, questionOperation ? ["contract", "input", "operation"] : ["input", "operation"]);
10165
10315
  let input = { ...object8(envelope.input) }, required = operations[operation2];
10166
- assert(required.every((key) => Object.hasOwn(input, key)) && Object.keys(input).every((key) => required.includes(key) || operation2 === "questions.answer" && key === "label" || operation2 === "questions.searchRecords" && key === "selected" || (operation2 === "items.list" || operation2 === "questions.list") && key === "beforeNumber" || operation2 === "questions.list" && key === "routines")), operation2 === "questions.list" && (assert(Object.hasOwn(input, "routines")), assert(array2(input.routines).every(isAppRoutineName)));
10316
+ assert(required.every((key) => Object.hasOwn(input, key)) && Object.keys(input).every((key) => required.includes(key) || operation2 === "questions.answer" && key === "label" || operation2 === "questions.listRecordOptions" && envelope.contract === INBOX_QUESTION_CONTRACT && key === "option" || (operation2 === "items.list" || operation2 === "questions.list") && key === "beforeNumber" || operation2 === "questions.list" && key === "routines")), operation2 === "questions.list" && (assert(Object.hasOwn(input, "routines")), assert(array2(input.routines).every(isAppRoutineName)));
10167
10317
  for (let key of ["itemId", "personId", "fileId"]) key in input && assert(id2(input[key]));
10168
- return "revision" in input && assert(integer(input.revision)), "beforeNumber" in input && assert(integer(input.beforeNumber)), "questionId" in input && assert(text4(input.questionId) && input.questionId === input.questionId.trim()), "submissionKey" in input && assert(text4(input.submissionKey) && input.submissionKey.length <= 128 && input.submissionKey === input.submissionKey.trim()), "title" in input && assert(text4(input.title)), "lifecycle" in input && assert(input.lifecycle === "open" || input.lifecycle === "closed"), "query" in input && assert(text4(input.query, !0) && input.query.length <= 256), "records" in input && (input.records = parseInboxRecordRefs(input.records)), "selected" in input && recordReference(input.selected), "response" in input && response(input.response), "label" in input && assert(text4(input.label) && typeof input.response?.selection == "object"), assert(new TextEncoder().encode(JSON.stringify(envelope)).byteLength <= INBOX_INPUT_BYTES), "routines" in input && (input.routines = [...new Set(input.routines)]), { operation: operation2, input, ...isAppQuestionOperation(operation2) ? { contract: INBOX_QUESTION_CONTRACT } : {} };
10318
+ if ("revision" in input && assert(integer(input.revision)), "beforeNumber" in input && assert(integer(input.beforeNumber)), "questionId" in input && assert(text4(input.questionId) && input.questionId === input.questionId.trim()), "submissionKey" in input && assert(text4(input.submissionKey) && input.submissionKey.length <= 128 && input.submissionKey === input.submissionKey.trim()), "title" in input && assert(text4(input.title)), "lifecycle" in input && assert(input.lifecycle === "open" || input.lifecycle === "closed"), "records" in input && (input.records = parseInboxRecordRefs(input.records)), "option" in input && assert(integer(input.option) && input.option <= 9), "response" in input && response(input.response, void 0, envelope.contract === INBOX_QUESTION_CONTRACT && "option" in object8(input.response)), "label" in input) {
10319
+ let answer = object8(input.response);
10320
+ assert(text4(input.label) && typeof ("option" in answer ? answer.value : answer.selection) == "object");
10321
+ }
10322
+ return assert(new TextEncoder().encode(JSON.stringify(envelope)).byteLength <= INBOX_INPUT_BYTES), "routines" in input && (input.routines = [...new Set(input.routines)]), { operation: operation2, input, ...isAppQuestionOperation(operation2) ? { contract: envelope.contract } : {} };
10169
10323
  } catch (error) {
10170
10324
  throw error instanceof InboxOperationError ? error : new InboxOperationError(400, "invalid_input");
10171
10325
  }
@@ -10189,7 +10343,7 @@ function parseInboxItem(value) {
10189
10343
  let question2 = object8(value2);
10190
10344
  if (assert(text4(question2.id) && id2(question2.to) && text4(question2.prompt) && (question2.instructions === null || text4(question2.instructions, !0)) && typeof question2.available == "boolean"), questionAvailability(question2, question2.available), parseQuestionStatus(question2.status), assert(!("requirements" in question2) && !("requirementsRepository" in question2) && !("handler" in question2)), responseDefinition(question2.response), assert(array2(question2.allowedResponders).every(id2)), question2.acceptedResponse !== null) {
10191
10345
  let accepted = object8(question2.acceptedResponse);
10192
- assert(id2(accepted.id) && id2(accepted.userId) && date(accepted.acceptedAt)), response(accepted.response), accepted.label === null ? delete accepted.label : "label" in accepted && assert(text4(accepted.label)), "acceptanceOrder" in accepted && assert(integer(accepted.acceptanceOrder));
10346
+ assert(id2(accepted.id) && id2(accepted.userId) && date(accepted.acceptedAt)), response(accepted.response, object8(question2.response)), accepted.label === null ? delete accepted.label : "label" in accepted && assert(text4(accepted.label)), "acceptanceOrder" in accepted && assert(integer(accepted.acceptanceOrder));
10193
10347
  }
10194
10348
  if (question2.execution !== null) {
10195
10349
  let execution = object8(question2.execution);
@@ -10221,7 +10375,7 @@ function parseInboxItem(value) {
10221
10375
  assert(id2(work.id) && text4(work.questionId) && text4(work.reason) && optionalDate(work.settledAt));
10222
10376
  }), item;
10223
10377
  }
10224
- function parseQuestionWork(value) {
10378
+ function parseQuestionWork(value, contract = INBOX_QUESTION_CONTRACT) {
10225
10379
  let entry = object8(json2(value));
10226
10380
  keys6(
10227
10381
  entry,
@@ -10233,7 +10387,9 @@ function parseQuestionWork(value) {
10233
10387
  let assignee = object8(entry.assignee);
10234
10388
  keys6(assignee, ["id", "name"]), assert(id2(assignee.id) && text4(assignee.name));
10235
10389
  let status = parseQuestionStatus(entry.status);
10236
- return assert(status.code !== "completed" && (!entry.canAnswer || status.code === "awaiting_answer") && (!("unavailableReason" in entry) || status.code === "awaiting_answer")), status.code === "awaiting_answer" && assert(status.label === "Needs your answer" || !entry.canAnswer && status.label === `Waiting for ${assignee.name}`), responseDefinition(entry.response), askMetadata(entry), entry;
10390
+ if (assert(status.code !== "completed" && (!entry.canAnswer || status.code === "awaiting_answer") && (!("unavailableReason" in entry) || status.code === "awaiting_answer")), status.code === "awaiting_answer" && assert(status.label === "Needs your answer" || !entry.canAnswer && status.label === `Waiting for ${assignee.name}`), contract === "question-work-v1" && "options" in object8(entry.response))
10391
+ throw new InboxOperationError(426, "client_update_required");
10392
+ return responseDefinition(entry.response), askMetadata(entry), entry;
10237
10393
  }
10238
10394
  function parseQuestionStatus(value) {
10239
10395
  let status = object8(value), code = status.code;
@@ -10261,12 +10417,12 @@ function parseInboxAcceptance(value) {
10261
10417
  let accepted = object8(value);
10262
10418
  return assert(id2(accepted.responseId) && date(accepted.acceptedAt)), "executionId" in accepted && assert(id2(accepted.executionId)), "acceptanceOrder" in accepted && assert(integer(accepted.acceptanceOrder)), "label" in accepted && assert(text4(accepted.label)), accepted;
10263
10419
  }
10264
- function parseInboxResult(operation2, value) {
10420
+ function parseInboxResult(operation2, value, contract = INBOX_QUESTION_CONTRACT) {
10265
10421
  if (operation2 === "current") return parseInboxCurrent(value);
10266
10422
  if (operation2 === "questions.list") {
10267
10423
  let page = object8(value);
10268
10424
  keys6(page, ["questions", "nextBeforeNumber"]);
10269
- let questions = array2(page.questions).map(parseQuestionWork);
10425
+ let questions = array2(page.questions).map((value2) => parseQuestionWork(value2, contract));
10270
10426
  return assert(page.nextBeforeNumber === null || integer(page.nextBeforeNumber)), { questions, nextBeforeNumber: page.nextBeforeNumber };
10271
10427
  }
10272
10428
  if (operation2 === "items.readRecords") return parseInboxRecords(value);
@@ -10299,14 +10455,18 @@ function parseInboxResult(operation2, value) {
10299
10455
  return assert(id2(addition.addedPersonId) && item.people.some((person) => person.id === addition.addedPersonId)), { ...addition, item };
10300
10456
  }
10301
10457
  if (operation2 === "questions.answer") return parseInboxAcceptance(value);
10302
- if (operation2 === "questions.searchRecords") {
10458
+ if (operation2 === "questions.listRecordOptions") {
10303
10459
  let result2 = object8(value);
10304
- assert(text4(result2.recordType) && integer(result2.eligibleCount, 0) && integer(result2.matchCount, 0) && Number(result2.matchCount) <= Number(result2.eligibleCount));
10305
- let labeled = (value2) => {
10306
- let record4 = object8(value2);
10307
- recordReference({ repository: record4.repository, ref: record4.ref }), assert(text4(record4.label)), "reason" in record4 && assert(text4(record4.reason));
10308
- };
10309
- return array2(result2.matches).forEach(labeled), array2(result2.suggestions).forEach(labeled), "selected" in result2 && labeled(result2.selected), result2;
10460
+ keys6(result2, ["recordType", "eligibleCount", "options"]), assert(text4(result2.recordType) && integer(result2.eligibleCount, 0));
10461
+ let options = array2(result2.options);
10462
+ assert(options.length === result2.eligibleCount);
10463
+ let refs = /* @__PURE__ */ new Set();
10464
+ return options.forEach((value2) => {
10465
+ let option = object8(value2);
10466
+ keys6(option, ["repository", "ref", "label", "searchText"]), recordReference({ repository: option.repository, ref: option.ref }), assert(text4(option.label) && option.searchText === normalizeRecordOptionSearch(option.label));
10467
+ let key = JSON.stringify([option.repository, option.ref]);
10468
+ assert(!refs.has(key)), refs.add(key);
10469
+ }), assert(new TextEncoder().encode(JSON.stringify(result2)).byteLength <= recordOptionCatalogueByteLimit), result2;
10310
10470
  }
10311
10471
  throw new Error("File content is not a JSON result");
10312
10472
  }
@@ -10367,9 +10527,9 @@ function hostedInboxContext() {
10367
10527
  };
10368
10528
  check();
10369
10529
  let matches2 = (entry2) => entry2.endpoint === host.endpoint && entry2.memberId === host.memberId && entry2.valid();
10370
- if (mode === "list" && denied && matches2(denied)) throw new InboxContextError(denied.status);
10530
+ if (mode === "member" && denied && matches2(denied)) throw new InboxContextError(denied.status);
10371
10531
  let bind = (value) => ({ ...value, isCurrent: () => host.isCurrent() && host.expiresAt > Date.now() && value.isCurrent() });
10372
- if (mode === "list" && retained && matches2(retained)) return bind(retained.value);
10532
+ if (mode === "member" && retained && matches2(retained)) return bind(retained.value);
10373
10533
  if (mode !== "fresh" && pending && matches2(pending)) {
10374
10534
  let value = await pending.result;
10375
10535
  return check(), bind(value);
@@ -10679,7 +10839,7 @@ function appContext(origin, active2, changed) {
10679
10839
  }
10680
10840
  }
10681
10841
  async function requestInbox(operation2, input, signal) {
10682
- if (!["questions.list", "questions.answer", "questions.searchRecords"].includes(operation2)) throw new Error("Inbox operation unavailable");
10842
+ if (!["questions.list", "questions.answer", "questions.listRecordOptions"].includes(operation2)) throw new Error("Inbox operation unavailable");
10683
10843
  return requestChecked("inbox", { method: "POST", body: JSON.stringify({ contract: INBOX_QUESTION_CONTRACT, operation: operation2, input }), signal }, !0);
10684
10844
  }
10685
10845
  async function requestRoutine(key, suffix, init2 = {}) {
@@ -10868,7 +11028,7 @@ async function send2(operation2, input, resolved, admitted) {
10868
11028
  ...isAppQuestionOperation(operation2) ? { contract: INBOX_QUESTION_CONTRACT } : {}
10869
11029
  }), context;
10870
11030
  try {
10871
- context = resolved ?? await resolveAppContext();
11031
+ context = resolved ?? await resolveAppContext(!1, !isAppQuestionOperation(operation2));
10872
11032
  } catch (error) {
10873
11033
  throw contextFailure(error);
10874
11034
  }
@@ -10894,7 +11054,7 @@ async function send2(operation2, input, resolved, admitted) {
10894
11054
  let host;
10895
11055
  if (!isAppQuestionOperation(operation2)) {
10896
11056
  try {
10897
- host = admitted ?? await resolveHostedInboxContext(context);
11057
+ host = admitted ?? await resolveHostedInboxContext(context, "member");
10898
11058
  } catch (error) {
10899
11059
  throw hostFailure(error, context);
10900
11060
  }
@@ -10908,7 +11068,11 @@ async function send2(operation2, input, resolved, admitted) {
10908
11068
  try {
10909
11069
  let response2 = await fetch(`${context.endpoint}/api/inbox`, {
10910
11070
  method: "POST",
10911
- headers: { authorization: `Bearer ${context.accessToken}`, "content-type": "application/json" },
11071
+ headers: {
11072
+ authorization: `Bearer ${context.accessToken}`,
11073
+ "content-type": "application/json",
11074
+ ...operation2 === "items.readRecords" ? { "x-os-inbox-records": "links-v1" } : {}
11075
+ },
10912
11076
  body: JSON.stringify(envelope),
10913
11077
  redirect: "error",
10914
11078
  cache: "no-store",
@@ -10981,7 +11145,7 @@ var inbox = {
10981
11145
  }
10982
11146
  let host;
10983
11147
  try {
10984
- host = initial.kind !== "local" && await resolveHostedInboxContext(initial, "list");
11148
+ host = initial.kind !== "local" && await resolveHostedInboxContext(initial, "member");
10985
11149
  } catch (error) {
10986
11150
  throw hostFailure(error, initial);
10987
11151
  }
@@ -11034,7 +11198,7 @@ var inbox = {
11034
11198
  } while (!0);
11035
11199
  },
11036
11200
  answer: async (input) => await send2("questions.answer", input),
11037
- searchRecords: async (input) => await send2("questions.searchRecords", input)
11201
+ listRecordOptions: async (input) => await send2("questions.listRecordOptions", input)
11038
11202
  }
11039
11203
  };
11040
11204
 
@@ -11897,11 +12061,11 @@ function routineRunHandle(operations2) {
11897
12061
  });
11898
12062
  }
11899
12063
 
11900
- var name = /^[a-z0-9][a-z0-9-]{0,62}$/, uuid2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, invalid12 = () => {
12064
+ var name = /^[a-z0-9][a-z0-9-]{0,62}$/, uuid2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, invalid13 = () => {
11901
12065
  throw new Error("Run state unavailable");
11902
- }, record3 = (value) => value && typeof value == "object" && !Array.isArray(value) ? value : invalid12();
12066
+ }, record3 = (value) => value && typeof value == "object" && !Array.isArray(value) ? value : invalid13();
11903
12067
  function time3(value) {
11904
- return typeof value != "string" || value.length > 40 || !Number.isFinite(Date.parse(value)) ? invalid12() : value;
12068
+ return typeof value != "string" || value.length > 40 || !Number.isFinite(Date.parse(value)) ? invalid13() : value;
11905
12069
  }
11906
12070
  function times(value) {
11907
12071
  return {
@@ -11910,16 +12074,16 @@ function times(value) {
11910
12074
  };
11911
12075
  }
11912
12076
  function bounded(value) {
11913
- return assertRoutineJson(value), new TextEncoder().encode(JSON.stringify(value)).byteLength > 256 * 1024 ? invalid12() : value;
12077
+ return assertRoutineJson(value), new TextEncoder().encode(JSON.stringify(value)).byteLength > 256 * 1024 ? invalid13() : value;
11914
12078
  }
11915
12079
  function progress(value) {
11916
12080
  if (value === void 0) return {};
11917
12081
  let v = record3(value);
11918
- return Object.keys(v).sort().join(",") !== "completed,total" || !Number.isSafeInteger(v.completed) || !Number.isSafeInteger(v.total) || v.completed < 1 || v.completed > v.total ? invalid12() : { progress: { completed: v.completed, total: v.total } };
12082
+ return Object.keys(v).sort().join(",") !== "completed,total" || !Number.isSafeInteger(v.completed) || !Number.isSafeInteger(v.total) || v.completed < 1 || v.completed > v.total ? invalid13() : { progress: { completed: v.completed, total: v.total } };
11919
12083
  }
11920
12084
  function parseRunStep(value, expected) {
11921
12085
  let v = record3(value);
11922
- if (typeof v.id != "string" || !name.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 invalid12();
12086
+ if (typeof v.id != "string" || !name.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 invalid13();
11923
12087
  let output = captureRetainedStepOutput(v.id, {
11924
12088
  ...Object.hasOwn(v, "summary") ? { summary: v.summary } : {},
11925
12089
  ...Object.hasOwn(v, "data") ? { data: v.data } : {}
@@ -11936,23 +12100,23 @@ function parseRunStep(value, expected) {
11936
12100
  }
11937
12101
  function parseRemoteRun(value, expected = {}) {
11938
12102
  let v = record3(value);
11939
- if (typeof v.id != "string" || !uuid2.test(v.id) || expected.id !== void 0 && v.id !== expected.id || typeof v.routine != "string" || !name.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 invalid12();
12103
+ if (typeof v.id != "string" || !uuid2.test(v.id) || expected.id !== void 0 && v.id !== expected.id || typeof v.routine != "string" || !name.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 invalid13();
11940
12104
  let steps = v.steps.map((value2) => {
11941
12105
  let step = record3(value2);
11942
- return typeof step.detailAvailable != "boolean" || Object.hasOwn(step, "data") ? invalid12() : { ...parseRunStep(step), detailAvailable: step.detailAvailable };
12106
+ return typeof step.detailAvailable != "boolean" || Object.hasOwn(step, "data") ? invalid13() : { ...parseRunStep(step), detailAvailable: step.detailAvailable };
11943
12107
  });
11944
- if (new Set(steps.map((step) => step.id)).size !== steps.length) return invalid12();
12108
+ if (new Set(steps.map((step) => step.id)).size !== steps.length) return invalid13();
11945
12109
  let failure;
11946
12110
  if (v.failure !== void 0) {
11947
12111
  let f = record3(v.failure);
11948
- if (v.status !== "failed" || typeof f.message != "string" || !f.message || f.message.length > 512) return invalid12();
12112
+ if (v.status !== "failed" || typeof f.message != "string" || !f.message || f.message.length > 512) return invalid13();
11949
12113
  if (f.code === "step_output_too_large") {
11950
12114
  let { code, message: message2, ...facts2 } = f, detail = parseRoutineStepOutputDetail(facts2);
11951
- if (!steps.some((step) => step.id === detail.step && step.status === "failed") || message2 !== routineStepOutputMessage(detail)) return invalid12();
12115
+ if (!steps.some((step) => step.id === detail.step && step.status === "failed") || message2 !== routineStepOutputMessage(detail)) return invalid13();
11952
12116
  failure = { code, message: message2, ...detail };
11953
12117
  } else failure = { message: f.message };
11954
12118
  }
11955
- return Object.hasOwn(v, "result") && v.status !== "succeeded" ? invalid12() : {
12119
+ return Object.hasOwn(v, "result") && v.status !== "succeeded" ? invalid13() : {
11956
12120
  id: v.id,
11957
12121
  routine: v.routine,
11958
12122
  placement: "remote",
@@ -12034,7 +12198,7 @@ async function request2(key, suffix, init2, maximum = SUMMARY_BYTES, retained, r
12034
12198
  clearTimeout(timeout);
12035
12199
  }
12036
12200
  }
12037
- function summary(value, key, context, id3) {
12201
+ function summary2(value, key, context, id3) {
12038
12202
  if (context.kind !== "local")
12039
12203
  try {
12040
12204
  return (!only(value, "id,routine,placement,status,createdAt,startedAt,finishedAt,steps,result,failure") || !Array.isArray(value.steps) || value.steps.some((step) => !only(step, "id,title,status,startedAt,finishedAt,progress,summary,detailAvailable")) || value.failure !== void 0 && !validFailure(value.failure, value.steps)) && fail7("execution_unavailable"), parseRemoteRun(value, { routine: key, id: id3 });
@@ -12109,7 +12273,7 @@ function structure(value) {
12109
12273
  }
12110
12274
  function handle(key, id3, context) {
12111
12275
  (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail7("authority_unavailable"), (typeof id3 != "string" || !uuid3.test(id3)) && fail7("invalid_input");
12112
- let read2 = async () => summary(await request2(key, `runs/${id3}`, void 0, SUMMARY_BYTES, context, !0), key, context, id3);
12276
+ let read2 = async () => summary2(await request2(key, `runs/${id3}`, void 0, SUMMARY_BYTES, context, !0), key, context, id3);
12113
12277
  return routineRunHandle({
12114
12278
  async current() {
12115
12279
  return current(context), read2();
@@ -12172,14 +12336,14 @@ function appRoutineBinding(key) {
12172
12336
  }
12173
12337
  let context = await authority();
12174
12338
  context.kind !== "local" && (encoded = JSON.stringify({ ...JSON.parse(encoded), startKey: crypto.randomUUID() }));
12175
- let run = summary(await request2(key, "runs", { method: "POST", body: encoded }, SUMMARY_BYTES, context), key, context);
12339
+ let run = summary2(await request2(key, "runs", { method: "POST", body: encoded }, SUMMARY_BYTES, context), key, context);
12176
12340
  return handle(key, run.id, context);
12177
12341
  },
12178
12342
  runs: Object.freeze({
12179
12343
  async list() {
12180
12344
  let context = await authority(!0), value = await request2(key, "runs", void 0, 20 * SUMMARY_BYTES, context, !0);
12181
12345
  if (!Array.isArray(value) || value.length > 20) return fail7("execution_unavailable");
12182
- let runs = value.map((run) => summary(run, key, context));
12346
+ let runs = value.map((run) => summary2(run, key, context));
12183
12347
  return new Set(runs.map((run) => run.id)).size !== runs.length && fail7("execution_unavailable"), runs;
12184
12348
  },
12185
12349
  async get(id3) {