@oddington/sdk 0.1.84 → 0.1.86

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 invalid18 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
2101
+ let invalid19 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
2102
2102
  if (Settings.throwOnInvalid)
2103
- throw new InvalidDurationError(invalid18);
2103
+ throw new InvalidDurationError(invalid19);
2104
2104
  return new _Duration({
2105
- invalid: invalid18
2105
+ invalid: invalid19
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 invalid18 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
2372
+ let invalid19 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
2373
2373
  if (Settings.throwOnInvalid)
2374
- throw new InvalidIntervalError(invalid18);
2374
+ throw new InvalidIntervalError(invalid19);
2375
2375
  return new _Interval({
2376
- invalid: invalid18
2376
+ invalid: invalid19
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 invalid18 = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
3234
- if (invalid18)
3235
- return DateTime.invalid(invalid18);
3233
+ let invalid19 = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
3234
+ if (invalid19)
3235
+ return DateTime.invalid(invalid19);
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, invalid18 = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (zone.isValid ? null : unsupportedZone(zone));
3263
+ let zone = config.zone || Settings.defaultZone, invalid19 = 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 (!invalid18)
3266
+ if (!invalid19)
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), invalid18 = Number.isNaN(c.year) ? new Invalid("invalid input") : null, c = invalid18 ? null : c, o = invalid18 ? null : ot;
3271
+ c = tsToObj(this.ts, ot), invalid19 = Number.isNaN(c.year) ? new Invalid("invalid input") : null, c = invalid19 ? null : c, o = invalid19 ? null : ot;
3272
3272
  }
3273
- this._zone = zone, this.loc = config.loc || Locale.create(), this.invalid = invalid18, this.weekData = null, this.localWeekData = null, this.c = c, this.o = o, this.isLuxonDateTime = !0;
3273
+ this._zone = zone, this.loc = config.loc || Locale.create(), this.invalid = invalid19, 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), invalid18 = higherOrderInvalid || hasInvalidTimeData(normalized);
3353
- if (invalid18)
3354
- return _DateTime.invalid(invalid18);
3352
+ let higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid19 = higherOrderInvalid || hasInvalidTimeData(normalized);
3353
+ if (invalid19)
3354
+ return _DateTime.invalid(invalid19);
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, invalid18] = parseFromTokens(localeToUse, text5, fmt);
3386
- return invalid18 ? _DateTime.invalid(invalid18) : parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text5, specificOffset);
3385
+ }), [vals, parsedZone, specificOffset, invalid19] = parseFromTokens(localeToUse, text5, fmt);
3386
+ return invalid19 ? _DateTime.invalid(invalid19) : 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 invalid18 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
3398
+ let invalid19 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
3399
3399
  if (Settings.throwOnInvalid)
3400
- throw new InvalidDateTimeError(invalid18);
3400
+ throw new InvalidDateTimeError(invalid19);
3401
3401
  return new _DateTime({
3402
- invalid: invalid18
3402
+ invalid: invalid19
3403
3403
  });
3404
3404
  }
3405
3405
  static isDateTime(o) {
@@ -4043,10 +4043,10 @@ var require_CronDate = /* @__PURE__ */ __commonJS({
4043
4043
  [TimeUnit.Second]: this.subtractSecond.bind(this)
4044
4044
  }
4045
4045
  };
4046
- constructor(timestamp2, tz) {
4046
+ constructor(timestamp3, tz) {
4047
4047
  let dateOpts = { zone: tz };
4048
- if (timestamp2 ? timestamp2 instanceof _CronDate ? (this.#date = timestamp2.#date, this.#dstStart = timestamp2.#dstStart, this.#dstEnd = timestamp2.#dstEnd) : timestamp2 instanceof Date ? this.#date = luxon_1.DateTime.fromJSDate(timestamp2, dateOpts) : typeof timestamp2 == "number" ? this.#date = luxon_1.DateTime.fromMillis(timestamp2, dateOpts) : (this.#date = luxon_1.DateTime.fromISO(timestamp2, dateOpts), this.#date.isValid || (this.#date = luxon_1.DateTime.fromRFC2822(timestamp2, dateOpts)), this.#date.isValid || (this.#date = luxon_1.DateTime.fromSQL(timestamp2, dateOpts)), this.#date.isValid || (this.#date = luxon_1.DateTime.fromFormat(timestamp2, "EEE, d MMM yyyy HH:mm:ss", dateOpts))) : this.#date = luxon_1.DateTime.local(), !this.#date.isValid)
4049
- throw new Error(`CronDate: unhandled timestamp: ${timestamp2}`);
4048
+ if (timestamp3 ? timestamp3 instanceof _CronDate ? (this.#date = timestamp3.#date, this.#dstStart = timestamp3.#dstStart, this.#dstEnd = timestamp3.#dstEnd) : timestamp3 instanceof Date ? this.#date = luxon_1.DateTime.fromJSDate(timestamp3, dateOpts) : typeof timestamp3 == "number" ? this.#date = luxon_1.DateTime.fromMillis(timestamp3, dateOpts) : (this.#date = luxon_1.DateTime.fromISO(timestamp3, dateOpts), this.#date.isValid || (this.#date = luxon_1.DateTime.fromRFC2822(timestamp3, dateOpts)), this.#date.isValid || (this.#date = luxon_1.DateTime.fromSQL(timestamp3, dateOpts)), this.#date.isValid || (this.#date = luxon_1.DateTime.fromFormat(timestamp3, "EEE, d MMM yyyy HH:mm:ss", dateOpts))) : this.#date = luxon_1.DateTime.local(), !this.#date.isValid)
4049
+ throw new Error(`CronDate: unhandled timestamp: ${timestamp3}`);
4050
4050
  tz && tz !== this.#date.zoneName && (this.#date = this.#date.setZone(tz));
4051
4051
  }
4052
4052
  static #isLeapYear(year) {
@@ -4987,25 +4987,25 @@ function parseFileErrorDetail(value) {
4987
4987
  ...v.receivedAtLeast ? { receivedAtLeast: !0 } : {}
4988
4988
  };
4989
4989
  }
4990
- function fileErrorExplanation(detail) {
4991
- return detail.reason === "size_mismatch" ? `The request declared ${detail.expectedBytes} bytes, but contained ${detail.receivedAtLeast ? "at least " : ""}${detail.receivedBytes} bytes.` : detail.reason === "size_limit" ? `The file content exceeds the ${fileSizeLabel(detail.limitBytes)} limit; received ${detail.receivedAtLeast ? "at least " : ""}${fileSizeLabel(detail.receivedBytes)}.` : Object.hasOwn(localStorageReasons, detail.reason) ? localStorageReasons[detail.reason] : fileValidationReasons[detail.reason];
4990
+ function fileErrorExplanation(detail2) {
4991
+ return detail2.reason === "size_mismatch" ? `The request declared ${detail2.expectedBytes} bytes, but contained ${detail2.receivedAtLeast ? "at least " : ""}${detail2.receivedBytes} bytes.` : detail2.reason === "size_limit" ? `The file content exceeds the ${fileSizeLabel(detail2.limitBytes)} limit; received ${detail2.receivedAtLeast ? "at least " : ""}${fileSizeLabel(detail2.receivedBytes)}.` : Object.hasOwn(localStorageReasons, detail2.reason) ? localStorageReasons[detail2.reason] : fileValidationReasons[detail2.reason];
4992
4992
  }
4993
4993
  function fileSizeLabel(bytes) {
4994
4994
  for (let [unit, size] of [["GiB", 1024 ** 3], ["MiB", 1024 ** 2], ["KiB", 1024]])
4995
4995
  if (bytes >= size && bytes % size === 0) return `${bytes / size} ${unit}`;
4996
4996
  return `${bytes} bytes`;
4997
4997
  }
4998
- function fileErrorDetailForCode(code, detail) {
4999
- let parsed = parseFileErrorDetail(detail);
4998
+ function fileErrorDetailForCode(code, detail2) {
4999
+ let parsed = parseFileErrorDetail(detail2);
5000
5000
  if (!parsed) return;
5001
5001
  if (Object.hasOwn(localStorageReasons, parsed.reason) ? code === "unavailable" : ["invalid_input", "request_too_large"].includes(code)) return parsed;
5002
5002
  }
5003
5003
  var FILE_CAPACITY_MESSAGE = "OS reached its file-processing limit. Try again in a moment. If this keeps happening with a large batch, split the files into smaller groups.", FILE_INTEGRITY_MESSAGE = "OS could not verify this File against its saved record. Try again. If the problem continues, add the original file again.";
5004
5004
  function fileErrorMessage(error) {
5005
- let detail = fileErrorDetailForCode(error.code, error.detail);
5006
- if (detail)
5007
- return `${["invalid_enrichment_name", "invalid_enrichment_request", "invalid_replacement"].includes(detail.reason) ? `Couldn\u2019t save the file\u2019s enrichment.
5008
- ` : ""}${fileErrorExplanation(detail)}`;
5005
+ let detail2 = fileErrorDetailForCode(error.code, error.detail);
5006
+ if (detail2)
5007
+ return `${["invalid_enrichment_name", "invalid_enrichment_request", "invalid_replacement"].includes(detail2.reason) ? `Couldn\u2019t save the file\u2019s enrichment.
5008
+ ` : ""}${fileErrorExplanation(detail2)}`;
5009
5009
  switch (error.code) {
5010
5010
  case "invalid_input":
5011
5011
  return "The file request is invalid.";
@@ -5034,8 +5034,8 @@ function fileErrorMessage(error) {
5034
5034
  }
5035
5035
  }
5036
5036
  var FileOperationError = class extends Error {
5037
- constructor(code, status, retryable = !1, detail) {
5038
- let safe = fileErrorDetailForCode(code, detail);
5037
+ constructor(code, status, retryable = !1, detail2) {
5038
+ let safe = fileErrorDetailForCode(code, detail2);
5039
5039
  super(fileErrorMessage({ code, retryable, detail: safe }));
5040
5040
  this.code = code;
5041
5041
  this.status = status;
@@ -5049,40 +5049,40 @@ var FileOperationError = class extends Error {
5049
5049
  };
5050
5050
  var FILE_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, FILE_ORIGINAL_MAX_BYTES = 5 * 1024 ** 3;
5051
5051
  function parseFileDescriptor(value) {
5052
- let invalid18 = () => {
5052
+ let invalid19 = () => {
5053
5053
  throw new FileOperationError("unavailable", 503, !0);
5054
5054
  };
5055
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
5055
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid19();
5056
5056
  let f = value;
5057
- if (Object.keys(f).sort().join(",") !== "enrichments,id,mediaType,name,path,sha256,size" || typeof f.id != "string" || !FILE_ID_PATTERN.test(f.id) || !safeFileName(f.name) || !safeFilePath(f.path) || !Number.isSafeInteger(f.size) || f.size < 0 || f.size > FILE_ORIGINAL_MAX_BYTES || typeof f.sha256 != "string" || !/^[0-9a-f]{64}$/.test(f.sha256) || !f.enrichments || typeof f.enrichments != "object" || Array.isArray(f.enrichments) || !isCanonicalOriginalMediaType(f.mediaType)) return invalid18();
5057
+ if (Object.keys(f).sort().join(",") !== "enrichments,id,mediaType,name,path,sha256,size" || typeof f.id != "string" || !FILE_ID_PATTERN.test(f.id) || !safeFileName(f.name) || !safeFilePath(f.path) || !Number.isSafeInteger(f.size) || f.size < 0 || f.size > FILE_ORIGINAL_MAX_BYTES || typeof f.sha256 != "string" || !/^[0-9a-f]{64}$/.test(f.sha256) || !f.enrichments || typeof f.enrichments != "object" || Array.isArray(f.enrichments) || !isCanonicalOriginalMediaType(f.mediaType)) return invalid19();
5058
5058
  for (let [name4, descriptor] of Object.entries(f.enrichments)) {
5059
- if (!safeEnrichmentName(name4)) return invalid18();
5059
+ if (!safeEnrichmentName(name4)) return invalid19();
5060
5060
  parseEnrichmentDescriptor(descriptor);
5061
5061
  }
5062
- return new TextEncoder().encode(JSON.stringify(f)).byteLength > 16 * 1024 ? invalid18() : f;
5062
+ return new TextEncoder().encode(JSON.stringify(f)).byteLength > 16 * 1024 ? invalid19() : f;
5063
5063
  }
5064
5064
  function parseEnrichmentDescriptor(value) {
5065
- let invalid18 = () => {
5065
+ let invalid19 = () => {
5066
5066
  throw new FileOperationError("unavailable", 503, !0);
5067
5067
  };
5068
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
5068
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid19();
5069
5069
  let d = value;
5070
- return Object.keys(d).sort().join(",") !== "mediaType,sha256,size" || !["application/octet-stream", "text/plain", "text/markdown", "application/json"].includes(d.mediaType) || !Number.isSafeInteger(d.size) || d.size < 0 || d.size > 16 * 1024 * 1024 || typeof d.sha256 != "string" || !/^[0-9a-f]{64}$/.test(d.sha256) ? invalid18() : d;
5070
+ return Object.keys(d).sort().join(",") !== "mediaType,sha256,size" || !["application/octet-stream", "text/plain", "text/markdown", "application/json"].includes(d.mediaType) || !Number.isSafeInteger(d.size) || d.size < 0 || d.size > 16 * 1024 * 1024 || typeof d.sha256 != "string" || !/^[0-9a-f]{64}$/.test(d.sha256) ? invalid19() : d;
5071
5071
  }
5072
5072
  function safeEnrichmentName(value) {
5073
5073
  return safeFileName(value) && !/^original(?:\.|$)/i.test(value);
5074
5074
  }
5075
5075
  function parseFileEnrichMetadata(value, maxBytes) {
5076
- let invalid18 = (reason = "invalid_metadata") => {
5076
+ let invalid19 = (reason = "invalid_metadata") => {
5077
5077
  throw new FileOperationError("invalid_input", 400, !1, { reason });
5078
5078
  };
5079
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
5079
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid19();
5080
5080
  let d = value;
5081
- if (Object.keys(d).some((key) => !["name", "size", "mediaType", "replace"].includes(key))) return invalid18();
5082
- if (!safeEnrichmentName(d.name)) return invalid18("invalid_enrichment_name");
5083
- if (!Number.isSafeInteger(d.size) || d.size < 0) return invalid18("invalid_size");
5084
- if (d.mediaType !== void 0 && (typeof d.mediaType != "string" || d.mediaType.length > 255 || /[\u0000-\u001f\u007f]/.test(d.mediaType))) return invalid18("invalid_media_type");
5085
- if (d.replace !== void 0 && (typeof d.replace != "string" || !/^[0-9a-f]{64}$/.test(d.replace))) return invalid18("invalid_replacement");
5081
+ if (Object.keys(d).some((key) => !["name", "size", "mediaType", "replace"].includes(key))) return invalid19();
5082
+ if (!safeEnrichmentName(d.name)) return invalid19("invalid_enrichment_name");
5083
+ if (!Number.isSafeInteger(d.size) || d.size < 0) return invalid19("invalid_size");
5084
+ if (d.mediaType !== void 0 && (typeof d.mediaType != "string" || d.mediaType.length > 255 || /[\u0000-\u001f\u007f]/.test(d.mediaType))) return invalid19("invalid_media_type");
5085
+ if (d.replace !== void 0 && (typeof d.replace != "string" || !/^[0-9a-f]{64}$/.test(d.replace))) return invalid19("invalid_replacement");
5086
5086
  if (d.size > maxBytes) throw new FileOperationError(
5087
5087
  "request_too_large",
5088
5088
  413,
@@ -5115,42 +5115,42 @@ function isCanonicalOriginalMediaType(value) {
5115
5115
  }
5116
5116
  }
5117
5117
  function parseFileUpdate(value) {
5118
- let invalid18 = (reason = "invalid_metadata") => {
5118
+ let invalid19 = (reason = "invalid_metadata") => {
5119
5119
  throw new FileOperationError("invalid_input", 400, !1, { reason });
5120
5120
  };
5121
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
5121
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid19();
5122
5122
  let input = value, update = {};
5123
- if (!Object.keys(input).length || Object.keys(input).some((key) => !["name", "path", "mediaType"].includes(key))) return invalid18();
5123
+ if (!Object.keys(input).length || Object.keys(input).some((key) => !["name", "path", "mediaType"].includes(key))) return invalid19();
5124
5124
  if (Object.hasOwn(input, "name")) {
5125
- if (!safeFileName(input.name)) return invalid18("invalid_name");
5125
+ if (!safeFileName(input.name)) return invalid19("invalid_name");
5126
5126
  update.name = input.name;
5127
5127
  }
5128
5128
  if (Object.hasOwn(input, "path")) {
5129
- if (!safeManagedFilePath(input.path)) return invalid18("invalid_path");
5129
+ if (!safeManagedFilePath(input.path)) return invalid19("invalid_path");
5130
5130
  update.path = input.path;
5131
5131
  }
5132
5132
  return Object.hasOwn(input, "mediaType") && (update.mediaType = declaredOriginalMediaType(input.mediaType)), update;
5133
5133
  }
5134
5134
  function parseFileCreateMetadata(value, maxBytes) {
5135
- let invalid18 = (reason = "invalid_metadata") => {
5135
+ let invalid19 = (reason = "invalid_metadata") => {
5136
5136
  throw new FileOperationError("invalid_input", 400, !1, { reason });
5137
5137
  };
5138
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
5138
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid19();
5139
5139
  let input = value;
5140
- if (Object.keys(input).some((key) => !["name", "path", "storage", "mediaType", "size", "requestKey"].includes(key))) return invalid18();
5140
+ if (Object.keys(input).some((key) => !["name", "path", "storage", "mediaType", "size", "requestKey"].includes(key))) return invalid19();
5141
5141
  let path = input.path === void 0 ? "Files" : input.path;
5142
- if (!safeFileName(input.name)) return invalid18("invalid_name");
5143
- if (!safeManagedFilePath(path)) return invalid18("invalid_path");
5144
- if (input.storage !== void 0 && input.storage !== "remote" && input.storage !== "local") return invalid18("invalid_storage");
5142
+ if (!safeFileName(input.name)) return invalid19("invalid_name");
5143
+ if (!safeManagedFilePath(path)) return invalid19("invalid_path");
5144
+ if (input.storage !== void 0 && input.storage !== "remote" && input.storage !== "local") return invalid19("invalid_storage");
5145
5145
  let mediaType = input.mediaType === void 0 ? "application/octet-stream" : declaredOriginalMediaType(input.mediaType);
5146
- if (!Number.isSafeInteger(input.size) || input.size < 0) return invalid18("invalid_size");
5146
+ if (!Number.isSafeInteger(input.size) || input.size < 0) return invalid19("invalid_size");
5147
5147
  if (input.size > maxBytes) throw new FileOperationError(
5148
5148
  "request_too_large",
5149
5149
  413,
5150
5150
  !1,
5151
5151
  { reason: "size_limit", limitBytes: maxBytes, receivedBytes: input.size }
5152
5152
  );
5153
- return typeof input.requestKey != "string" || input.requestKey.length < 1 || input.requestKey.length > 256 || input.requestKey !== input.requestKey.trim() || /[\u0000-\u001f\u007f]/.test(input.requestKey) ? invalid18("invalid_request_key") : {
5153
+ return typeof input.requestKey != "string" || input.requestKey.length < 1 || input.requestKey.length > 256 || input.requestKey !== input.requestKey.trim() || /[\u0000-\u001f\u007f]/.test(input.requestKey) ? invalid19("invalid_request_key") : {
5154
5154
  name: input.name,
5155
5155
  path,
5156
5156
  ...input.storage ? { storage: input.storage } : {},
@@ -5424,6 +5424,16 @@ function selectionOptions(value, published) {
5424
5424
  ...option.description === void 0 ? {} : { description: text(option.description, "Record description") },
5425
5425
  ...numbered
5426
5426
  };
5427
+ case "assign": {
5428
+ keys(option, [...common, "label", "assignee"], "assignment option");
5429
+ let assignee = option.assignee === void 0 ? void 0 : personReference(option.assignee, "assignment target"), isUuid = assignee !== void 0 && /^[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(assignee);
5430
+ return assignee !== void 0 && !isUuid && (published || assignee.length > 320 || !memberEmail.test(assignee)) && fail("Assignment target must be a workspace member UUID or email"), {
5431
+ type: "assign",
5432
+ label: text(option.label, "assignment label"),
5433
+ ...assignee === void 0 ? {} : { assignee: isUuid ? assignee.toLowerCase() : assignee },
5434
+ ...numbered
5435
+ };
5436
+ }
5427
5437
  case "record-picker":
5428
5438
  return keys(option, [...common, "label", "source"], "Record picker option"), {
5429
5439
  type: "record-picker",
@@ -5455,6 +5465,8 @@ function selectionResponse(saved, value) {
5455
5465
  option || fail("Option was not published");
5456
5466
  let answer;
5457
5467
  switch (option.type) {
5468
+ case "assign":
5469
+ return fail("Assignment options cannot be answered");
5458
5470
  case "choice":
5459
5471
  answer = id(response2.value, "choice value"), answer !== option.value && fail("Choice does not match published option");
5460
5472
  break;
@@ -6291,18 +6303,18 @@ function parseRoutineAIErrorDetail(code, value) {
6291
6303
  return { reason: "unsupported_media_type", mediaType: v.mediaType };
6292
6304
  }
6293
6305
  function routineAIErrorMessage(code, value) {
6294
- let detail = parseRoutineAIErrorDetail(code, value);
6295
- if (code === "invalid_output" && detail) return routineAIOutputMessage(detail);
6296
- if (detail) switch (detail.reason) {
6306
+ let detail2 = parseRoutineAIErrorDetail(code, value);
6307
+ if (code === "invalid_output" && detail2) return routineAIOutputMessage(detail2);
6308
+ if (detail2) switch (detail2.reason) {
6297
6309
  case "model_output_limit":
6298
- return `AI stopped because its response reached the model\u2019s ${detail.limit.toLocaleString("en-US")}-token output limit.`;
6310
+ return `AI stopped because its response reached the model\u2019s ${detail2.limit.toLocaleString("en-US")}-token output limit.`;
6299
6311
  case "response_transport_limit":
6300
- return `OS stopped accepting the AI response because it exceeded the ${formatBytes(detail.limitBytes)} response transport limit.`;
6312
+ return `OS stopped accepting the AI response because it exceeded the ${formatBytes(detail2.limitBytes)} response transport limit.`;
6301
6313
  case "accepted_value_limit":
6302
- return `OS couldn\u2019t accept the AI response because its final value exceeded the ${formatBytes(detail.limitBytes)} limit.`;
6314
+ return `OS couldn\u2019t accept the AI response because its final value exceeded the ${formatBytes(detail2.limitBytes)} limit.`;
6303
6315
  case "turn_limit":
6304
6316
  return `AI stopped before finishing the request.
6305
- It reached the ${detail.limit}-turn limit.`;
6317
+ It reached the ${detail2.limit}-turn limit.`;
6306
6318
  case "runner_exit":
6307
6319
  return `AI couldn\u2019t complete the request.
6308
6320
  The local AI runner stopped before returning a usable answer.`;
@@ -6323,7 +6335,7 @@ Set tools to true or false.`;
6323
6335
  Using tools requires a File input.`;
6324
6336
  case "unsupported_media_type":
6325
6337
  return `AI couldn\u2019t read this file.
6326
- Its media type is ${detail.mediaType}, which this input path doesn\u2019t support.
6338
+ Its media type is ${detail2.mediaType}, which this input path doesn\u2019t support.
6327
6339
 
6328
6340
  Check the file\u2019s stored media type before retrying. The model was not called.`;
6329
6341
  }
@@ -6358,22 +6370,22 @@ var ROUTINE_AI_VALUE_BYTES = 256 * 1024;
6358
6370
  var ROUTINE_AI_RESULT_BYTES = 6 * ROUTINE_AI_VALUE_BYTES + 1024, ROUTINE_AI_EVIDENCE_BYTES = 4 * 1024;
6359
6371
  var AIError = class extends Error {
6360
6372
  constructor(code, options = {}) {
6361
- let detail = parseRoutineAIErrorDetail(code, options.detail);
6362
- super(routineAIErrorMessage(code, detail));
6373
+ let detail2 = parseRoutineAIErrorDetail(code, options.detail);
6374
+ super(routineAIErrorMessage(code, detail2));
6363
6375
  this.code = code;
6364
- this.name = "AIError", detail && (this.detail = Object.freeze(detail)), code === "invalid_output" && typeof options.text == "string" && new TextEncoder().encode(options.text).byteLength <= ROUTINE_AI_VALUE_BYTES && Object.defineProperty(this, "text", { value: options.text });
6376
+ this.name = "AIError", detail2 && (this.detail = Object.freeze(detail2)), code === "invalid_output" && typeof options.text == "string" && new TextEncoder().encode(options.text).byteLength <= ROUTINE_AI_VALUE_BYTES && Object.defineProperty(this, "text", { value: options.text });
6365
6377
  }
6366
6378
  code;
6367
6379
  detail;
6368
6380
  };
6369
- function capture(value, invalid18, oversized, limit = ROUTINE_AI_VALUE_BYTES) {
6381
+ function capture(value, invalid19, oversized, limit = ROUTINE_AI_VALUE_BYTES) {
6370
6382
  try {
6371
6383
  assertRoutineJson(value);
6372
6384
  let encoded = JSON.stringify(value);
6373
6385
  if (new TextEncoder().encode(encoded).byteLength > limit) throw new AIError(oversized);
6374
6386
  return freezeRoutineMetadata(JSON.parse(encoded));
6375
6387
  } catch (error) {
6376
- throw error instanceof AIError ? error : new AIError(invalid18);
6388
+ throw error instanceof AIError ? error : new AIError(invalid19);
6377
6389
  }
6378
6390
  }
6379
6391
  function parseRoutineAIRequest(value) {
@@ -6412,13 +6424,13 @@ function parseRoutineAIResult(request3, value) {
6412
6424
  return validateObject(request3.schema, v.object), freezeRoutineMetadata({ object: v.object });
6413
6425
  }
6414
6426
  function validateObject(schema2, object11, text5) {
6415
- let detail = { reason: "invalid_response" };
6427
+ let detail2 = { reason: "invalid_response" };
6416
6428
  try {
6417
6429
  validateRoutineSchemaValue(schema2, object11, (issue) => {
6418
- detail = issue;
6430
+ detail2 = issue;
6419
6431
  });
6420
6432
  } catch {
6421
- throw new AIError("invalid_output", { ...text5 === void 0 ? {} : { text: text5 }, detail });
6433
+ throw new AIError("invalid_output", { ...text5 === void 0 ? {} : { text: text5 }, detail: detail2 });
6422
6434
  }
6423
6435
  }
6424
6436
  function acceptText(request3, text5) {
@@ -6438,22 +6450,22 @@ function acceptText(request3, text5) {
6438
6450
 
6439
6451
  var ROUTINE_STEP_SUMMARY_BYTES = 256 * 1024, ROUTINE_STEP_OUTPUT_BYTES = 1024 * 1024;
6440
6452
  function parseRoutineStepOutputDetail(value) {
6441
- let invalid18 = () => {
6453
+ let invalid19 = () => {
6442
6454
  throw new AppRoutineContractError("invalid_value");
6443
6455
  };
6444
6456
  assertRoutineFields(value, ["step", "sizeBytes", "limitBytes", "summaryBytes", "dataBytes"]);
6445
6457
  let { step, sizeBytes, limitBytes, summaryBytes, dataBytes } = value;
6446
- return !isAppRoutineName(step) || ![sizeBytes, limitBytes, summaryBytes, dataBytes].every((bytes) => Number.isSafeInteger(bytes) && bytes > 0) || sizeBytes !== summaryBytes + dataBytes || limitBytes !== (summaryBytes > ROUTINE_STEP_SUMMARY_BYTES ? ROUTINE_STEP_SUMMARY_BYTES : ROUTINE_STEP_OUTPUT_BYTES) || (limitBytes === ROUTINE_STEP_SUMMARY_BYTES ? summaryBytes : sizeBytes) <= limitBytes ? invalid18() : freezeRoutineMetadata({ step, sizeBytes, limitBytes, summaryBytes, dataBytes });
6458
+ 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 ? invalid19() : freezeRoutineMetadata({ step, sizeBytes, limitBytes, summaryBytes, dataBytes });
6447
6459
  }
6448
6460
  function routineStepOutputMessage(value) {
6449
- let detail = parseRoutineStepOutputDetail(value), size = `${(detail.sizeBytes / (1024 * 1024)).toFixed(1)} MB`, bound = detail.limitBytes === ROUTINE_STEP_SUMMARY_BYTES ? `, including ${(detail.summaryBytes / 1024).toFixed(1)} KB of summary. Each step's summary can return up to 256 KB.` : ". Each step can return up to 1 MB across its summary and data.";
6450
- return `Step ${detail.step} returned ${size} of output${bound} Return fewer fields or process a smaller batch, then try again.`;
6461
+ let detail2 = parseRoutineStepOutputDetail(value), size = `${(detail2.sizeBytes / (1024 * 1024)).toFixed(1)} MB`, bound = detail2.limitBytes === ROUTINE_STEP_SUMMARY_BYTES ? `, including ${(detail2.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.";
6462
+ return `Step ${detail2.step} returned ${size} of output${bound} Return fewer fields or process a smaller batch, then try again.`;
6451
6463
  }
6452
6464
  var RoutineStepOutputError = class extends Error {
6453
6465
  code = "step_output_too_large";
6454
6466
  detail;
6455
- constructor(detail) {
6456
- let captured = parseRoutineStepOutputDetail(detail);
6467
+ constructor(detail2) {
6468
+ let captured = parseRoutineStepOutputDetail(detail2);
6457
6469
  super(routineStepOutputMessage(captured)), this.detail = captured, Object.freeze(this);
6458
6470
  }
6459
6471
  };
@@ -6655,9 +6667,9 @@ function createCapabilityRuntime(contract, runtime2, current2, owner) {
6655
6667
  generateText: (value) => generate("generateText", value),
6656
6668
  generateObject: (value) => generate("generateObject", value)
6657
6669
  },
6658
- connections: { ...runtime2.connections, get: async (identity3) => {
6659
- if (!current2() || !contract.access.connections?.includes(identity3)) throw new Error("Connection unavailable");
6660
- let value = await runtime2.connections.get(identity3);
6670
+ connections: { ...runtime2.connections, get: async (identity4) => {
6671
+ if (!current2() || !contract.access.connections?.includes(identity4)) throw new Error("Connection unavailable");
6672
+ let value = await runtime2.connections.get(identity4);
6661
6673
  if (!current2()) throw new Error(`${owner} authority ended`);
6662
6674
  return value;
6663
6675
  } },
@@ -6785,37 +6797,103 @@ function parseQueuePage(value) {
6785
6797
  return { items: v.items.map(parseQueueItem), ...v.next === void 0 ? {} : { next: v.next } };
6786
6798
  }
6787
6799
 
6800
+ var XERO_WEBHOOK_KINDS = ["invoice.created", "invoice.updated", "payment.created", "payment.updated"], invalid4 = () => {
6801
+ throw new Error("Invalid routine webhook");
6802
+ }, connection = (value) => typeof value == "string" && value.startsWith("xero/") && isAppRoutineName(value.slice(5)), identity = (value) => typeof value == "string" && value.length > 0 && value.length <= 256 && !/[\s\x00-\x1f\x7f]/.test(value);
6803
+ function timestamp(value) {
6804
+ return typeof value != "string" || value.length > 40 || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?(?:Z|[+-]\d\d:\d\d)$/.test(value) || !Number.isFinite(Date.parse(value)) ? invalid4() : value;
6805
+ }
6806
+ function parseWebhookQueryTrigger(value, access) {
6807
+ return assertRoutineFields(value, ["connection", "events"]), !connection(value.connection) || !access.connections?.includes(value.connection) || !Array.isArray(value.events) || value.events.length < 1 || value.events.length > XERO_WEBHOOK_KINDS.length || new Set(value.events).size !== value.events.length || value.events.some((kind) => !XERO_WEBHOOK_KINDS.includes(kind)) ? invalid4() : freezeRoutineMetadata({ webhook: { connection: value.connection, events: [...value.events] } });
6808
+ }
6809
+ function detail(value) {
6810
+ let nodes = 0, visit = (v, depth) => {
6811
+ if (++nodes > 256 || depth > 8) return invalid4();
6812
+ if (!(v === null || typeof v == "boolean" || typeof v == "number" && Number.isFinite(v))) {
6813
+ if (typeof v == "string")
6814
+ return v.length > 8192 ? invalid4() : void 0;
6815
+ if (Array.isArray(v)) {
6816
+ if (v.length > 256 || Reflect.ownKeys(v).length !== v.length + 1) return invalid4();
6817
+ for (let i = 0; i < v.length; i++) {
6818
+ let descriptor = Object.getOwnPropertyDescriptor(v, i);
6819
+ if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value")) return invalid4();
6820
+ visit(descriptor.value, depth + 1);
6821
+ }
6822
+ } else {
6823
+ assertRoutineFields(v);
6824
+ for (let [key, child] of Object.entries(v)) {
6825
+ if (key.length > 256) return invalid4();
6826
+ visit(child, depth + 1);
6827
+ }
6828
+ }
6829
+ }
6830
+ };
6831
+ visit(value, 0);
6832
+ let encoded = JSON.stringify(value);
6833
+ return new TextEncoder().encode(encoded).length > 8192 ? invalid4() : JSON.parse(encoded);
6834
+ }
6835
+ function parseWebhookEvent(value) {
6836
+ return assertRoutineFields(value, ["id", "provider", "connection", "kind", "resource", "occurredAt", "receivedAt", "detail"]), assertRoutineFields(value.resource, ["type", "id"]), !identity(value.id) || value.provider !== "xero" || !connection(value.connection) || !XERO_WEBHOOK_KINDS.includes(value.kind) || !identity(value.resource.id) || value.resource.type !== value.kind.split(".")[0] ? invalid4() : freezeRoutineMetadata({
6837
+ id: value.id,
6838
+ provider: "xero",
6839
+ connection: value.connection,
6840
+ kind: value.kind,
6841
+ resource: { type: value.resource.type, id: value.resource.id },
6842
+ receivedAt: timestamp(value.receivedAt),
6843
+ ...value.occurredAt === void 0 ? {} : { occurredAt: timestamp(value.occurredAt) },
6844
+ ...value.detail === void 0 ? {} : { detail: detail(value.detail) }
6845
+ });
6846
+ }
6847
+
6848
+ function parseQueryTriggers(value, access) {
6849
+ if (assertRoutineJson(value), !Array.isArray(value)) throw new Error("Invalid query triggers");
6850
+ return value.map((trigger) => {
6851
+ if (assertRoutineFields(trigger, ["schedule", "webhook"]), Object.keys(trigger).length !== 1) throw new Error("Invalid query trigger");
6852
+ return Object.hasOwn(trigger, "schedule") ? { schedule: parseRoutineSchedule(trigger.schedule) } : parseWebhookQueryTrigger(trigger.webhook, access);
6853
+ });
6854
+ }
6855
+ function parseQueryTriggerContext(value, query) {
6856
+ if (assertRoutineFields(value, ["type", "scheduledAt", "event"]), value.type === "manual" && Object.keys(value).length === 1) return { type: "manual" };
6857
+ if (value.type === "schedule" && Object.keys(value).length === 2 && typeof value.scheduledAt == "string" && Number.isFinite(Date.parse(value.scheduledAt))) return { type: "schedule", scheduledAt: value.scheduledAt };
6858
+ if (value.type === "webhook" && Object.keys(value).length === 2) {
6859
+ let event = parseWebhookEvent(value.event);
6860
+ if (query && (!query.access.connections?.includes(event.connection) || !query.triggers.some((trigger) => "webhook" in trigger && trigger.webhook.connection === event.connection && trigger.webhook.events.includes(event.kind)))) throw new Error("Invalid query trigger authority");
6861
+ return { type: "webhook", event };
6862
+ }
6863
+ throw new Error("Invalid query trigger");
6864
+ }
6865
+
6788
6866
  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}$/;
6789
- function invalid4() {
6867
+ function invalid5() {
6790
6868
  throw new Error("Invalid query result");
6791
6869
  }
6792
6870
  function object4(value) {
6793
- return !value || typeof value != "object" || Array.isArray(value) ? invalid4() : value;
6871
+ return !value || typeof value != "object" || Array.isArray(value) ? invalid5() : value;
6794
6872
  }
6795
6873
  function id3(value) {
6796
- return typeof value == "string" && uuid2.test(value) ? value : invalid4();
6874
+ return typeof value == "string" && uuid2.test(value) ? value : invalid5();
6797
6875
  }
6798
- function identity(value) {
6799
- return typeof value == "string" && name.test(value) ? value : invalid4();
6876
+ function identity2(value) {
6877
+ return typeof value == "string" && name.test(value) ? value : invalid5();
6800
6878
  }
6801
6879
  function date2(value) {
6802
- return typeof value == "string" && Number.isFinite(Date.parse(value)) ? value : invalid4();
6880
+ return typeof value == "string" && Number.isFinite(Date.parse(value)) ? value : invalid5();
6803
6881
  }
6804
6882
  function count(value) {
6805
- return typeof value == "number" && Number.isSafeInteger(value) && value >= 0 ? value : invalid4();
6883
+ return typeof value == "number" && Number.isSafeInteger(value) && value >= 0 ? value : invalid5();
6806
6884
  }
6807
6885
  function parseQueryExecution(value) {
6808
6886
  let v = object4(value), trigger = object4(v.trigger);
6809
- if (!["queued", "running", "succeeded", "failed"].includes(v.status) || !["manual", "schedule"].includes(trigger.type)) return invalid4();
6887
+ if (!["queued", "running", "succeeded", "failed"].includes(v.status) || !["manual", "schedule", "webhook"].includes(trigger.type)) return invalid5();
6810
6888
  let found = count(v.found), added = count(v.added), skipped = count(v.skipped);
6811
- if (added > found - skipped) return invalid4();
6889
+ if (added > found - skipped) return invalid5();
6812
6890
  let failure = v.failure === void 0 ? void 0 : object4(v.failure);
6813
- return failure && typeof failure.message != "string" || v.status === "failed" && !failure ? invalid4() : {
6891
+ return failure && typeof failure.message != "string" || v.status === "failed" && !failure ? invalid5() : {
6814
6892
  id: id3(v.id),
6815
- queryId: identity(v.queryId),
6893
+ queryId: identity2(v.queryId),
6816
6894
  deploymentId: id3(v.deploymentId),
6817
6895
  status: v.status,
6818
- trigger: trigger.type === "manual" ? { type: "manual" } : { type: "schedule", scheduledAt: date2(trigger.scheduledAt) },
6896
+ trigger: parseQueryTriggerContext(trigger),
6819
6897
  acceptedAt: date2(v.acceptedAt),
6820
6898
  found,
6821
6899
  added,
@@ -6828,19 +6906,19 @@ function parseQueryExecution(value) {
6828
6906
  }
6829
6907
  function parseQueryDescription(value) {
6830
6908
  let v = object4(value);
6831
- if (!Array.isArray(v.triggers)) return invalid4();
6832
- let result2 = {
6833
- id: identity(v.id),
6834
- routineId: identity(v.routineId),
6835
- access: parseRoutineAccess(v.access),
6836
- triggers: v.triggers.map((trigger) => ({ schedule: parseRoutineSchedule(object4(trigger).schedule) })),
6909
+ if (!Array.isArray(v.triggers)) return invalid5();
6910
+ let access = parseRoutineAccess(v.access), result2 = {
6911
+ id: identity2(v.id),
6912
+ routineId: identity2(v.routineId),
6913
+ access,
6914
+ triggers: parseQueryTriggers(v.triggers, access),
6837
6915
  ...v.latestExecution === void 0 ? {} : { latestExecution: parseQueryExecution(v.latestExecution) }
6838
6916
  };
6839
- return result2.latestExecution && result2.latestExecution.queryId !== result2.id ? invalid4() : result2;
6917
+ return result2.latestExecution && result2.latestExecution.queryId !== result2.id ? invalid5() : result2;
6840
6918
  }
6841
6919
  function parseQueryExecutionPage(value) {
6842
6920
  let v = object4(value);
6843
- return !Array.isArray(v.items) || v.items.length > 500 || v.next !== void 0 && (typeof v.next != "string" || !v.next) ? invalid4() : { items: v.items.map(parseQueryExecution), ...v.next === void 0 ? {} : { next: v.next } };
6921
+ return !Array.isArray(v.items) || v.items.length > 500 || v.next !== void 0 && (typeof v.next != "string" || !v.next) ? invalid5() : { items: v.items.map(parseQueryExecution), ...v.next === void 0 ? {} : { next: v.next } };
6844
6922
  }
6845
6923
 
6846
6924
  var fieldProblems = ["unknown", "missing", "invalid", "source_schema"], reasons = {
@@ -6946,39 +7024,39 @@ function parsePublicationConflict(value) {
6946
7024
  function dataValidationMessageFacts(error) {
6947
7025
  if (["invalid_change", "conflict"].includes(error.code) && error.detail && typeof error.detail == "object" && "code" in error.detail && error.detail.code === "publication_conflict")
6948
7026
  try {
6949
- let detail = parsePublicationConflict(error.detail), descriptions = {
7027
+ let detail2 = parsePublicationConflict(error.detail), descriptions = {
6950
7028
  record_version_changed: "changed after it was reviewed",
6951
7029
  record_missing: "is missing",
6952
7030
  create_identity_conflict: "already exists",
6953
7031
  filing_conflict: "has a conflicting filing path",
6954
7032
  schema_changed: "has an unavailable or incompatible schema"
6955
7033
  };
6956
- return { detail, message: `Record "${detail.record}" ${descriptions[detail.conflict]}. No changes were saved.` };
7034
+ return { detail: detail2, message: `Record "${detail2.record}" ${descriptions[detail2.conflict]}. No changes were saved.` };
6957
7035
  } catch {
6958
7036
  return {};
6959
7037
  }
6960
7038
  if (error.code === "invalid_change") {
6961
- let detail = parseDataValidationDetail(error.detail);
6962
- if (detail) {
6963
- let problem = fieldProblems.find((problem2) => reasons[problem2] === detail.reason);
6964
- return { detail, message: recordFieldMessage(
6965
- detail.record,
6966
- detail.field,
7039
+ let detail2 = parseDataValidationDetail(error.detail);
7040
+ if (detail2) {
7041
+ let problem = fieldProblems.find((problem2) => reasons[problem2] === detail2.reason);
7042
+ return { detail: detail2, message: recordFieldMessage(
7043
+ detail2.record,
7044
+ detail2.field,
6967
7045
  problem,
6968
- detail.schemaFile,
6969
- detail.expected
7046
+ detail2.schemaFile,
7047
+ detail2.expected
6970
7048
  ) };
6971
7049
  }
6972
7050
  }
6973
7051
  let message2 = error.code === "invalid_change" ? safeRecordFieldMessage(error.message) : void 0;
6974
7052
  return message2 ? { message: message2 } : {};
6975
7053
  }
6976
- function explainDataValidation(error, message2, detail) {
6977
- return Object.assign(error, dataValidationMessageFacts({ code: error.code, message: typeof message2 == "string" ? message2 : "", detail })), error;
7054
+ function explainDataValidation(error, message2, detail2) {
7055
+ return Object.assign(error, dataValidationMessageFacts({ code: error.code, message: typeof message2 == "string" ? message2 : "", detail: detail2 })), error;
6978
7056
  }
6979
7057
 
6980
- function dataPublicationFailureMessage(detail) {
6981
- return detail.preflight === "dirty_repository" ? `Data repository ${detail.repository} has existing changes. No Record files were changed. Use os data push ${detail.repository} or stash those Data changes with Git, then run the routine again.` : (detail.state === "commit" ? `Data commit ${detail.commit} remains in your checkout; its push is unconfirmed.` : detail.state === "files" ? "Your Record files were applied, but Git could not create their commit." : "Data publication needs Git preparation. No Record files were changed.") + ` Review git status and your branch and destination, then use os data push ${detail.repository}. Do not rerun the routine to recover this publication.`;
7058
+ function dataPublicationFailureMessage(detail2) {
7059
+ return detail2.preflight === "dirty_repository" ? `Data repository ${detail2.repository} has existing changes. No Record files were changed. Use os data push ${detail2.repository} or stash those Data changes with Git, then run the routine again.` : (detail2.state === "commit" ? `Data commit ${detail2.commit} remains in your checkout; its push is unconfirmed.` : detail2.state === "files" ? "Your Record files were applied, but Git could not create their commit." : "Data publication needs Git preparation. No Record files were changed.") + ` Review git status and your branch and destination, then use os data push ${detail2.repository}. Do not rerun the routine to recover this publication.`;
6982
7060
  }
6983
7061
  var localDataPath = (value, repository) => typeof value == "string" && value.length <= 1024 && value.startsWith(`${repository}/`) && !value.includes("\\") && !/[\x00-\x1f\x7f]/.test(value) && value.split("/").every((part) => !!part && part !== "." && part !== ".."), localDataFile = (value, repository) => {
6984
7062
  if (!value || typeof value != "object" || Array.isArray(value)) return !1;
@@ -6986,20 +7064,20 @@ var localDataPath = (value, repository) => typeof value == "string" && value.len
6986
7064
  return Object.keys(row).sort().join(",") === "action,path" && ["created", "updated", "deleted"].includes(String(row.action)) && localDataPath(row.path, repository);
6987
7065
  };
6988
7066
  function parseDataFailureDetail(value) {
6989
- let invalid18 = () => {
7067
+ let invalid19 = () => {
6990
7068
  throw new Error("Invalid local Data failure detail");
6991
7069
  };
6992
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
7070
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid19();
6993
7071
  let row = value;
6994
- if (Object.keys(row).sort().join(",") !== "cause,code,files,nextAction,operation,repository" || !["local_data_read_failed", "local_data_write_failed", "local_data_write_partial"].includes(String(row.code)) || !["read", "write"].includes(String(row.operation)) || typeof row.repository != "string" || !/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(row.repository) || row.repository.includes("//") || row.repository.includes("..") || !["fix_failed_file_then_rerun", "review_resolve_then_rerun"].includes(String(row.nextAction))) return invalid18();
7072
+ 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 invalid19();
6995
7073
  let repository = row.repository;
6996
- if (!row.cause || typeof row.cause != "object" || Array.isArray(row.cause)) return invalid18();
7074
+ if (!row.cause || typeof row.cause != "object" || Array.isArray(row.cause)) return invalid19();
6997
7075
  let cause = row.cause;
6998
- if (!["code,message", "code,message,path"].includes(Object.keys(cause).sort().join(",")) || !["schema_validation_failed", "invalid_record", "unsafe_record", "stale_record", "path_conflict", "filesystem_unavailable"].includes(String(cause.code)) || typeof cause.message != "string" || !cause.message || cause.message.length > 512 || /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(cause.message) || cause.path !== void 0 && !localDataPath(cause.path, repository) || !row.files || typeof row.files != "object" || Array.isArray(row.files)) return invalid18();
7076
+ 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 invalid19();
6999
7077
  let files3 = row.files;
7000
- if (Object.keys(files3).some((key) => !["state", "saved", "failed", "notAttempted", "savedOmitted", "notAttemptedOmitted"].includes(key)) || !["none", "partial"].includes(String(files3.state)) || !Array.isArray(files3.saved) || files3.saved.length > 128 || !files3.saved.every((item) => localDataFile(item, repository)) || files3.failed !== void 0 && !localDataFile(files3.failed, repository) || !Array.isArray(files3.notAttempted) || files3.notAttempted.length > 128 || !files3.notAttempted.every((item) => localDataFile(item, repository))) return invalid18();
7001
- for (let key of ["savedOmitted", "notAttemptedOmitted"]) if (files3[key] !== void 0 && (!Number.isSafeInteger(files3[key]) || Number(files3[key]) < 1 || Number(files3[key]) > 1e4)) return invalid18();
7002
- return row.operation === "read" && (row.code !== "local_data_read_failed" || files3.state !== "none" || files3.saved.length || files3.failed !== void 0 || files3.notAttempted.length) || row.operation === "write" && row.code === "local_data_read_failed" || row.code === "local_data_write_partial" && (files3.state !== "partial" || !files3.saved.length) || row.code !== "local_data_write_partial" && files3.state === "partial" ? invalid18() : structuredClone(value);
7078
+ 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 invalid19();
7079
+ for (let key of ["savedOmitted", "notAttemptedOmitted"]) if (files3[key] !== void 0 && (!Number.isSafeInteger(files3[key]) || Number(files3[key]) < 1 || Number(files3[key]) > 1e4)) return invalid19();
7080
+ 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" ? invalid19() : structuredClone(value);
7003
7081
  }
7004
7082
  function parseDataOperationDetail(value) {
7005
7083
  if (value && typeof value == "object" && !Array.isArray(value) && value.code === "publication_conflict")
@@ -7020,9 +7098,9 @@ function parseDataOperationDetail(value) {
7020
7098
  }
7021
7099
  return parseDataFailureDetail(value);
7022
7100
  }
7023
- function dataRecordLimitMessage(detail) {
7024
- let scope = detail.collections.length === 1 ? ` from ${detail.collections[0]}` : ` across ${detail.collections.join(", ")}`;
7025
- return `The routine tried to load more than ${detail.maxRecords.toLocaleString("en-US")} matching Records${scope}. Narrow the query or increase maxRecords.`;
7101
+ function dataRecordLimitMessage(detail2) {
7102
+ let scope = detail2.collections.length === 1 ? ` from ${detail2.collections[0]}` : ` across ${detail2.collections.join(", ")}`;
7103
+ return `The routine tried to load more than ${detail2.maxRecords.toLocaleString("en-US")} matching Records${scope}. Narrow the query or increase maxRecords.`;
7026
7104
  }
7027
7105
  function dataErrorMessage(code, effect) {
7028
7106
  return effect === "uncertain" ? "We couldn\u2019t confirm whether your changes were saved." : code === "unavailable" && effect === "unapplied" ? "Your changes could not be saved." : code === "apply_pending" ? effect === "applied" ? "Your changes were saved, but confirmation is still pending." : effect === "unapplied" ? "Your changes have not been saved yet." : "We couldn\u2019t confirm whether your changes were saved." : {
@@ -7039,8 +7117,8 @@ function dataErrorMessage(code, effect) {
7039
7117
  }[code] + (effect === "unapplied" ? " No changes were saved." : effect === "applied" ? " Your changes were saved." : "");
7040
7118
  }
7041
7119
  var DataOperationError = class extends Error {
7042
- constructor(code, retryable = !1, effect, component, detail) {
7043
- let parsed = detail === void 0 ? void 0 : parseDataOperationDetail(detail);
7120
+ constructor(code, retryable = !1, effect, component, detail2) {
7121
+ let parsed = detail2 === void 0 ? void 0 : parseDataOperationDetail(detail2);
7044
7122
  if (parsed && ("reason" in parsed ? code !== "invalid_change" : parsed.code === "publication_conflict" ? !["invalid_change", "conflict"].includes(code) : parsed.code === "record_limit_exceeded" && code !== "capacity"))
7045
7123
  throw new Error("Invalid Data operation detail");
7046
7124
  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));
@@ -7048,7 +7126,7 @@ var DataOperationError = class extends Error {
7048
7126
  this.retryable = retryable;
7049
7127
  this.effect = effect;
7050
7128
  this.component = component;
7051
- this.detail = detail;
7129
+ this.detail = detail2;
7052
7130
  this.name = "DataOperationError", parsed !== void 0 && (this.detail = parsed);
7053
7131
  }
7054
7132
  code;
@@ -7083,19 +7161,19 @@ function parseConnectionFailureDetail(value) {
7083
7161
  };
7084
7162
  }
7085
7163
  function connectionFailureMessage(value) {
7086
- let detail = parseConnectionFailureDetail(value), [, provider2, name4] = identityPattern.exec(detail.identity), duration = detail.elapsedMs < 1e3 ? `${detail.elapsedMs}ms` : `${(detail.elapsedMs / 1e3).toFixed(1)}s`, explanation = `OS couldn\u2019t grant this Run access to ${providerNames[provider2]} connection ${name4}.
7087
- ${detail.attempts} ${detail.attempts === 1 ? "attempt" : "attempts"} in ${duration}.
7164
+ let detail2 = parseConnectionFailureDetail(value), [, provider2, name4] = identityPattern.exec(detail2.identity), duration = detail2.elapsedMs < 1e3 ? `${detail2.elapsedMs}ms` : `${(detail2.elapsedMs / 1e3).toFixed(1)}s`, explanation = `OS couldn\u2019t grant this Run access to ${providerNames[provider2]} connection ${name4}.
7165
+ ${detail2.attempts} ${detail2.attempts === 1 ? "attempt" : "attempts"} in ${duration}.
7088
7166
 
7089
7167
  The routine received no provider access through this lease and made no provider business request through it.`;
7090
- return detail.code !== "attention_required" ? explanation : detail.workspace ? `${explanation}
7168
+ return detail2.code !== "attention_required" ? explanation : detail2.workspace ? `${explanation}
7091
7169
 
7092
7170
  Check it with:
7093
- os connection test --workspace ${detail.workspace} --connection ${detail.identity}` : `${explanation}
7171
+ os connection test --workspace ${detail2.workspace} --connection ${detail2.identity}` : `${explanation}
7094
7172
 
7095
7173
  Check or reconnect this Connection.`;
7096
7174
  }
7097
- function connectionRunFailureMessage(detail, completedWork = !1) {
7098
- return connectionFailureMessage(detail) + `
7175
+ function connectionRunFailureMessage(detail2, completedWork = !1) {
7176
+ return connectionFailureMessage(detail2) + `
7099
7177
 
7100
7178
  The Run stopped safely.` + (completedWork ? `
7101
7179
 
@@ -7121,26 +7199,26 @@ var ConnectionOperationError = class extends Error {
7121
7199
  get status() {
7122
7200
  return this.detail.status;
7123
7201
  }
7124
- constructor(identity3, workspace, facts2 = {
7202
+ constructor(identity4, workspace, facts2 = {
7125
7203
  code: "invalid_response",
7126
7204
  stage: "validation",
7127
7205
  retryable: !1,
7128
7206
  attempts: 0,
7129
7207
  elapsedMs: 0
7130
7208
  }) {
7131
- let detail = parseConnectionFailureDetail({ ...facts2, identity: identity3, ...workspace === void 0 ? {} : { workspace } });
7132
- super(connectionFailureMessage(detail)), this.name = "ConnectionOperationError", this.detail = detail;
7209
+ let detail2 = parseConnectionFailureDetail({ ...facts2, identity: identity4, ...workspace === void 0 ? {} : { workspace } });
7210
+ super(connectionFailureMessage(detail2)), this.name = "ConnectionOperationError", this.detail = detail2;
7133
7211
  }
7134
7212
  };
7135
7213
 
7136
7214
  var ROUTINE_ERROR_CODE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
7137
7215
  function parseRoutineErrorDeclaration(value) {
7138
- let invalid18 = () => {
7216
+ let invalid19 = () => {
7139
7217
  throw new TypeError("Invalid RoutineError");
7140
7218
  };
7141
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
7219
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid19();
7142
7220
  let row = value;
7143
- return Object.keys(row).some((key) => !["code", "message", "retryable"].includes(key)) || !Object.hasOwn(row, "code") || !Object.hasOwn(row, "message") || typeof row.code != "string" || !ROUTINE_ERROR_CODE_PATTERN.test(row.code) || typeof row.message != "string" || !row.message || row.message.startsWith(" ") || row.message.endsWith(" ") || /[\u0000-\u001f\u007f\u0085\u2028\u2029]/.test(row.message) || /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF])/.test(row.message) || new TextEncoder().encode(row.message).byteLength > 512 || Object.hasOwn(row, "retryable") && typeof row.retryable != "boolean" ? invalid18() : { code: row.code, message: row.message, retryable: row.retryable === !0 };
7221
+ return Object.keys(row).some((key) => !["code", "message", "retryable"].includes(key)) || !Object.hasOwn(row, "code") || !Object.hasOwn(row, "message") || typeof row.code != "string" || !ROUTINE_ERROR_CODE_PATTERN.test(row.code) || typeof row.message != "string" || !row.message || row.message.startsWith(" ") || row.message.endsWith(" ") || /[\u0000-\u001f\u007f\u0085\u2028\u2029]/.test(row.message) || /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF])/.test(row.message) || new TextEncoder().encode(row.message).byteLength > 512 || Object.hasOwn(row, "retryable") && typeof row.retryable != "boolean" ? invalid19() : { code: row.code, message: row.message, retryable: row.retryable === !0 };
7144
7222
  }
7145
7223
  var RoutineError = class extends Error {
7146
7224
  code;
@@ -7157,26 +7235,26 @@ Anything the routine completed before stopping is safe.`, ROUTINE_RUN_UNCERTAIN_
7157
7235
 
7158
7236
  Some work may need review before you try again. Contact support.`;
7159
7237
  function parseRoutineAuthoredRunFailure(value) {
7160
- let invalid18 = () => {
7238
+ let invalid19 = () => {
7161
7239
  throw new Error("Invalid authored Run failure");
7162
7240
  };
7163
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
7241
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid19();
7164
7242
  let row = value;
7165
- if (Object.keys(row).sort().join(",") !== "code,message,retryable" || typeof row.message != "string" || typeof row.retryable != "boolean") return invalid18();
7243
+ if (Object.keys(row).sort().join(",") !== "code,message,retryable" || typeof row.message != "string" || typeof row.retryable != "boolean") return invalid19();
7166
7244
  let authored = row.message.endsWith(ROUTINE_RUN_UNCERTAIN_SUFFIX) ? row.message.slice(0, -ROUTINE_RUN_UNCERTAIN_SUFFIX.length) : row.message.endsWith(ROUTINE_RUN_COMPLETED_SUFFIX) ? row.message.slice(0, -ROUTINE_RUN_COMPLETED_SUFFIX.length) : row.message;
7167
7245
  try {
7168
7246
  parseRoutineErrorDeclaration({ code: row.code, message: authored, retryable: row.retryable });
7169
7247
  } catch {
7170
- return invalid18();
7248
+ return invalid19();
7171
7249
  }
7172
7250
  return { code: row.code, message: row.message, retryable: row.retryable };
7173
7251
  }
7174
7252
 
7175
- var name2 = /^[a-z0-9][a-z0-9-]{0,62}$/, uuid3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, invalid5 = () => {
7253
+ var name2 = /^[a-z0-9][a-z0-9-]{0,62}$/, uuid3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, invalid6 = () => {
7176
7254
  throw new Error("Run state unavailable");
7177
- }, record2 = (value) => value && typeof value == "object" && !Array.isArray(value) ? value : invalid5();
7255
+ }, record2 = (value) => value && typeof value == "object" && !Array.isArray(value) ? value : invalid6();
7178
7256
  function time(value) {
7179
- return typeof value != "string" || value.length > 40 || !Number.isFinite(Date.parse(value)) ? invalid5() : value;
7257
+ return typeof value != "string" || value.length > 40 || !Number.isFinite(Date.parse(value)) ? invalid6() : value;
7180
7258
  }
7181
7259
  function times(value) {
7182
7260
  return {
@@ -7185,16 +7263,16 @@ function times(value) {
7185
7263
  };
7186
7264
  }
7187
7265
  function bounded(value) {
7188
- return assertRoutineJson(value), new TextEncoder().encode(JSON.stringify(value)).byteLength > 256 * 1024 ? invalid5() : value;
7266
+ return assertRoutineJson(value), new TextEncoder().encode(JSON.stringify(value)).byteLength > 256 * 1024 ? invalid6() : value;
7189
7267
  }
7190
7268
  function progress(value) {
7191
7269
  if (value === void 0) return {};
7192
7270
  let v = record2(value);
7193
- return Object.keys(v).sort().join(",") !== "completed,total" || !Number.isSafeInteger(v.completed) || !Number.isSafeInteger(v.total) || v.completed < 1 || v.completed > v.total ? invalid5() : { progress: { completed: v.completed, total: v.total } };
7271
+ return Object.keys(v).sort().join(",") !== "completed,total" || !Number.isSafeInteger(v.completed) || !Number.isSafeInteger(v.total) || v.completed < 1 || v.completed > v.total ? invalid6() : { progress: { completed: v.completed, total: v.total } };
7194
7272
  }
7195
7273
  function parseRunStep(value, expected) {
7196
7274
  let v = record2(value);
7197
- if (typeof v.id != "string" || !name2.test(v.id) || expected !== void 0 && v.id !== expected || typeof v.title != "string" || !v.title.trim() || v.title.length > 256 || !["pending", "running", "waiting", "completed", "failed", "skipped"].includes(v.status)) return invalid5();
7275
+ if (typeof v.id != "string" || !name2.test(v.id) || expected !== void 0 && v.id !== expected || typeof v.title != "string" || !v.title.trim() || v.title.length > 256 || !["pending", "running", "waiting", "completed", "failed", "skipped"].includes(v.status)) return invalid6();
7198
7276
  let output = captureRetainedStepOutput(v.id, {
7199
7277
  ...Object.hasOwn(v, "summary") ? { summary: v.summary } : {},
7200
7278
  ...Object.hasOwn(v, "data") ? { data: v.data } : {}
@@ -7211,31 +7289,31 @@ function parseRunStep(value, expected) {
7211
7289
  }
7212
7290
  function parseRemoteRun(value, expected = {}) {
7213
7291
  let v = record2(value);
7214
- if (typeof v.id != "string" || !uuid3.test(v.id) || expected.id !== void 0 && v.id !== expected.id || typeof v.routine != "string" || !name2.test(v.routine) || expected.routine !== void 0 && v.routine !== expected.routine || v.placement !== "remote" || !["queued", "running", "waiting", "succeeded", "failed"].includes(v.status) || !Array.isArray(v.steps) || v.steps.length > 64) return invalid5();
7292
+ if (typeof v.id != "string" || !uuid3.test(v.id) || expected.id !== void 0 && v.id !== expected.id || typeof v.routine != "string" || !name2.test(v.routine) || expected.routine !== void 0 && v.routine !== expected.routine || v.placement !== "remote" || !["queued", "running", "waiting", "succeeded", "failed"].includes(v.status) || !Array.isArray(v.steps) || v.steps.length > 64) return invalid6();
7215
7293
  let steps = v.steps.map((value2) => {
7216
7294
  let step = record2(value2);
7217
- return typeof step.detailAvailable != "boolean" || Object.hasOwn(step, "data") ? invalid5() : { ...parseRunStep(step), detailAvailable: step.detailAvailable };
7295
+ return typeof step.detailAvailable != "boolean" || Object.hasOwn(step, "data") ? invalid6() : { ...parseRunStep(step), detailAvailable: step.detailAvailable };
7218
7296
  });
7219
- if (new Set(steps.map((step) => step.id)).size !== steps.length) return invalid5();
7297
+ if (new Set(steps.map((step) => step.id)).size !== steps.length) return invalid6();
7220
7298
  let failure;
7221
7299
  if (v.failure !== void 0) {
7222
7300
  let f = record2(v.failure);
7223
- if (v.status !== "failed" || typeof f.message != "string" || !f.message || f.message.length > 512) return invalid5();
7301
+ if (v.status !== "failed" || typeof f.message != "string" || !f.message || f.message.length > 512) return invalid6();
7224
7302
  if (f.code === "step_output_too_large") {
7225
- let { code, message: message2, ...facts2 } = f, detail = parseRoutineStepOutputDetail(facts2);
7226
- if (!steps.some((step) => step.id === detail.step && step.status === "failed") || message2 !== routineStepOutputMessage(detail)) return invalid5();
7227
- failure = { code, message: message2, ...detail };
7303
+ let { code, message: message2, ...facts2 } = f, detail2 = parseRoutineStepOutputDetail(facts2);
7304
+ if (!steps.some((step) => step.id === detail2.step && step.status === "failed") || message2 !== routineStepOutputMessage(detail2)) return invalid6();
7305
+ failure = { code, message: message2, ...detail2 };
7228
7306
  } else if (f.code !== void 0 || Object.hasOwn(f, "retryable"))
7229
7307
  try {
7230
7308
  failure = parseRoutineAuthoredRunFailure(f);
7231
7309
  } catch {
7232
- return invalid5();
7310
+ return invalid6();
7233
7311
  }
7234
7312
  else failure = { message: f.message };
7235
7313
  }
7236
- if (Object.hasOwn(v, "result") && v.status !== "succeeded") return invalid5();
7314
+ if (Object.hasOwn(v, "result") && v.status !== "succeeded") return invalid6();
7237
7315
  let askWait = v.askWait === void 0 ? void 0 : parseQueueAskWait(v.askWait);
7238
- return askWait && askWait.runId !== v.id ? invalid5() : {
7316
+ return askWait && askWait.runId !== v.id ? invalid6() : {
7239
7317
  id: v.id,
7240
7318
  routine: v.routine,
7241
7319
  placement: "remote",
@@ -7243,7 +7321,7 @@ function parseRemoteRun(value, expected = {}) {
7243
7321
  createdAt: time(v.createdAt),
7244
7322
  ...times(v),
7245
7323
  steps,
7246
- ...v.queueItemId === void 0 ? {} : { queueItemId: typeof v.queueItemId == "string" && uuid3.test(v.queueItemId) ? v.queueItemId : invalid5() },
7324
+ ...v.queueItemId === void 0 ? {} : { queueItemId: typeof v.queueItemId == "string" && uuid3.test(v.queueItemId) ? v.queueItemId : invalid6() },
7247
7325
  ...askWait === void 0 ? {} : { askWait },
7248
7326
  ...Object.hasOwn(v, "result") ? { result: bounded(v.result) } : {},
7249
7327
  ...failure ? { failure } : {}
@@ -7265,65 +7343,65 @@ function routineRunHandle(operations2) {
7265
7343
  });
7266
7344
  }
7267
7345
 
7268
- var invalid6 = () => {
7346
+ var invalid7 = () => {
7269
7347
  throw new DataOperationError("invalid_query");
7270
7348
  }, dataText = (value) => typeof value == "string" && !/[\u0000\uD800-\uDFFF]/u.test(value), dataVersion = (value) => dataText(value) && value.length > 0 && new TextEncoder().encode(value).length <= 1024 && !/[\u0000-\u001f\u007f-\u009f]/.test(value) && !/^[0-9a-f]{40}$/i.test(value);
7271
7349
  function dataProperties(value) {
7272
- if (!value || typeof value != "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return invalid6();
7350
+ if (!value || typeof value != "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return invalid7();
7273
7351
  let descriptors = Object.getOwnPropertyDescriptors(value);
7274
- return Reflect.ownKeys(value).some((key) => typeof key != "string" || !descriptors[key]?.enumerable || !Object.hasOwn(descriptors[key], "value")) ? invalid6() : descriptors;
7352
+ return Reflect.ownKeys(value).some((key) => typeof key != "string" || !descriptors[key]?.enumerable || !Object.hasOwn(descriptors[key], "value")) ? invalid7() : descriptors;
7275
7353
  }
7276
7354
  function dataArray(value) {
7277
- if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype) return invalid6();
7355
+ if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype) return invalid7();
7278
7356
  let descriptors = Object.getOwnPropertyDescriptors(value);
7279
- if (Reflect.ownKeys(value).length !== value.length + 1) return invalid6();
7357
+ if (Reflect.ownKeys(value).length !== value.length + 1) return invalid7();
7280
7358
  let result2 = [];
7281
7359
  for (let index = 0; index < value.length; index++) {
7282
7360
  let descriptor = descriptors[index];
7283
- if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value")) return invalid6();
7361
+ if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value")) return invalid7();
7284
7362
  result2.push(descriptor.value);
7285
7363
  }
7286
7364
  return result2;
7287
7365
  }
7288
7366
 
7289
- var invalid7 = () => {
7367
+ var invalid8 = () => {
7290
7368
  throw new DataOperationError("invalid_query");
7291
7369
  };
7292
7370
  function captureRecordsBacklinksInput(ref, value) {
7293
- if (!validRecordRef(ref)) return invalid7();
7371
+ if (!validRecordRef(ref)) return invalid8();
7294
7372
  if (value === void 0) return { ref, options: { limit: 100 } };
7295
7373
  let descriptors = dataProperties(value);
7296
- if (Object.keys(descriptors).some((key) => !["limit", "after"].includes(key))) return invalid7();
7374
+ if (Object.keys(descriptors).some((key) => !["limit", "after"].includes(key))) return invalid8();
7297
7375
  let options = Object.fromEntries(Object.entries(descriptors).map(([key, descriptor]) => [key, descriptor.value])), limit = Object.hasOwn(options, "limit") ? options.limit : 100;
7298
- return !Number.isSafeInteger(limit) || limit < 1 || limit > 500 || Object.hasOwn(options, "after") && (!dataText(options.after) || !options.after.length || options.after.length > 16384) ? invalid7() : { ref, options: { limit, ...options.after === void 0 ? {} : { after: options.after } } };
7376
+ return !Number.isSafeInteger(limit) || limit < 1 || limit > 500 || Object.hasOwn(options, "after") && (!dataText(options.after) || !options.after.length || options.after.length > 16384) ? invalid8() : { ref, options: { limit, ...options.after === void 0 ? {} : { after: options.after } } };
7299
7377
  }
7300
7378
 
7301
- var invalid8 = () => {
7379
+ var invalid9 = () => {
7302
7380
  throw new DataOperationError("invalid_query");
7303
7381
  };
7304
7382
  function captureRecordsSearchInput(query, options) {
7305
- if (!dataText(query)) return invalid8();
7383
+ if (!dataText(query)) return invalid9();
7306
7384
  let length = [...query.trim()].length;
7307
- if (length < 1 || length > 256) return invalid8();
7385
+ if (length < 1 || length > 256) return invalid9();
7308
7386
  if (options === void 0) return { query };
7309
7387
  let descriptors = dataProperties(options);
7310
- if (Object.keys(descriptors).some((key) => !["collections", "limit"].includes(key))) return invalid8();
7388
+ if (Object.keys(descriptors).some((key) => !["collections", "limit"].includes(key))) return invalid9();
7311
7389
  let captured = {};
7312
7390
  if (Object.hasOwn(descriptors, "collections")) {
7313
7391
  let supplied = descriptors.collections.value;
7314
- if (!Array.isArray(supplied) || supplied.length < 1 || supplied.length > 16 || Reflect.ownKeys(supplied).length !== supplied.length + 1) return invalid8();
7392
+ if (!Array.isArray(supplied) || supplied.length < 1 || supplied.length > 16 || Reflect.ownKeys(supplied).length !== supplied.length + 1) return invalid9();
7315
7393
  let collections = [];
7316
7394
  for (let index = 0; index < supplied.length; index++) {
7317
7395
  let descriptor = Object.getOwnPropertyDescriptor(supplied, String(index));
7318
- if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value") || !dataText(descriptor.value)) return invalid8();
7396
+ if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value") || !dataText(descriptor.value)) return invalid9();
7319
7397
  collections.push(descriptor.value);
7320
7398
  }
7321
- if (new Set(collections).size !== collections.length) return invalid8();
7399
+ if (new Set(collections).size !== collections.length) return invalid9();
7322
7400
  captured.collections = collections;
7323
7401
  }
7324
7402
  if (Object.hasOwn(descriptors, "limit")) {
7325
7403
  let supplied = descriptors.limit.value;
7326
- if (!Number.isInteger(supplied) || supplied < 1 || supplied > 100) return invalid8();
7404
+ if (!Number.isInteger(supplied) || supplied < 1 || supplied > 100) return invalid9();
7327
7405
  captured.limit = supplied;
7328
7406
  }
7329
7407
  return { query, options: captured };
@@ -7363,21 +7441,21 @@ function captureRecordsQuery(query) {
7363
7441
  return capture3(query);
7364
7442
  }
7365
7443
  function captureRecordsAll(query, options) {
7366
- let invalid18 = () => {
7444
+ let invalid19 = () => {
7367
7445
  throw new DataOperationError("invalid_query");
7368
7446
  };
7369
7447
  try {
7370
7448
  let properties = dataProperties(options), maxRecords = properties.maxRecords?.value;
7371
- if (Object.keys(properties).join(",") !== "maxRecords" || !Number.isSafeInteger(maxRecords) || maxRecords < 1) return invalid18();
7449
+ if (Object.keys(properties).join(",") !== "maxRecords" || !Number.isSafeInteger(maxRecords) || maxRecords < 1) return invalid19();
7372
7450
  let detached = capture3(query), selections = dataProperties(detached);
7373
- if (Object.keys(selections).length < 1 || Object.keys(selections).length > 16) return invalid18();
7451
+ if (Object.keys(selections).length < 1 || Object.keys(selections).length > 16) return invalid19();
7374
7452
  for (let selection2 of Object.values(selections)) {
7375
7453
  let fields4 = dataProperties(selection2.value);
7376
- if (fields4.$ && Object.hasOwn(dataProperties(fields4.$.value), "after")) return invalid18();
7454
+ if (fields4.$ && Object.hasOwn(dataProperties(fields4.$.value), "after")) return invalid19();
7377
7455
  }
7378
7456
  return { query: detached, maxRecords };
7379
7457
  } catch {
7380
- return invalid18();
7458
+ return invalid19();
7381
7459
  }
7382
7460
  }
7383
7461
 
@@ -7512,8 +7590,8 @@ function captureValue(value, ancestors = /* @__PURE__ */ new Set(), depth = 0) {
7512
7590
  }
7513
7591
  }
7514
7592
  function captureDataDelete(record4) {
7515
- let identity3 = mapping2(record4);
7516
- return !validRecordRef(identity3.$ref) || typeof identity3.$version != "string" || !identity3.$version.length || identity3.$version.length > 512 ? invalidChange() : { ref: identity3.$ref, expectedVersion: identity3.$version };
7593
+ let identity4 = mapping2(record4);
7594
+ return !validRecordRef(identity4.$ref) || typeof identity4.$version != "string" || !identity4.$version.length || identity4.$version.length > 512 ? invalidChange() : { ref: identity4.$ref, expectedVersion: identity4.$version };
7517
7595
  }
7518
7596
  function captureDataUpdate(record4, set) {
7519
7597
  if (!validRecordRef(record4)) return invalidChange();
@@ -7525,11 +7603,11 @@ function captureIdentities(value, update, allowEmpty = !0) {
7525
7603
  let captured = value.map((item) => {
7526
7604
  let row = mapping2(item);
7527
7605
  if (Object.keys(row).filter((key) => !update || !["body", "expectedVersion", "signals", "timeline"].includes(key)).sort().join(",") !== (update ? "ref,set" : "expectedVersion,ref")) return invalidChange();
7528
- let identity3 = { $ref: row.ref, $version: row.expectedVersion };
7606
+ let identity4 = { $ref: row.ref, $version: row.expectedVersion };
7529
7607
  if (update && Object.keys(mapping2(row.set)).some((key) => key.startsWith("$"))) return invalidChange();
7530
- if (!update) return captureDataDelete(identity3);
7608
+ if (!update) return captureDataDelete(identity4);
7531
7609
  let tables = captureDataTables(row);
7532
- return { ...Object.keys(mapping2(row.set)).length || Object.hasOwn(row, "body") ? captureDataUpdate(row.ref, { ...mapping2(row.set), ...Object.hasOwn(row, "body") ? { $body: row.body } : {} }) : validRecordRef(row.ref) && Object.keys(tables).length ? { ref: row.ref, set: {} } : invalidChange(), ...tables, ...Object.hasOwn(row, "expectedVersion") ? { expectedVersion: captureDataDelete(identity3).expectedVersion } : {} };
7610
+ return { ...Object.keys(mapping2(row.set)).length || Object.hasOwn(row, "body") ? captureDataUpdate(row.ref, { ...mapping2(row.set), ...Object.hasOwn(row, "body") ? { $body: row.body } : {} }) : validRecordRef(row.ref) && Object.keys(tables).length ? { ref: row.ref, set: {} } : invalidChange(), ...tables, ...Object.hasOwn(row, "expectedVersion") ? { expectedVersion: captureDataDelete(identity4).expectedVersion } : {} };
7533
7611
  });
7534
7612
  return new Set(captured.map((item) => item.ref)).size !== captured.length ? invalidChange() : captured;
7535
7613
  }
@@ -7580,17 +7658,17 @@ function dataTransportError(status, value) {
7580
7658
  413: ["request_too_large"],
7581
7659
  429: ["capacity"],
7582
7660
  503: ["unavailable", "apply_pending"]
7583
- }, error = value && typeof value == "object" && "error" in value ? value.error : void 0, row = error && typeof error == "object" ? error : void 0, code = failures2[status]?.find((allowed) => allowed === row?.code) ?? "unavailable", effect = ["unapplied", "uncertain", "applied"].includes(String(row?.effect)) ? row.effect : void 0, detail;
7661
+ }, error = value && typeof value == "object" && "error" in value ? value.error : void 0, row = error && typeof error == "object" ? error : void 0, code = failures2[status]?.find((allowed) => allowed === row?.code) ?? "unavailable", effect = ["unapplied", "uncertain", "applied"].includes(String(row?.effect)) ? row.effect : void 0, detail2;
7584
7662
  try {
7585
- detail = row?.detail === void 0 ? void 0 : parseDataOperationDetail(row.detail);
7663
+ detail2 = row?.detail === void 0 ? void 0 : parseDataOperationDetail(row.detail);
7586
7664
  } catch {
7587
7665
  }
7588
- 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(
7666
+ return detail2 && ("reason" in detail2 && code !== "invalid_change" || "code" in detail2 && detail2.code === "publication_conflict" && !["invalid_change", "conflict"].includes(code)) && (detail2 = void 0), explainDataValidation(new DataOperationError(
7589
7667
  code,
7590
7668
  typeof row?.retryable == "boolean" ? row.retryable : ["capacity", "unavailable", "apply_pending"].includes(code),
7591
7669
  code === "conflict" ? "unapplied" : effect,
7592
7670
  (["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,
7593
- detail
7671
+ detail2
7594
7672
  ), row?.message, row?.detail);
7595
7673
  }
7596
7674
 
@@ -7615,10 +7693,10 @@ function parseStoredRecordLink(value) {
7615
7693
  return typeof value == "string" && value.startsWith("[[") && value.endsWith("]]") ? parseRecordLink(value.slice(2, -2)) : void 0;
7616
7694
  }
7617
7695
 
7618
- var NAME = /^[a-zA-Z][a-zA-Z0-9_-]*$/, invalid9 = (message2) => {
7696
+ var NAME = /^[a-zA-Z][a-zA-Z0-9_-]*$/, invalid10 = (message2) => {
7619
7697
  throw new Error(message2);
7620
7698
  };
7621
- function parseRecordDisplay(value, definitions3, fail9 = invalid9) {
7699
+ function parseRecordDisplay(value, definitions3, fail9 = invalid10) {
7622
7700
  if (value === void 0) return;
7623
7701
  if (!value || typeof value != "object" || Array.isArray(value)) return fail9("Expected a field mapping");
7624
7702
  let row = value;
@@ -7670,7 +7748,7 @@ function parseInboxRecords(value, maximumRecords = 100) {
7670
7748
 
7671
7749
  var InboxOperationError = class extends Error {
7672
7750
  constructor(status, reason) {
7673
- super(reason === "action_processing" ? "The previous answer is still processing. Wait for it to finish." : reason === "action_failed" ? "The previous answer could not be completed. Further answers are on hold." : reason === "handler_unavailable" ? "Deploy the routine that owns this question\u2019s response handler." : reason === "client_update_required" ? "This app must be updated to use Inbox Questions." : reason === "conflict" ? "This question already has an accepted answer" : reason === "unavailable" ? "Inbox request unavailable. Retry the same action." : reason === "invalid_input" ? "Invalid Inbox request" : "Inbox access unavailable");
7751
+ super(reason === "question_unavailable" ? "This Question is missing, changed, answered, or no longer open. Reload before assigning." : reason === "assignment_denied" ? "Only the current assignee can assign this Question." : reason === "assignee_unavailable" ? "The assignee is not a current workspace member." : reason === "action_processing" ? "The previous answer is still processing. Wait for it to finish." : reason === "action_failed" ? "The previous answer could not be completed. Further answers are on hold." : reason === "handler_unavailable" ? "Deploy the routine that owns this question\u2019s response handler." : reason === "client_update_required" ? "This app must be updated to use Inbox Questions." : reason === "conflict" ? "This question already has an accepted answer" : reason === "unavailable" ? "Inbox request unavailable. Retry the same action." : reason === "invalid_input" ? "Invalid Inbox request" : "Inbox access unavailable");
7674
7752
  this.status = status;
7675
7753
  this.reason = reason;
7676
7754
  }
@@ -7689,6 +7767,11 @@ function questionAvailability(value, available = !1) {
7689
7767
  function parseInboxUnavailableFailure(value, status) {
7690
7768
  try {
7691
7769
  let envelope = object5(value);
7770
+ for (let [reason, code] of [["question_unavailable", 409], ["assignment_denied", 403], ["assignee_unavailable", 400]]) {
7771
+ let error = new InboxOperationError(code, reason);
7772
+ if (status === code && envelope.error === error.message)
7773
+ return keys2(envelope, ["error"]), error;
7774
+ }
7692
7775
  if (status === 409) {
7693
7776
  keys2(envelope, ["error"]);
7694
7777
  for (let reason of ["action_processing", "action_failed"]) {
@@ -7711,6 +7794,9 @@ function parseInboxUnavailableFailure(value, status) {
7711
7794
  }
7712
7795
  }
7713
7796
  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;
7797
+ function isAssignmentTarget(value) {
7798
+ return typeof value == "string" && value === value.trim() && value.length <= 320 && (INBOX_UUID.test(value) || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value));
7799
+ }
7714
7800
  function isAppQuestionOperation(operation2) {
7715
7801
  return operation2 === "questions.list" || operation2 === "questions.answer" || operation2 === "questions.listRecordOptions";
7716
7802
  }
@@ -7729,7 +7815,9 @@ var operations = {
7729
7815
  "items.listRecipientCandidates": ["itemId"],
7730
7816
  "items.addRecipient": ["itemId", "personId"],
7731
7817
  "questions.answer": ["itemId", "revision", "questionId", "response", "submissionKey"],
7732
- "questions.listRecordOptions": ["itemId", "revision", "questionId"]
7818
+ "questions.listRecordOptions": ["itemId", "revision", "questionId"],
7819
+ "questions.listAssignmentCandidates": ["itemId", "revision", "questionId"],
7820
+ "questions.assign": ["itemId", "revision", "questionId", "assignee"]
7733
7821
  };
7734
7822
  function assert(value) {
7735
7823
  if (!value) throw new Error("Invalid Inbox result");
@@ -7808,6 +7896,9 @@ function responseDefinition(value) {
7808
7896
  []
7809
7897
  ), option.type === "choice" ? choiceValue(option.value) : recordReference(option.value), choiceDetails(option);
7810
7898
  break;
7899
+ case "assign":
7900
+ keys2(option, ["id", "type", "label", "assignee"], []), "assignee" in option && assert(id4(option.assignee));
7901
+ break;
7811
7902
  case "record-picker": {
7812
7903
  keys2(option, ["id", "type", "label", "source"]);
7813
7904
  let source3 = object5(option.source);
@@ -7856,7 +7947,7 @@ function response(value, definition, numbered = !1) {
7856
7947
  if (typeof selected == "string" ? choiceValue(selected) : recordReference(selected), options || numbered) {
7857
7948
  if (keys2(answer, ["option", "value", "note"], []), assert(integer(answer.option) && answer.option <= (options?.length ?? 9)), options) {
7858
7949
  let option = object5(options[answer.option - 1]);
7859
- assert(option.type === "choice" == (typeof selected == "string")), assert("note" in answer == (option.type === "choice" && "note" in option));
7950
+ assert(option.type !== "assign"), assert(option.type === "choice" == (typeof selected == "string")), assert("note" in answer == (option.type === "choice" && "note" in option));
7860
7951
  }
7861
7952
  } else assert(Object.keys(answer).every((key) => ["selection", "note"].includes(key)));
7862
7953
  return Object.hasOwn(answer, "note") && assert(text2(answer.note)), answer;
@@ -7872,7 +7963,7 @@ function parseInboxRequest(value) {
7872
7963
  let input = { ...object5(envelope.input) }, required = operations[operation2];
7873
7964
  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)));
7874
7965
  for (let key of ["itemId", "personId", "fileId"]) key in input && assert(id4(input[key]));
7875
- if ("revision" in input && assert(integer(input.revision)), "beforeNumber" in input && assert(integer(input.beforeNumber)), "questionId" in input && assert(text2(input.questionId) && input.questionId === input.questionId.trim()), "submissionKey" in input && assert(text2(input.submissionKey) && input.submissionKey.length <= 128 && input.submissionKey === input.submissionKey.trim()), "title" in input && assert(text2(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 object5(input.response)), "label" in input) {
7966
+ if ("revision" in input && assert(integer(input.revision)), "beforeNumber" in input && assert(integer(input.beforeNumber)), "questionId" in input && assert(text2(input.questionId) && input.questionId === input.questionId.trim()), "assignee" in input && assert(isAssignmentTarget(input.assignee)), "submissionKey" in input && assert(text2(input.submissionKey) && input.submissionKey.length <= 128 && input.submissionKey === input.submissionKey.trim()), "title" in input && assert(text2(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 object5(input.response)), "label" in input) {
7876
7967
  let answer = object5(input.response);
7877
7968
  assert(text2(input.label) && typeof ("option" in answer ? answer.value : answer.selection) == "object");
7878
7969
  }
@@ -7930,7 +8021,7 @@ function parseInboxItem(value) {
7930
8021
  let event = object5(value2);
7931
8022
  assert(integer(event.id) && text2(event.type) && (event.actorId === null || id4(event.actorId)) && (event.questionId === null || text2(event.questionId)) && integer(event.revision) && date3(event.createdAt));
7932
8023
  let data3 = object5(event.data);
7933
- event.type === "recipient-added" && (keys2(data3, ["personId"]), assert(id4(event.actorId) && id4(data3.personId)));
8024
+ event.type === "question-assigned" && (keys2(data3, ["previousAssigneeId", "assigneeId", "addedRecipient"]), assert(id4(event.actorId) && text2(event.questionId) && id4(data3.previousAssigneeId) && id4(data3.assigneeId) && typeof data3.addedRecipient == "boolean")), event.type === "recipient-added" && (keys2(data3, ["personId"]), assert(id4(event.actorId) && id4(data3.personId)));
7934
8025
  }), array2(item.work).forEach((value2) => {
7935
8026
  let work = object5(value2);
7936
8027
  assert(id4(work.id) && text2(work.questionId) && text2(work.reason) && optionalDate(work.settledAt));
@@ -8006,13 +8097,21 @@ function parseInboxResult(operation2, value, contract = INBOX_QUESTION_CONTRACT)
8006
8097
  let update = object5(value), item = parseInboxItem(update.item);
8007
8098
  return assert((update.activityId === null || integer(update.activityId)) && optionalDate(update.changedAt)), { ...update, item };
8008
8099
  }
8009
- if (operation2 === "items.listRecipientCandidates") {
8100
+ if (operation2 === "items.listRecipientCandidates" || operation2 === "questions.listAssignmentCandidates") {
8010
8101
  let candidates = array2(value);
8011
8102
  return candidates.forEach((value2) => {
8012
8103
  let person = object5(value2);
8013
- assert(id4(person.id) && text2(person.name) && text2(person.email));
8104
+ operation2 === "questions.listAssignmentCandidates" && keys2(person, ["id", "name", "email"]), assert(id4(person.id) && text2(person.name) && text2(person.email));
8014
8105
  }), assert(new Set(candidates.map((value2) => object5(value2).id)).size === candidates.length), candidates;
8015
8106
  }
8107
+ if (operation2 === "questions.assign") {
8108
+ let result2 = object5(value);
8109
+ keys2(result2, ["item", "questionId", "previousAssigneeId", "assigneeId", "activityId", "assignedAt"]);
8110
+ let item = parseInboxItem(result2.item);
8111
+ assert(item.kind === "ask" && text2(result2.questionId) && id4(result2.previousAssigneeId) && id4(result2.assigneeId));
8112
+ let question2 = item.questions.find((question3) => question3.id === result2.questionId);
8113
+ return assert(question2 && question2.to === result2.assigneeId && question2.acceptedResponse === null && question2.execution === null && question2.allowedResponders.includes(result2.previousAssigneeId) && question2.allowedResponders.includes(result2.assigneeId) && item.people.some((person) => person.id === result2.assigneeId) && item.people.some((person) => person.id === result2.previousAssigneeId)), result2.previousAssigneeId === result2.assigneeId ? assert(result2.activityId === null && result2.assignedAt === null) : (assert(integer(result2.activityId) && date3(result2.assignedAt)), assert(item.activity.some((event) => event.id === result2.activityId && event.type === "question-assigned" && event.questionId === result2.questionId && event.revision === item.revision && event.createdAt === result2.assignedAt && event.actorId === result2.previousAssigneeId && event.data.previousAssigneeId === result2.previousAssigneeId && event.data.assigneeId === result2.assigneeId))), { ...result2, item };
8114
+ }
8016
8115
  if (operation2 === "items.addRecipient") {
8017
8116
  let addition = object5(value), item = parseInboxItem(addition.item);
8018
8117
  return assert(id4(addition.addedPersonId) && item.people.some((person) => person.id === addition.addedPersonId)), { ...addition, item };
@@ -8033,6 +8132,15 @@ function parseInboxResult(operation2, value, contract = INBOX_QUESTION_CONTRACT)
8033
8132
  }
8034
8133
  throw new Error("File content is not a JSON result");
8035
8134
  }
8135
+ function assertInboxAssignmentMatches(result2, input) {
8136
+ assert(result2.item.id === input.itemId && result2.item.revision === input.revision && result2.questionId === input.questionId && result2.assigneeId.toLowerCase() === input.assignee.toLowerCase());
8137
+ }
8138
+ function assignmentTargetId(assignee, candidates) {
8139
+ if (INBOX_UUID.test(assignee)) return assignee.toLowerCase();
8140
+ let matches2 = candidates.filter((person) => person.email.toLowerCase() === assignee.toLowerCase());
8141
+ if (matches2.length !== 1) throw new InboxOperationError(400, "assignee_unavailable");
8142
+ return matches2[0].id;
8143
+ }
8036
8144
  function parseInboxBootstrap(value) {
8037
8145
  let snapshot = object5(value);
8038
8146
  keys2(snapshot, ["current", "items", "hydrations"]);
@@ -8586,7 +8694,7 @@ function routineTransport() {
8586
8694
  var fail3 = (code) => {
8587
8695
  throw new RoutineOperationError(code);
8588
8696
  }, uuid4 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
8589
- function identity2(id5) {
8697
+ function identity3(id5) {
8590
8698
  return (typeof id5 != "string" || !uuid4.test(id5)) && fail3("invalid_input"), id5;
8591
8699
  }
8592
8700
  function name3(id5) {
@@ -8673,16 +8781,16 @@ function routineOperations(routine, host) {
8673
8781
  pause: () => request3(`${root}/queue/pause`, summary3, {}),
8674
8782
  resume: () => request3(`${root}/queue/resume`, summary3, {}),
8675
8783
  list: (options = {}) => request3(`${root}/queue/items${pageOptions(options, options.states ?? [])}`, parseQueuePage, void 0, void 0, 500 * 327680),
8676
- get: (id5) => request3(`${root}/queue/items/${identity2(id5)}`, selectedItem(id5)),
8784
+ get: (id5) => request3(`${root}/queue/items/${identity3(id5)}`, selectedItem(id5)),
8677
8785
  async add(input, options = {}) {
8678
8786
  (!options || Object.keys(options).some((key) => key !== "idempotencyKey") || options.idempotencyKey !== void 0 && typeof options.idempotencyKey != "string") && fail3("invalid_input");
8679
8787
  let body = { input, ...options };
8680
8788
  return new TextEncoder().encode(json2(input)).byteLength > 262144 && fail3("invalid_input"), host ? request3(`${root}/queue/items`, selectedItem(), body) : managedQueue("queue/add", { routineId: routine, ...body }, selectedItem(), !0);
8681
8789
  },
8682
8790
  async remove(id5) {
8683
- return id5 = identity2(id5), host ? request3(`${root}/queue/items/${id5}/remove`, selectedItem(id5), {}) : managedQueue("queue/remove", { routineId: routine, itemId: id5 }, selectedItem(id5));
8791
+ return id5 = identity3(id5), host ? request3(`${root}/queue/items/${id5}/remove`, selectedItem(id5), {}) : managedQueue("queue/remove", { routineId: routine, itemId: id5 }, selectedItem(id5));
8684
8792
  },
8685
- retry: (id5, options) => ((!options || Object.keys(options).join() !== "failureId") && fail3("invalid_input"), identity2(options.failureId), request3(`${root}/queue/items/${identity2(id5)}/retry`, selectedItem(id5), options))
8793
+ retry: (id5, options) => ((!options || Object.keys(options).join() !== "failureId") && fail3("invalid_input"), identity3(options.failureId), request3(`${root}/queue/items/${identity3(id5)}/retry`, selectedItem(id5), options))
8686
8794
  },
8687
8795
  queries: {
8688
8796
  list: () => request3(`${root}/queries`, (value) => Array.isArray(value) ? value.map((v) => {
@@ -8695,7 +8803,7 @@ function routineOperations(routine, host) {
8695
8803
  let result2 = parseQueryExecution(value);
8696
8804
  return (result2.queryId !== query || id5 !== void 0 && result2.id !== id5) && fail3("unavailable"), result2;
8697
8805
  }, handle2 = (id5) => {
8698
- identity2(id5);
8806
+ identity3(id5);
8699
8807
  let read2 = () => request3(`${path}/executions/${id5}`, execution(id5));
8700
8808
  return Object.freeze({ current: read2, async *watch() {
8701
8809
  let previous;
@@ -8725,7 +8833,7 @@ function routineOperations(routine, host) {
8725
8833
  runs: {
8726
8834
  list: () => request3(`${root}/runs`, (value) => !Array.isArray(value) || value.length > 20 ? fail3("unavailable") : value.map(readRun()), void 0, void 0, 340 * 1024 * 1024),
8727
8835
  async get(id5) {
8728
- return identity2(id5), current2(), runHandle(id5);
8836
+ return identity3(id5), current2(), runHandle(id5);
8729
8837
  }
8730
8838
  },
8731
8839
  async run(input) {
@@ -8757,18 +8865,17 @@ function inspectRoutineQueueReference(queue) {
8757
8865
  return id5;
8758
8866
  }
8759
8867
 
8760
- var definitions2 = /* @__PURE__ */ new WeakMap(), invalid10 = () => {
8868
+ var definitions2 = /* @__PURE__ */ new WeakMap(), invalid11 = () => {
8761
8869
  throw new AppRoutineContractError("invalid_contract");
8762
8870
  }, defineQuery = (definition) => {
8763
- if (assertRoutineFields(definition, ["id", "queue", "triggers", "access", "run"]), !isAppRoutineName(definition.id) || typeof definition.run != "function") return invalid10();
8764
- let routineId = inspectRoutineQueueReference(definition.queue), triggers;
8871
+ if (assertRoutineFields(definition, ["id", "queue", "triggers", "access", "run"]), !isAppRoutineName(definition.id) || typeof definition.run != "function") return invalid11();
8872
+ let routineId = inspectRoutineQueueReference(definition.queue), access = parseRoutineAccess(definition.access), triggers;
8765
8873
  try {
8766
- if (assertRoutineJson(definition.triggers), !Array.isArray(definition.triggers)) return invalid10();
8767
- triggers = definition.triggers.map((trigger) => (assertRoutineFields(trigger, ["schedule"]), { schedule: parseRoutineSchedule(trigger.schedule) }));
8874
+ triggers = parseQueryTriggers(definition.triggers, access);
8768
8875
  } catch {
8769
- return invalid10();
8876
+ return invalid11();
8770
8877
  }
8771
- let access = parseRoutineAccess(definition.access), contract = freezeRoutineMetadata({ id: definition.id, routineId, access, triggers }), captured = Object.freeze({ ...definition, access, triggers: contract.triggers });
8878
+ let contract = freezeRoutineMetadata({ id: definition.id, routineId, access, triggers }), captured = Object.freeze({ ...definition, access, triggers: contract.triggers });
8772
8879
  return definitions2.set(captured, contract), captured;
8773
8880
  };
8774
8881
 
@@ -8875,14 +8982,14 @@ function checked(workspace, endpoint, headers) {
8875
8982
  return { url: `${origin.origin}/api/data`, headers: { ...headers, "x-os-workspace": workspace } };
8876
8983
  }
8877
8984
 
8878
- var invalid11 = () => {
8985
+ var invalid12 = () => {
8879
8986
  throw new DataOperationError("invalid_query");
8880
8987
  }, unavailable = () => {
8881
8988
  throw new DataOperationError("unavailable");
8882
8989
  }, text3 = (value) => typeof value == "string" && value.length > 0;
8883
8990
  function capture4(value, ancestors = /* @__PURE__ */ new Set(), depth = 0) {
8884
8991
  if (value === null || typeof value == "string" || typeof value == "boolean" || typeof value == "number" && Number.isFinite(value)) return value;
8885
- if (!value || typeof value != "object" || ancestors.has(value) || depth > 32) return invalid11();
8992
+ if (!value || typeof value != "object" || ancestors.has(value) || depth > 32) return invalid12();
8886
8993
  ancestors.add(value);
8887
8994
  try {
8888
8995
  return Array.isArray(value) ? dataArray(value).map((item) => capture4(item, ancestors, depth + 1)) : Object.fromEntries(Object.entries(dataProperties(value)).map(([key, descriptor]) => [key, capture4(descriptor.value, ancestors, depth + 1)]));
@@ -8897,7 +9004,7 @@ function recordPagination(queryRecords) {
8897
9004
  let selection2 = dataProperties(captured[name4]);
8898
9005
  if (Object.hasOwn(selection2, "$")) {
8899
9006
  let options = dataProperties(selection2.$.value);
8900
- if (Object.hasOwn(options, "after")) return invalid11();
9007
+ if (Object.hasOwn(options, "after")) return invalid12();
8901
9008
  }
8902
9009
  }
8903
9010
  return iterate();
@@ -9405,9 +9512,9 @@ function cursorPosition(value, binding, limit) {
9405
9512
  return Object.keys(payload).length !== 4 || payload.format !== 1 || payload.binding !== binding || typeof position != "number" || !Number.isSafeInteger(position) || position <= 0 || position % limit !== 0 || typeof ref != "string" || !validRecordRef(ref) ? fail5("incompatible cursor") : { position, ref };
9406
9513
  }
9407
9514
 
9408
- var invalid12 = () => {
9515
+ var invalid13 = () => {
9409
9516
  throw new DataOperationError("unavailable", !0);
9410
- }, object7 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid12() : value, keys4 = (value, expected) => Object.keys(value).sort().join(",") === expected, hash = (value) => typeof value == "string" && /^[0-9a-f]{40}$/.test(value), time2 = (value) => typeof value == "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(value) && Number.isFinite(Date.parse(value)), sorted = (values) => values.every((value, i) => i === 0 || values[i - 1] < value);
9517
+ }, object7 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid13() : value, keys4 = (value, expected) => Object.keys(value).sort().join(",") === expected, hash = (value) => typeof value == "string" && /^[0-9a-f]{40}$/.test(value), time2 = (value) => typeof value == "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(value) && Number.isFinite(Date.parse(value)), sorted = (values) => values.every((value, i) => i === 0 || values[i - 1] < value);
9411
9518
  function json3(value) {
9412
9519
  if (!(value === null || typeof value == "boolean" || typeof value == "number" && Number.isFinite(value) || dataText(value))) {
9413
9520
  if (Array.isArray(value)) {
@@ -9415,7 +9522,7 @@ function json3(value) {
9415
9522
  return;
9416
9523
  }
9417
9524
  for (let [key, item] of Object.entries(object7(value))) {
9418
- if (!dataText(key)) return invalid12();
9525
+ if (!dataText(key)) return invalid13();
9419
9526
  json3(item);
9420
9527
  }
9421
9528
  }
@@ -9427,66 +9534,66 @@ var slot = (values, field) => Object.hasOwn(values, field) ? { present: !0, valu
9427
9534
  function apply(book, event) {
9428
9535
  let records = book.get(event.collection), prior = records.get(event.ref);
9429
9536
  if (event.kind === "create") {
9430
- if (prior) return invalid12();
9537
+ if (prior) return invalid13();
9431
9538
  records.set(event.ref, structuredClone(event.values));
9432
9539
  } else if (event.kind === "delete") {
9433
- if (!prior || stable(prior) !== stable(event.values)) return invalid12();
9540
+ if (!prior || stable(prior) !== stable(event.values)) return invalid13();
9434
9541
  records.delete(event.ref);
9435
9542
  } else if (event.kind === "rename") {
9436
9543
  let before = records.get(event.previousRef);
9437
- if (!before || prior) return invalid12();
9544
+ if (!before || prior) return invalid13();
9438
9545
  records.delete(event.previousRef), records.set(event.ref, before);
9439
9546
  } else if (event.kind === "update") {
9440
- if (!prior || stable(slot(prior, event.field)) !== stable(event.before) || stable(event.before) === stable(event.after)) return invalid12();
9547
+ if (!prior || stable(slot(prior, event.field)) !== stable(event.before) || stable(event.before) === stable(event.after)) return invalid13();
9441
9548
  event.after.present ? Object.defineProperty(prior, event.field, { value: structuredClone(event.after.value), enumerable: !0, configurable: !0, writable: !0 }) : delete prior[event.field];
9442
9549
  }
9443
9550
  }
9444
9551
  function validateSnapshotHistory(input, collections, version) {
9445
9552
  let row = object7(input), selections = object7(row.fields);
9446
- if (!keys4(row, "commits,fields,through") || !hash(row.through) || version !== `current-${row.through}` || !Array.isArray(row.commits) || !row.commits.length || !Object.keys(selections).length || !sorted(Object.keys(selections))) return invalid12();
9553
+ if (!keys4(row, "commits,fields,through") || !hash(row.through) || version !== `current-${row.through}` || !Array.isArray(row.commits) || !row.commits.length || !Object.keys(selections).length || !sorted(Object.keys(selections))) return invalid13();
9447
9554
  let book = /* @__PURE__ */ new Map();
9448
9555
  for (let [collection, selection2] of Object.entries(selections)) {
9449
9556
  let selected = object7(selection2), fields4 = selected.fields;
9450
- if (!Object.hasOwn(collections, collection) || !keys4(selected, "fields") || !Array.isArray(fields4) || !fields4.length || fields4.some((field) => typeof field != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(field)) || !sorted(fields4)) return invalid12();
9557
+ if (!Object.hasOwn(collections, collection) || !keys4(selected, "fields") || !Array.isArray(fields4) || !fields4.length || fields4.some((field) => typeof field != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(field)) || !sorted(fields4)) return invalid13();
9451
9558
  book.set(collection, /* @__PURE__ */ new Map());
9452
9559
  }
9453
9560
  let history = row, seen = /* @__PURE__ */ new Set(), parent = null;
9454
9561
  for (let group of history.commits) {
9455
- if (!keys4(object7(group), "authoredAt,commit,committedAt,events,firstParent") || !hash(group.commit) || seen.has(group.commit) || group.firstParent !== parent || !time2(group.authoredAt) || !time2(group.committedAt) || !Array.isArray(group.events)) return invalid12();
9562
+ if (!keys4(object7(group), "authoredAt,commit,committedAt,events,firstParent") || !hash(group.commit) || seen.has(group.commit) || group.firstParent !== parent || !time2(group.authoredAt) || !time2(group.committedAt) || !Array.isArray(group.events)) return invalid13();
9456
9563
  seen.add(group.commit), parent = group.commit;
9457
9564
  let previous, created = /* @__PURE__ */ new Set();
9458
9565
  for (let event of group.events) {
9459
- if (object7(event), !book.has(event.collection) || !validRecordRef(event.ref) || !event.ref.startsWith(`${event.collection}/`)) return invalid12();
9566
+ if (object7(event), !book.has(event.collection) || !validRecordRef(event.ref) || !event.ref.startsWith(`${event.collection}/`)) return invalid13();
9460
9567
  let fields4 = history.fields[event.collection].fields;
9461
9568
  if (event.kind === "create" || event.kind === "delete") {
9462
- if (!keys4(event, "collection,kind,ref,values") || Object.keys(object7(event.values)).some((field) => !fields4.includes(field))) return invalid12();
9569
+ if (!keys4(event, "collection,kind,ref,values") || Object.keys(object7(event.values)).some((field) => !fields4.includes(field))) return invalid13();
9463
9570
  json3(event.values), event.kind === "create" && created.add(event.ref);
9464
9571
  } else if (event.kind === "rename") {
9465
- if (!keys4(event, "collection,kind,previousRef,ref") || !validRecordRef(event.previousRef) || !event.previousRef.startsWith(`${event.collection}/`) || event.previousRef === event.ref) return invalid12();
9572
+ if (!keys4(event, "collection,kind,previousRef,ref") || !validRecordRef(event.previousRef) || !event.previousRef.startsWith(`${event.collection}/`) || event.previousRef === event.ref) return invalid13();
9466
9573
  } else if (event.kind === "update") {
9467
- if (!keys4(event, "after,before,collection,field,kind,ref") || !fields4.includes(event.field) || created.has(event.ref)) return invalid12();
9574
+ if (!keys4(event, "after,before,collection,field,kind,ref") || !fields4.includes(event.field) || created.has(event.ref)) return invalid13();
9468
9575
  for (let value of [event.before, event.after]) {
9469
- if (object7(value), value.present === !1 ? !keys4(value, "present") : value.present !== !0 || !keys4(value, "present,value")) return invalid12();
9576
+ if (object7(value), value.present === !1 ? !keys4(value, "present") : value.present !== !0 || !keys4(value, "present,value")) return invalid13();
9470
9577
  value.present && json3(value.value);
9471
9578
  }
9472
- } else return invalid12();
9579
+ } else return invalid13();
9473
9580
  let order = [event.kind === "delete" ? 0 : 1, event.ref, event.kind === "update" ? 1 : 0, event.kind === "update" ? event.field : ""];
9474
9581
  if (previous) {
9475
9582
  let index = order.findIndex((value, i) => value !== previous[i]);
9476
- if (index === -1 || order[index] < previous[index]) return invalid12();
9583
+ if (index === -1 || order[index] < previous[index]) return invalid13();
9477
9584
  }
9478
9585
  previous = order, apply(book, event);
9479
9586
  }
9480
9587
  let refs = /* @__PURE__ */ new Set();
9481
9588
  for (let records of book.values()) for (let ref of records.keys()) {
9482
- if (refs.has(ref)) return invalid12();
9589
+ if (refs.has(ref)) return invalid13();
9483
9590
  refs.add(ref);
9484
9591
  }
9485
9592
  }
9486
- if (parent !== history.through) return invalid12();
9593
+ if (parent !== history.through) return invalid13();
9487
9594
  for (let [collection, records] of book) {
9488
9595
  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]]))]);
9489
- if (stable([...records].sort(([a], [b]) => a < b ? -1 : 1)) !== stable(expected)) return invalid12();
9596
+ if (stable([...records].sort(([a], [b]) => a < b ? -1 : 1)) !== stable(expected)) return invalid13();
9490
9597
  }
9491
9598
  return history;
9492
9599
  }
@@ -9513,33 +9620,33 @@ function readSnapshotHistory(history, input, operation2) {
9513
9620
  };
9514
9621
  }
9515
9622
 
9516
- var snapshotCollection = (catalogue, ref) => catalogue.filter((c) => ref.startsWith(`${c.name}/`)).sort((a, b) => b.name.length - a.name.length)[0], invalid13 = () => {
9623
+ var snapshotCollection = (catalogue, ref) => catalogue.filter((c) => ref.startsWith(`${c.name}/`)).sort((a, b) => b.name.length - a.name.length)[0], invalid14 = () => {
9517
9624
  throw new DataOperationError("unavailable", !0);
9518
- }, object8 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid13() : value;
9625
+ }, object8 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid14() : value;
9519
9626
  function stable2(value) {
9520
9627
  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);
9521
9628
  }
9522
9629
  function schemaText(value) {
9523
- if (typeof value == "string" && !dataText(value)) return invalid13();
9630
+ if (typeof value == "string" && !dataText(value)) return invalid14();
9524
9631
  if (value && typeof value == "object") for (let [key, entry] of Object.entries(value)) {
9525
- if (!dataText(key)) return invalid13();
9632
+ if (!dataText(key)) return invalid14();
9526
9633
  schemaText(entry);
9527
9634
  }
9528
9635
  }
9529
9636
  function validateSnapshotEnvelope(input, repository, name4, bodies = [], timelines = []) {
9530
9637
  try {
9531
9638
  let row = object8(input), legacy = row.format === "data-snapshot.v1";
9532
- if (!["collections,format,name,repository,schemas,version", "collections,format,history,name,repository,schemas,version"].includes(Object.keys(row).sort().join(",")) || !legacy && row.format !== "data-snapshot.v2" || legacy && timelines.length > 0 || row.repository !== repository || row.name !== name4 || !dataVersion(row.version)) return invalid13();
9639
+ if (!["collections,format,name,repository,schemas,version", "collections,format,history,name,repository,schemas,version"].includes(Object.keys(row).sort().join(",")) || !legacy && row.format !== "data-snapshot.v2" || legacy && timelines.length > 0 || row.repository !== repository || row.name !== name4 || !dataVersion(row.version)) return invalid14();
9533
9640
  let schemas2 = object8(row.schemas), collections = object8(row.collections);
9534
9641
  schemaText(schemas2);
9535
9642
  let names = Object.keys(collections);
9536
- for (let subset of [bodies, timelines]) if (new Set(subset).size !== subset.length || subset.some((name5) => !names.includes(name5))) return invalid13();
9537
- if (!names.length || names.join("\0") !== [...names].sort().join("\0") || Object.keys(schemas2).join("\0") !== names.join("\0")) return invalid13();
9643
+ for (let subset of [bodies, timelines]) if (new Set(subset).size !== subset.length || subset.some((name5) => !names.includes(name5))) return invalid14();
9644
+ if (!names.length || names.join("\0") !== [...names].sort().join("\0") || Object.keys(schemas2).join("\0") !== names.join("\0")) return invalid14();
9538
9645
  let catalogue = names.map((name5) => {
9539
9646
  let schema2 = object8(schemas2[name5]);
9540
- if (!validRecordRef(`${name5}/example`) || schema2.name !== name5 || typeof schema2.type != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(schema2.type) || schema2.description !== void 0 && !dataText(schema2.description) || Object.keys(schema2).some((key) => !["name", "type", "description", "display", "fields"].includes(key))) return invalid13();
9647
+ if (!validRecordRef(`${name5}/example`) || schema2.name !== name5 || typeof schema2.type != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(schema2.type) || schema2.description !== void 0 && !dataText(schema2.description) || Object.keys(schema2).some((key) => !["name", "type", "description", "display", "fields"].includes(key))) return invalid14();
9541
9648
  let definitions3 = fields2(schema2.fields, 0, !0);
9542
- if (stable2(definitions3.map(publicField)) !== stable2(schema2.fields)) return invalid13();
9649
+ if (stable2(definitions3.map(publicField)) !== stable2(schema2.fields)) return invalid14();
9543
9650
  let display = parseRecordDisplay2(schema2.display, definitions3);
9544
9651
  return { name: name5, schema: {
9545
9652
  type: schema2.type,
@@ -9550,23 +9657,23 @@ function validateSnapshotEnvelope(input, repository, name4, bodies = [], timelin
9550
9657
  }), types = /* @__PURE__ */ new Map();
9551
9658
  for (let collection of catalogue) {
9552
9659
  let records = collections[collection.name];
9553
- if (!Array.isArray(records)) return invalid13();
9660
+ if (!Array.isArray(records)) return invalid14();
9554
9661
  let previous = "";
9555
9662
  for (let record4 of records) {
9556
9663
  let value = object8(record4);
9557
- if (!validRecordRef(value.$ref) || snapshotCollection(catalogue, value.$ref)?.name !== collection.name || value.$ref <= previous || types.has(value.$ref) || typeof value.$version != "string" || !/^record-v1:[0-9a-f]{64}$/.test(value.$version)) return invalid13();
9664
+ 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 invalid14();
9558
9665
  types.set(value.$ref, collection.schema.type), previous = value.$ref;
9559
9666
  }
9560
9667
  }
9561
9668
  for (let collection of catalogue) for (let record4 of collections[collection.name]) {
9562
9669
  let { $ref: _ref, $version: _version, $body, $signals, $timeline, ...values } = record4;
9563
9670
  if (legacy) {
9564
- if (Object.hasOwn(record4, "$signals") || Object.hasOwn(record4, "$timeline")) return invalid13();
9671
+ if (Object.hasOwn(record4, "$signals") || Object.hasOwn(record4, "$timeline")) return invalid14();
9565
9672
  } else if (captureRecordSignals($signals), timelines.includes(collection.name)) {
9566
- if (!Array.isArray($timeline)) return invalid13();
9673
+ if (!Array.isArray($timeline)) return invalid14();
9567
9674
  $timeline.forEach((value) => captureTimeline(value));
9568
- } else if (Object.hasOwn(record4, "$timeline")) return invalid13();
9569
- if (Object.hasOwn(record4, "$body") && (!bodies.includes(collection.name) || typeof $body != "string")) return invalid13();
9675
+ } else if (Object.hasOwn(record4, "$timeline")) return invalid14();
9676
+ if (Object.hasOwn(record4, "$body") && (!bodies.includes(collection.name) || typeof $body != "string")) return invalid14();
9570
9677
  validateRecordFields(values, collection.schema.fields, (ref, targets2) => types.get(ref) ?? targets2[0], !0);
9571
9678
  }
9572
9679
  let normalized = legacy ? Object.fromEntries(Object.entries(collections).map(([collection, records]) => [
@@ -9585,7 +9692,7 @@ function validateSnapshotEnvelope(input, repository, name4, bodies = [], timelin
9585
9692
  ...Object.hasOwn(row, "history") ? { history: validateSnapshotHistory(row.history, normalized, row.version) } : {}
9586
9693
  };
9587
9694
  } catch {
9588
- return invalid13();
9695
+ return invalid14();
9589
9696
  }
9590
9697
  }
9591
9698
 
@@ -9723,14 +9830,14 @@ function* evaluateRecordsQuery(query, catalogue, context, maxRecords, cloneValue
9723
9830
 
9724
9831
  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";
9725
9832
 
9726
- var invalid14 = () => {
9833
+ var invalid15 = () => {
9727
9834
  throw new DataOperationError("unavailable", !0);
9728
- }, object9 = (v) => v && typeof v == "object" && !Array.isArray(v) ? v : invalid14(), uuid5 = (v) => typeof v == "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v), time3 = (v) => typeof v == "string" && Number.isFinite(Date.parse(v)), recordVersion = (v) => typeof v == "string" && /^record-v1:[0-9a-f]{64}$/.test(v), keys5 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
9835
+ }, object9 = (v) => v && typeof v == "object" && !Array.isArray(v) ? v : invalid15(), uuid5 = (v) => typeof v == "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v), time3 = (v) => typeof v == "string" && Number.isFinite(Date.parse(v)), recordVersion = (v) => typeof v == "string" && /^record-v1:[0-9a-f]{64}$/.test(v), keys5 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
9729
9836
  function validateAcquisition(input, repository, name4) {
9730
9837
  let row = object9(input), snapshot = object9(row.snapshot);
9731
- if (Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== snapshotAcquisitionFormat || !keys5(snapshot, ["id", "name", "refreshedAt", "repository", "version", "collections", "bodies", "timelines"]) || !uuid5(snapshot.id) || snapshot.repository !== repository || snapshot.name !== name4 || !dataVersion(snapshot.version) || !time3(snapshot.refreshedAt) || !Array.isArray(snapshot.collections) || !snapshot.collections.length || !snapshot.collections.every((c) => typeof c == "string" && validRecordRef(`${c}/example`)) || snapshot.collections.join("\0") !== [...new Set(snapshot.collections)].sort().join("\0") || !Array.isArray(row.changes)) return invalid14();
9838
+ if (Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== snapshotAcquisitionFormat || !keys5(snapshot, ["id", "name", "refreshedAt", "repository", "version", "collections", "bodies", "timelines"]) || !uuid5(snapshot.id) || snapshot.repository !== repository || snapshot.name !== name4 || !dataVersion(snapshot.version) || !time3(snapshot.refreshedAt) || !Array.isArray(snapshot.collections) || !snapshot.collections.length || !snapshot.collections.every((c) => typeof c == "string" && validRecordRef(`${c}/example`)) || snapshot.collections.join("\0") !== [...new Set(snapshot.collections)].sort().join("\0") || !Array.isArray(row.changes)) return invalid15();
9732
9839
  let bodies = snapshot.bodies === void 0 ? [] : snapshot.bodies, timelines = snapshot.timelines === void 0 ? [] : snapshot.timelines;
9733
- for (let subset of [bodies, timelines]) if (!Array.isArray(subset) || subset.some((c) => !snapshot.collections.includes(c)) || subset.join("\0") !== [...new Set(subset)].sort().join("\0")) return invalid14();
9840
+ 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 invalid15();
9734
9841
  return {
9735
9842
  snapshot: { ...snapshot, bodies, timelines },
9736
9843
  changes: validateSnapshotChanges(row.changes, snapshot.collections)
@@ -9738,47 +9845,47 @@ function validateAcquisition(input, repository, name4) {
9738
9845
  }
9739
9846
  function validateSnapshotChanges(input, collections) {
9740
9847
  try {
9741
- if (!Array.isArray(input)) return invalid14();
9848
+ if (!Array.isArray(input)) return invalid15();
9742
9849
  let ids = /* @__PURE__ */ new Set(), unpublished = !1;
9743
9850
  for (let value of input) {
9744
9851
  let c = object9(value), effect = object9(c.effect);
9745
- if (!keys5(c, ["id", "version", "ref", "recordVersion", "effect", "updatedAt", "person", "source", "publication"]) || !uuid5(c.id) || ids.has(c.id) || !dataVersion(c.version) || !validRecordRef(c.ref) || !collections.some((name4) => c.ref.startsWith(`${name4}/`)) || !recordVersion(c.recordVersion) || !time3(c.updatedAt)) return invalid14();
9852
+ if (!keys5(c, ["id", "version", "ref", "recordVersion", "effect", "updatedAt", "person", "source", "publication"]) || !uuid5(c.id) || ids.has(c.id) || !dataVersion(c.version) || !validRecordRef(c.ref) || !collections.some((name4) => c.ref.startsWith(`${name4}/`)) || !recordVersion(c.recordVersion) || !time3(c.updatedAt)) return invalid15();
9746
9853
  if (ids.add(c.id), c.person !== void 0) {
9747
9854
  let person = object9(c.person);
9748
- if (!keys5(person, ["id", "name", "email"]) || !uuid5(person.id) || person.name !== void 0 && !dataText(person.name) || person.email !== void 0 && !dataText(person.email)) return invalid14();
9855
+ if (!keys5(person, ["id", "name", "email"]) || !uuid5(person.id) || person.name !== void 0 && !dataText(person.name) || person.email !== void 0 && !dataText(person.email)) return invalid15();
9749
9856
  }
9750
9857
  if (c.source !== void 0) {
9751
9858
  let source2 = object9(c.source);
9752
- if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid14();
9859
+ if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid15();
9753
9860
  }
9754
9861
  if (c.publication !== void 0) {
9755
9862
  let publication = object9(c.publication);
9756
- if (unpublished || Object.keys(publication).sort().join(",") !== "commit,time" || typeof publication.commit != "string" || !/^[0-9a-f]{40}$/.test(publication.commit) || !time3(publication.time)) return invalid14();
9863
+ if (unpublished || Object.keys(publication).sort().join(",") !== "commit,time" || typeof publication.commit != "string" || !/^[0-9a-f]{40}$/.test(publication.commit) || !time3(publication.time)) return invalid15();
9757
9864
  } else unpublished = !0;
9758
9865
  if (effect.kind === "set") {
9759
- if (Object.keys(effect).sort().join(",") !== "field,kind,value" || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field)) return invalid14();
9866
+ if (Object.keys(effect).sort().join(",") !== "field,kind,value" || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field)) return invalid15();
9760
9867
  } else if (effect.kind === "link" || effect.kind === "unlink") {
9761
- if (!keys5(effect, ["kind", "field", "refs", ...effect.kind === "link" ? ["remove"] : []]) || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field) || !Array.isArray(effect.refs) || !effect.refs.length || effect.refs.length > 1e5 || effect.refs.some((ref) => !validRecordRef(ref)) || new Set(effect.refs).size !== effect.refs.length || effect.remove !== void 0 && (!Array.isArray(effect.remove) || !effect.remove.length || effect.remove.length > 1e5 || effect.remove.some((ref) => !validRecordRef(ref)) || new Set(effect.remove).size !== effect.remove.length)) return invalid14();
9868
+ if (!keys5(effect, ["kind", "field", "refs", ...effect.kind === "link" ? ["remove"] : []]) || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field) || !Array.isArray(effect.refs) || !effect.refs.length || effect.refs.length > 1e5 || effect.refs.some((ref) => !validRecordRef(ref)) || new Set(effect.refs).size !== effect.refs.length || effect.remove !== void 0 && (!Array.isArray(effect.remove) || !effect.remove.length || effect.remove.length > 1e5 || effect.remove.some((ref) => !validRecordRef(ref)) || new Set(effect.remove).size !== effect.remove.length)) return invalid15();
9762
9869
  } else if (effect.kind === "signal") {
9763
- if (Object.keys(effect).sort().join(",") !== "key,kind,value") return invalid14();
9870
+ if (Object.keys(effect).sort().join(",") !== "key,kind,value") return invalid15();
9764
9871
  let value2 = object9(effect.value);
9765
- if (!keys5(value2, ["label", "status", "reason", "related", "asOf", "number"])) return invalid14();
9872
+ if (!keys5(value2, ["label", "status", "reason", "related", "asOf", "number"])) return invalid15();
9766
9873
  let { number, ...assessment } = value2;
9767
9874
  captureSignal({ ...assessment, key: effect.key }), (c.publication || Object.hasOwn(value2, "number")) && captureRecordSignal({ ...value2, key: effect.key });
9768
9875
  } else if (effect.kind === "timeline") {
9769
- if (Object.keys(effect).sort().join(",") !== "entry,kind") return invalid14();
9876
+ if (Object.keys(effect).sort().join(",") !== "entry,kind") return invalid15();
9770
9877
  captureTimeline(effect.entry);
9771
9878
  } else if (effect.kind === "create" || effect.kind === "delete") {
9772
- if (!keys5(effect, ["fields", "kind", "signals", "timeline"])) return invalid14();
9879
+ if (!keys5(effect, ["fields", "kind", "signals", "timeline"])) return invalid15();
9773
9880
  if (object9(effect.fields), Object.hasOwn(effect, "signals") && captureRecordSignals(effect.signals), Object.hasOwn(effect, "timeline")) {
9774
- if (!Array.isArray(effect.timeline)) return invalid14();
9881
+ if (!Array.isArray(effect.timeline)) return invalid15();
9775
9882
  effect.timeline.forEach((value2) => captureTimeline(value2));
9776
9883
  }
9777
- } else return invalid14();
9884
+ } else return invalid15();
9778
9885
  }
9779
9886
  return input;
9780
9887
  } catch {
9781
- return invalid14();
9888
+ return invalid15();
9782
9889
  }
9783
9890
  }
9784
9891
  function materializeSnapshot(envelope, changes, version) {
@@ -9787,13 +9894,13 @@ function materializeSnapshot(envelope, changes, version) {
9787
9894
  let rows = new Map(Object.values(envelope.collections).flat().map((r) => [r.$ref, structuredClone(r)]));
9788
9895
  for (let c of changes) {
9789
9896
  let schema2 = snapshotCollection(envelope.catalogue, c.ref);
9790
- if (!schema2) return invalid14();
9897
+ if (!schema2) return invalid15();
9791
9898
  let effect = c.effect, definitions3 = "field" in effect ? schema2.schema.fields.filter((f) => f.name === effect.field) : schema2.schema.fields;
9792
- if ("field" in effect && !definitions3.length) return invalid14();
9899
+ if ("field" in effect && !definitions3.length) return invalid15();
9793
9900
  let values;
9794
9901
  if (effect.kind === "link" || effect.kind === "unlink") {
9795
9902
  let field = definitions3[0];
9796
- if (field.kind !== "link" || !field.many && effect.kind === "link" && effect.refs.length !== 1) return invalid14();
9903
+ if (field.kind !== "link" || !field.many && effect.kind === "link" && effect.refs.length !== 1) return invalid15();
9797
9904
  let targets2 = [...effect.refs, ...effect.kind === "link" ? effect.remove ?? [] : []];
9798
9905
  for (let ref of targets2) validateRecordFields({ [effect.field]: field.many ? [ref] : ref }, definitions3, (_ref, allowed) => allowed[0], !0);
9799
9906
  values = { [effect.field]: field.many ? effect.refs : effect.refs[0] };
@@ -9806,25 +9913,25 @@ function materializeSnapshot(envelope, changes, version) {
9806
9913
  ), !c.publication) continue;
9807
9914
  let prior = rows.get(c.ref);
9808
9915
  if (effect.kind === "set") {
9809
- if (!prior) return invalid14();
9916
+ if (!prior) return invalid15();
9810
9917
  rows.set(c.ref, { ...prior, [effect.field]: effect.value, $version: c.recordVersion });
9811
9918
  } else if (effect.kind === "link" || effect.kind === "unlink") {
9812
- if (!prior) return invalid14();
9919
+ if (!prior) return invalid15();
9813
9920
  let field = definitions3[0], current2 = prior[effect.field], value = field.many ? effect.kind === "link" ? [.../* @__PURE__ */ new Set([...Array.isArray(current2) ? current2 : [], ...effect.refs])].filter((ref) => !effect.remove?.includes(String(ref))) : (Array.isArray(current2) ? current2 : []).filter((ref) => !effect.refs.includes(String(ref))) : effect.kind === "link" ? effect.remove?.includes(effect.refs[0]) ? null : effect.refs[0] : effect.refs.includes(String(current2)) ? null : current2;
9814
9921
  rows.set(c.ref, { ...prior, [effect.field]: value, $version: c.recordVersion });
9815
9922
  } else if (effect.kind === "signal") {
9816
- if (!prior || !effect.value.number) return invalid14();
9923
+ if (!prior || !effect.value.number) return invalid15();
9817
9924
  let signal = captureRecordSignal({ ...effect.value, key: effect.key }), signals = captureRecordSignals(prior.$signals), index = signals.findIndex((row) => row.key === effect.key);
9818
9925
  index < 0 ? signals.push(signal) : signals[index] = signal, rows.set(c.ref, { ...prior, $signals: captureRecordSignals(signals), $version: c.recordVersion });
9819
9926
  } else if (effect.kind === "timeline") {
9820
- if (!prior) return invalid14();
9927
+ if (!prior) return invalid15();
9821
9928
  rows.set(c.ref, {
9822
9929
  ...prior,
9823
9930
  $version: c.recordVersion,
9824
9931
  ...envelope.timelineCollections.includes(schema2.name) ? { $timeline: [...prior.$timeline, effect.entry] } : {}
9825
9932
  });
9826
9933
  } else if (effect.kind === "create") {
9827
- if (prior) return invalid14();
9934
+ if (prior) return invalid15();
9828
9935
  rows.set(c.ref, {
9829
9936
  ...effect.fields,
9830
9937
  $ref: c.ref,
@@ -9833,7 +9940,7 @@ function materializeSnapshot(envelope, changes, version) {
9833
9940
  ...envelope.timelineCollections.includes(schema2.name) ? { $timeline: effect.timeline ?? [] } : {}
9834
9941
  });
9835
9942
  } else {
9836
- if (!prior) return invalid14();
9943
+ if (!prior) return invalid15();
9837
9944
  rows.delete(c.ref);
9838
9945
  }
9839
9946
  }
@@ -9846,7 +9953,7 @@ function materializeSnapshot(envelope, changes, version) {
9846
9953
  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)]))
9847
9954
  }, envelope.repository, envelope.name, envelope.bodyCollections, envelope.timelineCollections), ...envelope.history ? { history: envelope.history } : {} };
9848
9955
  } catch {
9849
- return invalid14();
9956
+ return invalid15();
9850
9957
  }
9851
9958
  }
9852
9959
 
@@ -9902,23 +10009,23 @@ function applySnapshotMutation(envelope, prior, mutation, installation) {
9902
10009
  return { envelope, changes };
9903
10010
  }
9904
10011
 
9905
- var invalid15 = () => {
10012
+ var invalid16 = () => {
9906
10013
  throw new DataOperationError("unavailable", !0, void 0, "snapshot_cache");
9907
10014
  };
9908
10015
  function targets(value, definition, found) {
9909
10016
  if (value != null) {
9910
10017
  if (definition.many) {
9911
- if (!Array.isArray(value)) return invalid15();
10018
+ if (!Array.isArray(value)) return invalid16();
9912
10019
  for (let item of value) targets(item, { ...definition, many: !1 }, found);
9913
10020
  } else if (definition.kind === "link") {
9914
10021
  let link = parseRecordLink(value);
9915
- if (!link) return invalid15();
10022
+ if (!link) return invalid16();
9916
10023
  found.add(link.ref);
9917
10024
  } else if (definition.kind === "object") {
9918
- if (typeof value != "object" || Array.isArray(value)) return invalid15();
10025
+ if (typeof value != "object" || Array.isArray(value)) return invalid16();
9919
10026
  for (let field of definition.fields) targets(value[field.name], field, found);
9920
10027
  } else if (definition.kind === "map") {
9921
- if (typeof value != "object" || Array.isArray(value)) return invalid15();
10028
+ if (typeof value != "object" || Array.isArray(value)) return invalid16();
9922
10029
  for (let item of Object.values(value)) targets(item, definition.value, found);
9923
10030
  }
9924
10031
  }
@@ -10350,8 +10457,8 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
10350
10457
  }, Math.min(2147483647, Math.max(0, authority2.expiresAt - Date.now())));
10351
10458
  }, later = () => {
10352
10459
  retry = setTimeout(open, delay), delay = Math.min(3e4, delay * 2);
10353
- }, reconnect = (connection) => {
10354
- session !== owned || !connection || socket !== connection || (socket = void 0, connection.close(), later());
10460
+ }, reconnect = (connection2) => {
10461
+ session !== owned || !connection2 || socket !== connection2 || (socket = void 0, connection2.close(), later());
10355
10462
  }, refresh2 = () => {
10356
10463
  dirty = !0, !running && (running = !0, (async () => {
10357
10464
  try {
@@ -10380,15 +10487,15 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
10380
10487
  }
10381
10488
  armExpiry();
10382
10489
  try {
10383
- let connection = connect(url.replace(/^http/, "ws") + "/updates", [
10490
+ let connection2 = connect(url.replace(/^http/, "ws") + "/updates", [
10384
10491
  snapshotUpdatesProtocol,
10385
10492
  snapshotUpdatesCredentialPrefix + authority2.headers.authorization.slice(7)
10386
10493
  ]);
10387
- socket = connection, connection.addEventListener("open", () => {
10388
- socket === connection && session === owned && refresh2();
10389
- }), connection.addEventListener("message", (event) => {
10390
- socket === connection && session === owned && event.data === snapshotUpdateHint && refresh2();
10391
- }), connection.addEventListener("close", () => reconnect(connection)), connection.addEventListener("error", () => reconnect(connection));
10494
+ socket = connection2, connection2.addEventListener("open", () => {
10495
+ socket === connection2 && session === owned && refresh2();
10496
+ }), connection2.addEventListener("message", (event) => {
10497
+ socket === connection2 && session === owned && event.data === snapshotUpdateHint && refresh2();
10498
+ }), connection2.addEventListener("close", () => reconnect(connection2)), connection2.addEventListener("error", () => reconnect(connection2));
10392
10499
  } catch {
10393
10500
  session === owned && later();
10394
10501
  }
@@ -10487,19 +10594,19 @@ function captureSelection(input) {
10487
10594
  }
10488
10595
  }
10489
10596
 
10490
- var invalid16 = () => {
10597
+ var invalid17 = () => {
10491
10598
  throw new DataOperationError("invalid_query");
10492
10599
  };
10493
10600
  function captureSnapshotAll(query, options) {
10494
10601
  let properties = dataProperties(options);
10495
- return Object.keys(properties).some((key) => !["maxRecords", "body", "timeline"].includes(key)) || properties.body && properties.body.value !== !0 || properties.timeline && properties.timeline.value !== !0 ? invalid16() : { ...captureRecordsAll(query, { maxRecords: properties.maxRecords?.value }), body: properties.body?.value === !0, timeline: properties.timeline?.value === !0 };
10602
+ return Object.keys(properties).some((key) => !["maxRecords", "body", "timeline"].includes(key)) || properties.body && properties.body.value !== !0 || properties.timeline && properties.timeline.value !== !0 ? invalid17() : { ...captureRecordsAll(query, { maxRecords: properties.maxRecords?.value }), body: properties.body?.value === !0, timeline: properties.timeline?.value === !0 };
10496
10603
  }
10497
10604
  var safeName = (value) => typeof value == "string" && /^[a-z0-9][a-z0-9._-]{0,127}$/.test(value) && !value.includes("..");
10498
10605
  function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore, connect = (url, protocols) => new WebSocket(url, protocols)) {
10499
10606
  let pending = /* @__PURE__ */ new WeakMap(), maintenance = /* @__PURE__ */ new WeakMap();
10500
10607
  return async function(input) {
10501
10608
  let properties = dataProperties(input), repository = properties.repository?.value, snapshot = properties.snapshot?.value;
10502
- if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid16();
10609
+ if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid17();
10503
10610
  let authority2 = await resolve(), invalidated = !1, stopLive, assertCurrent = () => {
10504
10611
  if (invalidated || authority2.signal.aborted || !authority2.isCurrent() || !authority2.refresh && authority2.expiresAt <= Date.now())
10505
10612
  throw invalidated = !0, stopLive?.(), new DataOperationError("context_unavailable");
@@ -10671,7 +10778,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
10671
10778
  let store;
10672
10779
  try {
10673
10780
  let selections = planIndexQuery(captured, pinned.catalogue, { allowUnknownTerminalRefs: !0 }), checkTimeline = (collection, selection2) => {
10674
- if ((timeline || selection2.timeline) && !pinned.timelineCollections.includes(collection)) return invalid16();
10781
+ if ((timeline || selection2.timeline) && !pinned.timelineCollections.includes(collection)) return invalid17();
10675
10782
  for (let link of selection2.links) for (let [name4, nested] of link.targets) checkTimeline(name4, nested);
10676
10783
  };
10677
10784
  for (let { name: name4, selection: selection2 } of selections) checkTimeline(name4, selection2);
@@ -10756,7 +10863,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
10756
10863
  return snapshotCollection(installation.catalogue, captured) ? writes.then(() => {
10757
10864
  let pinned = installation;
10758
10865
  return localRead(async (store) => {
10759
- if (timeline && !pinned.timelineCollections.includes(snapshotCollection(pinned.catalogue, captured).name)) return invalid16();
10866
+ if (timeline && !pinned.timelineCollections.includes(snapshotCollection(pinned.catalogue, captured).name)) return invalid17();
10760
10867
  let record4 = await store.read(pinned, captured);
10761
10868
  if (!record4) return record4;
10762
10869
  let { $body, $timeline, ...structured } = record4;
@@ -10893,7 +11000,7 @@ var genericData = {
10893
11000
  }
10894
11001
  }, data = genericData;
10895
11002
 
10896
- var MAX_BYTES = 16 * 1024 * 1024, PART_BYTES = 8 * 1024 * 1024, METADATA_BYTES = 4096, RESULT_BYTES = 16 * 1024, CONTROL_RESULT_BYTES = 128 * 1024, TIMEOUT_MS = 3e4, MAX_ACTIVE = 4, ATTEMPTS = 2, active = 0, waiters = [], invalid17 = () => new FileOperationError("invalid_input", 400), unavailable4 = () => new FileOperationError("unavailable", 503, !0), failures = {
11003
+ 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 = [], invalid18 = () => new FileOperationError("invalid_input", 400), unavailable4 = () => new FileOperationError("unavailable", 503, !0), failures = {
10897
11004
  400: ["invalid_input", "unsupported_context"],
10898
11005
  401: ["unauthenticated"],
10899
11006
  403: ["access_denied"],
@@ -11049,7 +11156,7 @@ async function send(suffix, init2, descriptor, initial, parent) {
11049
11156
  throw unavailable4();
11050
11157
  }
11051
11158
  function idPath(id5) {
11052
- if (typeof id5 != "string" || !FILE_ID_PATTERN.test(id5)) throw invalid17();
11159
+ if (typeof id5 != "string" || !FILE_ID_PATTERN.test(id5)) throw invalid18();
11053
11160
  return `/${id5}`;
11054
11161
  }
11055
11162
  async function multipartCreate(input, metadata, exchange, release, upload, expectedSha256) {
@@ -11092,18 +11199,18 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
11092
11199
  if (!chunk || offset === chunk.byteLength) {
11093
11200
  chunk = void 0, offset = 0;
11094
11201
  let value2 = await next();
11095
- if (value2.done || !(value2.value instanceof Uint8Array) || (chunk = value2.value, chunk.byteLength > metadata.size - sent - filled)) throw invalid17();
11202
+ if (value2.done || !(value2.value instanceof Uint8Array) || (chunk = value2.value, chunk.byteLength > metadata.size - sent - filled)) throw invalid18();
11096
11203
  }
11097
11204
  let take = Math.min(length - filled, chunk.byteLength - offset);
11098
11205
  part.set(chunk.subarray(offset, offset + take), filled), filled += take, offset += take, offset === chunk.byteLength && (chunk = void 0, offset = 0);
11099
11206
  }
11100
11207
  }
11101
- if (part.byteLength !== length) throw invalid17();
11208
+ if (part.byteLength !== length) throw invalid18();
11102
11209
  if (reader && sent + length === metadata.size)
11103
11210
  for (lastProgress = Date.now(); ; ) {
11104
11211
  let value2 = await next();
11105
11212
  if (value2.done) break;
11106
- if (!(value2.value instanceof Uint8Array) || value2.value.byteLength) throw invalid17();
11213
+ if (!(value2.value instanceof Uint8Array) || value2.value.byteLength) throw invalid18();
11107
11214
  }
11108
11215
  let value = await request3((signal) => exchange(`${route}/part`, {
11109
11216
  method: "POST",
@@ -11117,7 +11224,7 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
11117
11224
  }
11118
11225
  if (upload) for (let name4 of Object.keys(upload.file.enrichments)) {
11119
11226
  let bytes = await request3(() => upload.enrichment(name4));
11120
- if (bytes.byteLength !== upload.file.enrichments[name4].size || bytes.byteLength > MAX_BYTES) throw invalid17();
11227
+ if (bytes.byteLength !== upload.file.enrichments[name4].size || bytes.byteLength > MAX_BYTES) throw invalid18();
11121
11228
  await request3((signal) => exchange(`${route}/enrichments/${encodeURIComponent(name4)}`, {
11122
11229
  method: "POST",
11123
11230
  headers: { "content-type": "application/octet-stream", "x-os-transfer": ticket },
@@ -11159,7 +11266,7 @@ async function operation(work, initial, parent) {
11159
11266
  function contentPath(id5, name4) {
11160
11267
  let path = idPath(id5);
11161
11268
  if (name4 === void 0) return `${path}/content`;
11162
- if (!safeEnrichmentName(name4)) throw invalid17();
11269
+ if (!safeEnrichmentName(name4)) throw invalid18();
11163
11270
  return `${path}/enrichments/${encodeURIComponent(name4)}/content`;
11164
11271
  }
11165
11272
  async function read(id5, names) {
@@ -11168,12 +11275,12 @@ async function read(id5, names) {
11168
11275
  let path = contentPath(id5, names);
11169
11276
  return operation((context2, signal) => send(path, { method: "GET" }, !1, context2, signal), context);
11170
11277
  }
11171
- if (!Array.isArray(names)) throw invalid17();
11278
+ if (!Array.isArray(names)) throw invalid18();
11172
11279
  let distinct = [], seen = /* @__PURE__ */ new Set();
11173
11280
  for (let name4 of names) {
11174
- if (typeof name4 != "string" || !safeEnrichmentName(name4)) throw invalid17();
11281
+ if (typeof name4 != "string" || !safeEnrichmentName(name4)) throw invalid18();
11175
11282
  if (!seen.has(name4)) {
11176
- if (seen.size === 16) throw invalid17();
11283
+ if (seen.size === 16) throw invalid18();
11177
11284
  seen.add(name4), distinct.push(name4);
11178
11285
  }
11179
11286
  }
@@ -11213,9 +11320,9 @@ var files = {
11213
11320
  async create(input, options) {
11214
11321
  let context = await resolveFilesContext();
11215
11322
  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")))
11216
- throw invalid17();
11323
+ throw invalid18();
11217
11324
  let blob = input.file instanceof Blob, array3 = input.file instanceof Uint8Array, stream = input.file instanceof ReadableStream;
11218
- if (!blob && !array3 && !stream) throw invalid17();
11325
+ if (!blob && !array3 && !stream) throw invalid18();
11219
11326
  let intrinsic = blob ? input.file.size : array3 ? input.file.byteLength : void 0;
11220
11327
  if (intrinsic !== void 0 && input.size !== void 0 && input.size !== intrinsic)
11221
11328
  throw !Number.isSafeInteger(input.size) || input.size < 0 ? new FileOperationError("invalid_input", 400, !1, { reason: "invalid_size" }) : new FileOperationError(
@@ -11236,7 +11343,7 @@ var files = {
11236
11343
  }, FILE_ORIGINAL_MAX_BYTES);
11237
11344
  if (!context.local && !context.localFiles && metadata.storage === "local") throw new FileOperationError("unsupported_context", 400);
11238
11345
  let header = encodeURIComponent(JSON.stringify(metadata));
11239
- if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid17();
11346
+ if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid18();
11240
11347
  let release = await acquireSlot(context.signal);
11241
11348
  if (context.localFiles && !routineTransport() && metadata.size > MAX_BYTES)
11242
11349
  try {
@@ -11287,7 +11394,7 @@ var files = {
11287
11394
  },
11288
11395
  async enrich(input) {
11289
11396
  let context = await resolveFilesContext();
11290
- if (!input || typeof input != "object" || Array.isArray(input) || Object.keys(input).some((key) => !["file", "name", "content", "mediaType", "replace"].includes(key)) || typeof input.content != "string" && !(input.content instanceof Uint8Array)) throw invalid17();
11397
+ 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 invalid18();
11291
11398
  let path = `${idPath(input.file)}/enrichments`;
11292
11399
  if (typeof input.content == "string" ? input.content.length > MAX_BYTES : input.content.byteLength > MAX_BYTES)
11293
11400
  throw new FileOperationError("request_too_large", 413);
@@ -11304,7 +11411,7 @@ var files = {
11304
11411
  ...input.mediaType === void 0 ? {} : { mediaType: input.mediaType },
11305
11412
  ...input.replace === void 0 ? {} : { replace: input.replace }
11306
11413
  }, MAX_BYTES), header = encodeURIComponent(JSON.stringify(metadata));
11307
- if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid17();
11414
+ if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid18();
11308
11415
  let result2 = await send(path, { method: "POST", headers: {
11309
11416
  "content-type": "application/octet-stream",
11310
11417
  "x-os-enrichment": header
@@ -11651,10 +11758,10 @@ async function reportLocalRoutineEffect(value) {
11651
11758
  }
11652
11759
 
11653
11760
  var local;
11654
- async function localLease(identity3) {
11761
+ async function localLease(identity4) {
11655
11762
  let current2 = local;
11656
- if (!current2 || !current2.declared.includes(identity3)) throw new Error("Connection unavailable");
11657
- let lease = current2.leases.find((value) => `${value.provider}/${value.name}` === identity3);
11763
+ if (!current2 || !current2.declared.includes(identity4)) throw new Error("Connection unavailable");
11764
+ let lease = current2.leases.find((value) => `${value.provider}/${value.name}` === identity4);
11658
11765
  if (lease)
11659
11766
  try {
11660
11767
  return parseConnectionLease(lease);
@@ -11664,25 +11771,25 @@ async function localLease(identity3) {
11664
11771
  lease = void 0;
11665
11772
  }
11666
11773
  if (!lease && current2.acquire) {
11667
- let acquiring = current2.acquiring.get(identity3);
11774
+ let acquiring = current2.acquiring.get(identity4);
11668
11775
  acquiring || (acquiring = (async () => {
11669
- let acquired = parseConnectionLease(await current2.acquire(identity3));
11670
- if (local !== current2 || acquired.runId !== current2.runId || `${acquired.provider}/${acquired.name}` !== identity3)
11776
+ let acquired = parseConnectionLease(await current2.acquire(identity4));
11777
+ if (local !== current2 || acquired.runId !== current2.runId || `${acquired.provider}/${acquired.name}` !== identity4)
11671
11778
  throw new Error("Connection unavailable");
11672
11779
  return current2.leases.push(acquired), acquired;
11673
- })(), current2.acquiring.set(identity3, acquiring), acquiring.finally(() => {
11674
- current2.acquiring.get(identity3) === acquiring && current2.acquiring.delete(identity3);
11780
+ })(), current2.acquiring.set(identity4, acquiring), acquiring.finally(() => {
11781
+ current2.acquiring.get(identity4) === acquiring && current2.acquiring.delete(identity4);
11675
11782
  }).catch(() => {
11676
11783
  })), lease = await acquiring;
11677
11784
  }
11678
- if (local !== current2 || !lease || lease.runId !== current2.runId || `${lease.provider}/${lease.name}` !== identity3)
11785
+ if (local !== current2 || !lease || lease.runId !== current2.runId || `${lease.provider}/${lease.name}` !== identity4)
11679
11786
  throw new Error("Connection unavailable");
11680
11787
  return parseConnectionLease(lease);
11681
11788
  }
11682
- function connectionFailure(identity3) {
11789
+ function connectionFailure(identity4) {
11683
11790
  let workspace = typeof process > "u" ? void 0 : process.env.OS_ROUTINE_WORKSPACE;
11684
11791
  try {
11685
- return new ConnectionOperationError(identity3, workspace);
11792
+ return new ConnectionOperationError(identity4, workspace);
11686
11793
  } catch {
11687
11794
  return new Error("Connection unavailable");
11688
11795
  }
@@ -11693,8 +11800,8 @@ var airtable = /* @__PURE__ */ createConnections(async (name4, operation2, input
11693
11800
  function runtimeConnections() {
11694
11801
  return {
11695
11802
  ...airtable,
11696
- async get(identity3) {
11697
- throw connectionFailure(identity3);
11803
+ async get(identity4) {
11804
+ throw connectionFailure(identity4);
11698
11805
  }
11699
11806
  };
11700
11807
  }
@@ -11842,7 +11949,7 @@ var source = {
11842
11949
  merge(existing, incoming) {
11843
11950
  let merged = existing.map((location) => ({ ...location }));
11844
11951
  for (let location of incoming) {
11845
- let identity3 = locationIdentity(location), index = identity3 === void 0 ? -1 : merged.findIndex((value) => locationIdentity(value) === identity3);
11952
+ let identity4 = locationIdentity(location), index = identity4 === void 0 ? -1 : merged.findIndex((value) => locationIdentity(value) === identity4);
11846
11953
  index < 0 ? merged.push({ ...location }) : merged[index] = { ...location };
11847
11954
  }
11848
11955
  return merged;
@@ -11915,15 +12022,15 @@ function subscribeInbox(resolve, authorize, onDirty, onState, rt = runtime, sign
11915
12022
  if (setup.expiresAt <= rt.now()) throw new Error();
11916
12023
  let url = new URL(setup.url);
11917
12024
  url.searchParams.set("apikey", setup.key), url.searchParams.set("vsn", "1.0.0");
11918
- let connection = rt.connect(url.href);
11919
- socket = connection;
11920
- let valid = () => active2 && current2() && started === generation && socket === connection, topic = `realtime:${setup.topic}`, join = String(++sequence), joined = !1, send3 = (event, payload, ref = String(++sequence), destination = topic) => connection.send(JSON.stringify({ topic: destination, event, payload, ref }));
11921
- deadline = rt.later(reconnect, 15e3), connection.addEventListener("open", () => {
12025
+ let connection2 = rt.connect(url.href);
12026
+ socket = connection2;
12027
+ let valid = () => active2 && current2() && started === generation && socket === connection2, topic = `realtime:${setup.topic}`, join = String(++sequence), joined = !1, send3 = (event, payload, ref = String(++sequence), destination = topic) => connection2.send(JSON.stringify({ topic: destination, event, payload, ref }));
12028
+ deadline = rt.later(reconnect, 15e3), connection2.addEventListener("open", () => {
11922
12029
  valid() && send3("phx_join", {
11923
12030
  config: { private: !0, broadcast: { ack: !1, self: !1 }, presence: { enabled: !1 }, postgres_changes: [] },
11924
12031
  access_token: setup.token
11925
12032
  }, join);
11926
- }), connection.addEventListener("message", (event) => {
12033
+ }), connection2.addEventListener("message", (event) => {
11927
12034
  if (!valid() || typeof event.data != "string" || event.data.length > 8192) return;
11928
12035
  let value;
11929
12036
  try {
@@ -11953,9 +12060,9 @@ function subscribeInbox(resolve, authorize, onDirty, onState, rt = runtime, sign
11953
12060
  }
11954
12061
  else (value.event === "phx_error" || value.event === "phx_close" || value.event === "system" && value.payload?.status === "error") && reconnect();
11955
12062
  }
11956
- }), connection.addEventListener("close", () => {
12063
+ }), connection2.addEventListener("close", () => {
11957
12064
  valid() && reconnect();
11958
- }), connection.addEventListener("error", () => {
12065
+ }), connection2.addEventListener("error", () => {
11959
12066
  valid() && reconnect();
11960
12067
  });
11961
12068
  } catch (error) {
@@ -11989,12 +12096,17 @@ function subscribeInbox(resolve, authorize, onDirty, onState, rt = runtime, sign
11989
12096
  return signal?.aborted ? revoked() : (signal?.addEventListener("abort", revoked, { once: !0 }), initialize()), stop;
11990
12097
  }
11991
12098
 
11992
- async function limitedBody(request3, limit, timeoutMs) {
12099
+ async function limitedBody(request3, limit, timeoutMs, signal) {
11993
12100
  if (!request3.body) return new Uint8Array();
11994
- let reader = request3.body.getReader(), expired = !1, timer = timeoutMs === void 0 ? void 0 : setTimeout(() => {
12101
+ let reader = request3.body.getReader(), expired = !1, abort = () => {
12102
+ expired = !0, reader.cancel(signal?.reason).catch(() => {
12103
+ });
12104
+ }, timer = timeoutMs === void 0 ? void 0 : setTimeout(() => {
11995
12105
  expired = !0, reader.cancel().catch(() => {
11996
12106
  });
11997
- }, timeoutMs), chunks = [], length = 0;
12107
+ }, timeoutMs);
12108
+ signal?.addEventListener("abort", abort, { once: !0 }), signal?.aborted && abort();
12109
+ let chunks = [], length = 0;
11998
12110
  try {
11999
12111
  for (; ; ) {
12000
12112
  let { done, value } = await reader.read();
@@ -12011,7 +12123,7 @@ async function limitedBody(request3, limit, timeoutMs) {
12011
12123
  contents.set(chunk, offset), offset += chunk.byteLength;
12012
12124
  return contents;
12013
12125
  } finally {
12014
- timer !== void 0 && clearTimeout(timer);
12126
+ timer !== void 0 && clearTimeout(timer), signal?.removeEventListener("abort", abort);
12015
12127
  }
12016
12128
  }
12017
12129
 
@@ -12215,8 +12327,12 @@ async function send2(operation2, input, resolved, admitted) {
12215
12327
  }
12216
12328
  if (operation2 === "current" && parsed.workspace.slug !== context.workspace) throw unavailable5();
12217
12329
  if ("itemId" in envelope.input) {
12218
- let item = operation2 === "items.read" ? parsed : operation2 === "items.rename" || operation2 === "items.setLifecycle" || operation2 === "items.addRecipient" ? parsed.item : void 0;
12330
+ let item = operation2 === "items.read" ? parsed : operation2 === "items.rename" || operation2 === "items.setLifecycle" || operation2 === "items.addRecipient" || operation2 === "questions.assign" ? parsed.item : void 0;
12219
12331
  if (item && (item.id !== envelope.input.itemId || "revision" in envelope.input && item.revision !== envelope.input.revision) || operation2 === "items.addRecipient" && parsed.addedPersonId !== envelope.input.personId) throw unavailable5();
12332
+ if (operation2 === "questions.assign") {
12333
+ let result2 = parsed;
12334
+ if (assertInboxAssignmentMatches(result2, envelope.input), result2.item.workspaceId !== host?.context.workspaceId || result2.previousAssigneeId !== context.memberId) throw unavailable5();
12335
+ }
12220
12336
  }
12221
12337
  return parsed;
12222
12338
  } catch (error) {
@@ -12315,6 +12431,25 @@ var inbox = {
12315
12431
  addRecipient: async (input) => await send2("items.addRecipient", input)
12316
12432
  },
12317
12433
  questions: {
12434
+ listAssignmentCandidates: async (input) => await send2("questions.listAssignmentCandidates", input),
12435
+ async assign(input) {
12436
+ let supplied = parseInboxRequest({ operation: "questions.assign", input }).input, initial;
12437
+ try {
12438
+ initial = await resolveAppContext(!1, !0);
12439
+ } catch (error) {
12440
+ throw contextFailure(error);
12441
+ }
12442
+ if (initial.kind === "local") throw new InboxOperationError(403, "access_denied");
12443
+ let host;
12444
+ try {
12445
+ host = await resolveHostedInboxContext(initial, "member");
12446
+ } catch (error) {
12447
+ throw hostFailure(error, initial);
12448
+ }
12449
+ if (host.context.kind !== "inbox") throw new InboxOperationError(403, "access_denied");
12450
+ let assignee = assignmentTargetId(supplied.assignee, INBOX_UUID.test(supplied.assignee) ? [] : await send2("questions.listAssignmentCandidates", { itemId: supplied.itemId, revision: supplied.revision, questionId: supplied.questionId }, initial, host));
12451
+ return await send2("questions.assign", { ...supplied, assignee }, initial, host);
12452
+ },
12318
12453
  async list(input) {
12319
12454
  let supplied = parseInboxRequest({ contract: INBOX_QUESTION_CONTRACT, operation: "questions.list", input }).input;
12320
12455
  if (Object.hasOwn(supplied, "beforeNumber")) throw new InboxOperationError(400, "invalid_input");
@@ -13264,7 +13399,7 @@ function summary2(value, key, context, id5) {
13264
13399
  return fail8("execution_unavailable");
13265
13400
  }
13266
13401
  let run = value;
13267
- return (!only(run, "id,routine,placement,status,createdAt,startedAt,finishedAt,steps,result,failure,local") || typeof run.id != "string" || !uuid6.test(run.id) || id5 !== void 0 && run.id !== id5 || run.routine !== key || run.placement !== "local" || !["queued", "running", "succeeded", "failed", "legacy"].includes(run.status) || !timestamp(run.createdAt) || !optionalTimes(run) || !Array.isArray(run.steps) || run.steps.length > 64 || run.steps.some((step) => !only(step, "id,title,status,startedAt,finishedAt,progress,summary,detailAvailable") || typeof step.detailAvailable != "boolean" || !validStep(step)) || new Set(run.steps.map((step) => step.id)).size !== run.steps.length || Object.hasOwn(run, "result") && (run.status !== "succeeded" || !bounded2(run.result)) || run.failure !== void 0 && (run.status !== "failed" || !validFailure(run.failure, run.steps, run)) || run.local !== void 0 && !validLocalActivity(run.local)) && fail8("execution_unavailable"), run;
13402
+ return (!only(run, "id,routine,placement,status,createdAt,startedAt,finishedAt,steps,result,failure,local") || typeof run.id != "string" || !uuid6.test(run.id) || id5 !== void 0 && run.id !== id5 || run.routine !== key || run.placement !== "local" || !["queued", "running", "succeeded", "failed", "legacy"].includes(run.status) || !timestamp2(run.createdAt) || !optionalTimes(run) || !Array.isArray(run.steps) || run.steps.length > 64 || run.steps.some((step) => !only(step, "id,title,status,startedAt,finishedAt,progress,summary,detailAvailable") || typeof step.detailAvailable != "boolean" || !validStep(step)) || new Set(run.steps.map((step) => step.id)).size !== run.steps.length || Object.hasOwn(run, "result") && (run.status !== "succeeded" || !bounded2(run.result)) || run.failure !== void 0 && (run.status !== "failed" || !validFailure(run.failure, run.steps, run)) || run.local !== void 0 && !validLocalActivity(run.local)) && fail8("execution_unavailable"), run;
13268
13403
  }
13269
13404
  function validFailure(value, steps, local2) {
13270
13405
  try {
@@ -13273,16 +13408,16 @@ function validFailure(value, steps, local2) {
13273
13408
  }
13274
13409
  if (local2 && only(value, "message,code,detail") && value.code !== void 0)
13275
13410
  try {
13276
- let detail = parseConnectionFailureDetail(value.detail), completedWork = steps.some((step) => step.status === "completed") || !!local2.local?.effects.some((effect) => effect.status === "completed") || !!local2.local?.data.some((repository) => repository.created.length || repository.updated.length || repository.deleted.length);
13277
- return value.code === detail.code && value.message === connectionRunFailureMessage(detail, completedWork);
13411
+ let detail2 = parseConnectionFailureDetail(value.detail), completedWork = steps.some((step) => step.status === "completed") || !!local2.local?.effects.some((effect) => effect.status === "completed") || !!local2.local?.data.some((repository) => repository.created.length || repository.updated.length || repository.deleted.length);
13412
+ return value.code === detail2.code && value.message === connectionRunFailureMessage(detail2, completedWork);
13278
13413
  } catch {
13279
13414
  }
13280
13415
  if (!only(value, "message,code,step,sizeBytes,limitBytes,summaryBytes,dataBytes") || !message(value.message)) return !1;
13281
13416
  if (value.code === void 0) return only(value, "message");
13282
13417
  if (value.code !== "step_output_too_large") return !1;
13283
13418
  try {
13284
- let { code: _, message: message2, ...facts2 } = value, detail = parseRoutineStepOutputDetail(facts2);
13285
- return message2 === routineStepOutputMessage(detail) && steps.some((step) => step.id === detail.step && step.status === "failed");
13419
+ let { code: _, message: message2, ...facts2 } = value, detail2 = parseRoutineStepOutputDetail(facts2);
13420
+ return message2 === routineStepOutputMessage(detail2) && steps.some((step) => step.id === detail2.step && step.status === "failed");
13286
13421
  } catch {
13287
13422
  return !1;
13288
13423
  }
@@ -13290,9 +13425,9 @@ function validFailure(value, steps, local2) {
13290
13425
  function only(value, allowed) {
13291
13426
  return !!value && typeof value == "object" && !Array.isArray(value) && Object.keys(value).every((key) => allowed.split(",").includes(key));
13292
13427
  }
13293
- var timestamp = (value) => typeof value == "string" && value.length <= 32 && Number.isFinite(Date.parse(value)), message = (value) => typeof value == "string" && value.length > 0 && value.length <= 512, bounded2 = (value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 256 * 1024;
13428
+ var timestamp2 = (value) => typeof value == "string" && value.length <= 32 && Number.isFinite(Date.parse(value)), message = (value) => typeof value == "string" && value.length > 0 && value.length <= 512, bounded2 = (value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 256 * 1024;
13294
13429
  function optionalTimes(value) {
13295
- return (value.startedAt === void 0 || timestamp(value.startedAt)) && (value.finishedAt === void 0 || timestamp(value.finishedAt));
13430
+ return (value.startedAt === void 0 || timestamp2(value.startedAt)) && (value.finishedAt === void 0 || timestamp2(value.finishedAt));
13296
13431
  }
13297
13432
  function validStep(step) {
13298
13433
  return typeof step.id == "string" && identifier.test(step.id) && typeof step.title == "string" && step.title.length > 0 && step.title.length <= 256 && ["pending", "running", "completed", "failed", "skipped"].includes(step.status) && optionalTimes(step) && (step.progress === void 0 || only(step.progress, "completed,total") && Number.isSafeInteger(step.progress.completed) && Number.isSafeInteger(step.progress.total) && step.progress.completed > 0 && step.progress.completed <= step.progress.total) && (() => {
@@ -13357,7 +13492,7 @@ function unavailable6(key, reason) {
13357
13492
  let descriptor = appDescriptors().find((item) => item.id === key);
13358
13493
  return {
13359
13494
  ...structuredClone(descriptor),
13360
- connections: descriptor.connections.map((connection) => ({ ...connection, available: !1 })),
13495
+ connections: descriptor.connections.map((connection2) => ({ ...connection2, available: !1 })),
13361
13496
  readiness: { state: "unavailable", reason, message: reason === "not_deployed" ? "Routine is not deployed." : "Routine capability unavailable." }
13362
13497
  };
13363
13498
  }