@oddington/sdk 0.1.63 → 0.1.64

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
@@ -97,40 +97,40 @@ var FileOperationError = class extends Error {
97
97
  };
98
98
  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;
99
99
  function parseFileDescriptor(value) {
100
- let invalid12 = () => {
100
+ let invalid13 = () => {
101
101
  throw new FileOperationError("unavailable", 503, !0);
102
102
  };
103
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid12();
103
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid13();
104
104
  let f = value;
105
- 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 invalid12();
105
+ if (Object.keys(f).sort().join(",") !== "enrichments,id,mediaType,name,path,sha256,size" || typeof f.id != "string" || !FILE_ID_PATTERN.test(f.id) || !safeFileName(f.name) || !safeFilePath(f.path) || !Number.isSafeInteger(f.size) || f.size < 0 || f.size > FILE_ORIGINAL_MAX_BYTES || typeof f.sha256 != "string" || !/^[0-9a-f]{64}$/.test(f.sha256) || !f.enrichments || typeof f.enrichments != "object" || Array.isArray(f.enrichments) || !isCanonicalOriginalMediaType(f.mediaType)) return invalid13();
106
106
  for (let [name2, descriptor] of Object.entries(f.enrichments)) {
107
- if (!safeEnrichmentName(name2)) return invalid12();
107
+ if (!safeEnrichmentName(name2)) return invalid13();
108
108
  parseEnrichmentDescriptor(descriptor);
109
109
  }
110
- return new TextEncoder().encode(JSON.stringify(f)).byteLength > 16 * 1024 ? invalid12() : f;
110
+ return new TextEncoder().encode(JSON.stringify(f)).byteLength > 16 * 1024 ? invalid13() : f;
111
111
  }
112
112
  function parseEnrichmentDescriptor(value) {
113
- let invalid12 = () => {
113
+ let invalid13 = () => {
114
114
  throw new FileOperationError("unavailable", 503, !0);
115
115
  };
116
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid12();
116
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid13();
117
117
  let d = value;
118
- 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) ? invalid12() : d;
118
+ return Object.keys(d).sort().join(",") !== "mediaType,sha256,size" || !["application/octet-stream", "text/plain", "text/markdown", "application/json"].includes(d.mediaType) || !Number.isSafeInteger(d.size) || d.size < 0 || d.size > 16 * 1024 * 1024 || typeof d.sha256 != "string" || !/^[0-9a-f]{64}$/.test(d.sha256) ? invalid13() : d;
119
119
  }
120
120
  function safeEnrichmentName(value) {
121
121
  return safeFileName(value) && !/^original(?:\.|$)/i.test(value);
122
122
  }
123
123
  function parseFileEnrichMetadata(value, maxBytes) {
124
- let invalid12 = (reason = "invalid_metadata") => {
124
+ let invalid13 = (reason = "invalid_metadata") => {
125
125
  throw new FileOperationError("invalid_input", 400, !1, { reason });
126
126
  };
127
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid12();
127
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid13();
128
128
  let d = value;
129
- if (Object.keys(d).some((key) => !["name", "size", "mediaType", "replace"].includes(key))) return invalid12();
130
- if (!safeEnrichmentName(d.name)) return invalid12("invalid_enrichment_name");
131
- if (!Number.isSafeInteger(d.size) || d.size < 0) return invalid12("invalid_size");
132
- if (d.mediaType !== void 0 && (typeof d.mediaType != "string" || d.mediaType.length > 255 || /[\u0000-\u001f\u007f]/.test(d.mediaType))) return invalid12("invalid_media_type");
133
- if (d.replace !== void 0 && (typeof d.replace != "string" || !/^[0-9a-f]{64}$/.test(d.replace))) return invalid12("invalid_replacement");
129
+ if (Object.keys(d).some((key) => !["name", "size", "mediaType", "replace"].includes(key))) return invalid13();
130
+ if (!safeEnrichmentName(d.name)) return invalid13("invalid_enrichment_name");
131
+ if (!Number.isSafeInteger(d.size) || d.size < 0) return invalid13("invalid_size");
132
+ if (d.mediaType !== void 0 && (typeof d.mediaType != "string" || d.mediaType.length > 255 || /[\u0000-\u001f\u007f]/.test(d.mediaType))) return invalid13("invalid_media_type");
133
+ if (d.replace !== void 0 && (typeof d.replace != "string" || !/^[0-9a-f]{64}$/.test(d.replace))) return invalid13("invalid_replacement");
134
134
  if (d.size > maxBytes) throw new FileOperationError(
135
135
  "request_too_large",
136
136
  413,
@@ -163,25 +163,25 @@ function isCanonicalOriginalMediaType(value) {
163
163
  }
164
164
  }
165
165
  function parseFileCreateMetadata(value, maxBytes) {
166
- let invalid12 = (reason = "invalid_metadata") => {
166
+ let invalid13 = (reason = "invalid_metadata") => {
167
167
  throw new FileOperationError("invalid_input", 400, !1, { reason });
168
168
  };
169
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid12();
169
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid13();
170
170
  let input = value;
171
- if (Object.keys(input).some((key) => !["name", "path", "storage", "mediaType", "size", "requestKey"].includes(key))) return invalid12();
171
+ if (Object.keys(input).some((key) => !["name", "path", "storage", "mediaType", "size", "requestKey"].includes(key))) return invalid13();
172
172
  let path = input.path === void 0 ? "Files" : input.path;
173
- if (!safeFileName(input.name)) return invalid12("invalid_name");
174
- if (!safeManagedFilePath(path)) return invalid12("invalid_path");
175
- if (input.storage !== void 0 && input.storage !== "remote" && input.storage !== "local") return invalid12("invalid_storage");
173
+ if (!safeFileName(input.name)) return invalid13("invalid_name");
174
+ if (!safeManagedFilePath(path)) return invalid13("invalid_path");
175
+ if (input.storage !== void 0 && input.storage !== "remote" && input.storage !== "local") return invalid13("invalid_storage");
176
176
  let mediaType = input.mediaType === void 0 ? "application/octet-stream" : declaredOriginalMediaType(input.mediaType);
177
- if (!Number.isSafeInteger(input.size) || input.size < 0) return invalid12("invalid_size");
177
+ if (!Number.isSafeInteger(input.size) || input.size < 0) return invalid13("invalid_size");
178
178
  if (input.size > maxBytes) throw new FileOperationError(
179
179
  "request_too_large",
180
180
  413,
181
181
  !1,
182
182
  { reason: "size_limit", limitBytes: maxBytes, receivedBytes: input.size }
183
183
  );
184
- return typeof input.requestKey != "string" || input.requestKey.length < 1 || input.requestKey.length > 256 || input.requestKey !== input.requestKey.trim() || /[\u0000-\u001f\u007f]/.test(input.requestKey) ? invalid12("invalid_request_key") : {
184
+ return typeof input.requestKey != "string" || input.requestKey.length < 1 || input.requestKey.length > 256 || input.requestKey !== input.requestKey.trim() || /[\u0000-\u001f\u007f]/.test(input.requestKey) ? invalid13("invalid_request_key") : {
185
185
  name: input.name,
186
186
  path,
187
187
  ...input.storage ? { storage: input.storage } : {},
@@ -596,10 +596,10 @@ function handlerReference(value) {
596
596
  function defineHandler(value) {
597
597
  let source2 = object(value, "handler");
598
598
  keys(source2, ["id", "results", "run"], "handler");
599
- let stable3 = (value2) => typeof value2 == "string" && /^[a-zA-Z0-9][a-zA-Z0-9_./-]{0,127}$/.test(value2);
600
- stable3(source2.id) || fail("Handler ID must be stable");
599
+ let stable4 = (value2) => typeof value2 == "string" && /^[a-zA-Z0-9][a-zA-Z0-9_./-]{0,127}$/.test(value2);
600
+ stable4(source2.id) || fail("Handler ID must be stable");
601
601
  let results = source2.results === void 0 ? void 0 : distinctIds(source2.results, "handler results", !1);
602
- return results && (results.length > 64 || results.some((result2) => !stable3(result2))) && fail("Handler results must be stable IDs"), typeof source2.run != "function" && fail("Handler requires a run function"), Object.freeze({ id: value.id, ...results === void 0 ? {} : { results: Object.freeze(results.sort()) }, run: value.run });
602
+ return results && (results.length > 64 || results.some((result2) => !stable4(result2))) && fail("Handler results must be stable IDs"), typeof source2.run != "function" && fail("Handler requires a run function"), Object.freeze({ id: value.id, ...results === void 0 ? {} : { results: Object.freeze(results.sort()) }, run: value.run });
603
603
  }
604
604
  function respond(handler, input) {
605
605
  return defineHandler(handler), handlerReference({ id: handler.id, input });
@@ -782,10 +782,10 @@ function assertRoutineJson(value, ancestors = /* @__PURE__ */ new Set()) {
782
782
  if (!value || typeof value != "object" || ancestors.has(value)) return invalid2();
783
783
  let array3 = Array.isArray(value);
784
784
  if (!array3 && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return invalid2();
785
- let keys6 = Reflect.ownKeys(value);
786
- if (array3 && (keys6.length !== value.length + 1 || !Array.from({ length: value.length }, (_, index) => Object.hasOwn(value, index)).every(Boolean))) return invalid2();
785
+ let keys7 = Reflect.ownKeys(value);
786
+ if (array3 && (keys7.length !== value.length + 1 || !Array.from({ length: value.length }, (_, index) => Object.hasOwn(value, index)).every(Boolean))) return invalid2();
787
787
  ancestors.add(value);
788
- for (let key of keys6) {
788
+ for (let key of keys7) {
789
789
  if (array3 && key === "length") continue;
790
790
  if (typeof key != "string") return invalid2();
791
791
  let descriptor = Object.getOwnPropertyDescriptor(value, key);
@@ -873,7 +873,7 @@ function routineAIOutputMessage(issue) {
873
873
  function parseRoutineAIErrorDetail(code, value) {
874
874
  if (code === "invalid_output") return parseRoutineAIOutputIssue(value);
875
875
  if (!value || typeof value != "object" || Array.isArray(value)) return;
876
- let v = value, only2 = (...keys6) => Object.keys(v).every((key) => ["reason", ...keys6].includes(key));
876
+ let v = value, only2 = (...keys7) => Object.keys(v).every((key) => ["reason", ...keys7].includes(key));
877
877
  if (code === "provider_failure") {
878
878
  if (v.reason === "turn_limit" && only2("limit") && Number.isSafeInteger(v.limit) && Number(v.limit) >= 1 && Number(v.limit) <= 1024)
879
879
  return { reason: "turn_limit", limit: v.limit };
@@ -953,14 +953,14 @@ var AIError = class extends Error {
953
953
  code;
954
954
  detail;
955
955
  };
956
- function capture(value, invalid12, oversized, limit = ROUTINE_AI_VALUE_BYTES) {
956
+ function capture(value, invalid13, oversized, limit = ROUTINE_AI_VALUE_BYTES) {
957
957
  try {
958
958
  assertRoutineJson(value);
959
959
  let encoded = JSON.stringify(value);
960
960
  if (new TextEncoder().encode(encoded).byteLength > limit) throw new AIError(oversized);
961
961
  return freezeRoutineMetadata(JSON.parse(encoded));
962
962
  } catch (error) {
963
- throw error instanceof AIError ? error : new AIError(invalid12);
963
+ throw error instanceof AIError ? error : new AIError(invalid13);
964
964
  }
965
965
  }
966
966
  function parseRoutineAIRequest(value) {
@@ -998,10 +998,10 @@ function parseRoutineAIResult(request3, value) {
998
998
  }
999
999
  return validateObject(request3.schema, v.object), freezeRoutineMetadata({ object: v.object });
1000
1000
  }
1001
- function validateObject(schema2, object8, text5) {
1001
+ function validateObject(schema2, object9, text5) {
1002
1002
  let detail = { reason: "invalid_response" };
1003
1003
  try {
1004
- validateRoutineSchemaValue(schema2, object8, (issue) => {
1004
+ validateRoutineSchemaValue(schema2, object9, (issue) => {
1005
1005
  detail = issue;
1006
1006
  });
1007
1007
  } catch {
@@ -1014,23 +1014,23 @@ function acceptText(request3, text5) {
1014
1014
  if (!text5.trim()) throw new AIError("invalid_output", { text: text5, detail: { reason: "empty_text" } });
1015
1015
  return freezeRoutineMetadata({ text: text5 });
1016
1016
  }
1017
- let object8, trimmed = text5.trim(), fenced = /^(`{3,}|~{3,})(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n\1[ \t]*$/i.exec(trimmed);
1017
+ let object9, trimmed = text5.trim(), fenced = /^(`{3,}|~{3,})(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n\1[ \t]*$/i.exec(trimmed);
1018
1018
  try {
1019
- object8 = JSON.parse(fenced ? fenced[2] : text5);
1019
+ object9 = JSON.parse(fenced ? fenced[2] : text5);
1020
1020
  } catch {
1021
1021
  throw new AIError("invalid_output", { text: text5, detail: { reason: "invalid_json" } });
1022
1022
  }
1023
- return validateObject(request3.schema, object8, text5), capture({ object: object8 }, "invalid_output", "output_too_large");
1023
+ return validateObject(request3.schema, object9, text5), capture({ object: object9 }, "invalid_output", "output_too_large");
1024
1024
  }
1025
1025
 
1026
1026
  var ROUTINE_STEP_SUMMARY_BYTES = 256 * 1024, ROUTINE_STEP_OUTPUT_BYTES = 1024 * 1024;
1027
1027
  function parseRoutineStepOutputDetail(value) {
1028
- let invalid12 = () => {
1028
+ let invalid13 = () => {
1029
1029
  throw new AppRoutineContractError("invalid_value");
1030
1030
  };
1031
1031
  assertRoutineFields(value, ["step", "sizeBytes", "limitBytes", "summaryBytes", "dataBytes"]);
1032
1032
  let { step, sizeBytes, limitBytes, summaryBytes, dataBytes } = value;
1033
- 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 ? invalid12() : freezeRoutineMetadata({ step, sizeBytes, limitBytes, summaryBytes, dataBytes });
1033
+ return !isAppRoutineName(step) || ![sizeBytes, limitBytes, summaryBytes, dataBytes].every((bytes) => Number.isSafeInteger(bytes) && bytes > 0) || sizeBytes !== summaryBytes + dataBytes || limitBytes !== (summaryBytes > ROUTINE_STEP_SUMMARY_BYTES ? ROUTINE_STEP_SUMMARY_BYTES : ROUTINE_STEP_OUTPUT_BYTES) || (limitBytes === ROUTINE_STEP_SUMMARY_BYTES ? summaryBytes : sizeBytes) <= limitBytes ? invalid13() : freezeRoutineMetadata({ step, sizeBytes, limitBytes, summaryBytes, dataBytes });
1034
1034
  }
1035
1035
  function routineStepOutputMessage(value) {
1036
1036
  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.";
@@ -1431,20 +1431,20 @@ var localDataPath = (value, repository) => typeof value == "string" && value.len
1431
1431
  return Object.keys(row).sort().join(",") === "action,path" && ["created", "updated", "deleted"].includes(String(row.action)) && localDataPath(row.path, repository);
1432
1432
  };
1433
1433
  function parseDataFailureDetail(value) {
1434
- let invalid12 = () => {
1434
+ let invalid13 = () => {
1435
1435
  throw new Error("Invalid local Data failure detail");
1436
1436
  };
1437
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid12();
1437
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid13();
1438
1438
  let row = value;
1439
- 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 invalid12();
1439
+ if (Object.keys(row).sort().join(",") !== "cause,code,files,nextAction,operation,repository" || !["local_data_read_failed", "local_data_write_failed", "local_data_write_partial"].includes(String(row.code)) || !["read", "write"].includes(String(row.operation)) || typeof row.repository != "string" || !/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(row.repository) || row.repository.includes("//") || row.repository.includes("..") || !["fix_failed_file_then_rerun", "review_resolve_then_rerun"].includes(String(row.nextAction))) return invalid13();
1440
1440
  let repository = row.repository;
1441
- if (!row.cause || typeof row.cause != "object" || Array.isArray(row.cause)) return invalid12();
1441
+ if (!row.cause || typeof row.cause != "object" || Array.isArray(row.cause)) return invalid13();
1442
1442
  let cause = row.cause;
1443
- 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 invalid12();
1443
+ if (!["code,message", "code,message,path"].includes(Object.keys(cause).sort().join(",")) || !["schema_validation_failed", "invalid_record", "unsafe_record", "stale_record", "path_conflict", "filesystem_unavailable"].includes(String(cause.code)) || typeof cause.message != "string" || !cause.message || cause.message.length > 512 || /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(cause.message) || cause.path !== void 0 && !localDataPath(cause.path, repository) || !row.files || typeof row.files != "object" || Array.isArray(row.files)) return invalid13();
1444
1444
  let files3 = row.files;
1445
- 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 invalid12();
1446
- for (let key of ["savedOmitted", "notAttemptedOmitted"]) if (files3[key] !== void 0 && (!Number.isSafeInteger(files3[key]) || Number(files3[key]) < 1 || Number(files3[key]) > 1e4)) return invalid12();
1447
- 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" ? invalid12() : structuredClone(value);
1445
+ if (Object.keys(files3).some((key) => !["state", "saved", "failed", "notAttempted", "savedOmitted", "notAttemptedOmitted"].includes(key)) || !["none", "partial"].includes(String(files3.state)) || !Array.isArray(files3.saved) || files3.saved.length > 128 || !files3.saved.every((item) => localDataFile(item, repository)) || files3.failed !== void 0 && !localDataFile(files3.failed, repository) || !Array.isArray(files3.notAttempted) || files3.notAttempted.length > 128 || !files3.notAttempted.every((item) => localDataFile(item, repository))) return invalid13();
1446
+ for (let key of ["savedOmitted", "notAttemptedOmitted"]) if (files3[key] !== void 0 && (!Number.isSafeInteger(files3[key]) || Number(files3[key]) < 1 || Number(files3[key]) > 1e4)) return invalid13();
1447
+ return row.operation === "read" && (row.code !== "local_data_read_failed" || files3.state !== "none" || files3.saved.length || files3.failed !== void 0 || files3.notAttempted.length) || row.operation === "write" && row.code === "local_data_read_failed" || row.code === "local_data_write_partial" && (files3.state !== "partial" || !files3.saved.length) || row.code !== "local_data_write_partial" && files3.state === "partial" ? invalid13() : structuredClone(value);
1448
1448
  }
1449
1449
  function parseDataOperationDetail(value) {
1450
1450
  let validation = parseDataValidationDetail(value);
@@ -1587,21 +1587,21 @@ function captureRecordsQuery(query) {
1587
1587
  return capture3(query);
1588
1588
  }
1589
1589
  function captureRecordsAll(query, options) {
1590
- let invalid12 = () => {
1590
+ let invalid13 = () => {
1591
1591
  throw new DataOperationError("invalid_query");
1592
1592
  };
1593
1593
  try {
1594
1594
  let properties = dataProperties(options), maxRecords = properties.maxRecords?.value;
1595
- if (Object.keys(properties).join(",") !== "maxRecords" || !Number.isSafeInteger(maxRecords) || maxRecords < 1) return invalid12();
1595
+ if (Object.keys(properties).join(",") !== "maxRecords" || !Number.isSafeInteger(maxRecords) || maxRecords < 1) return invalid13();
1596
1596
  let detached = capture3(query), selections = dataProperties(detached);
1597
- if (Object.keys(selections).length < 1 || Object.keys(selections).length > 16) return invalid12();
1597
+ if (Object.keys(selections).length < 1 || Object.keys(selections).length > 16) return invalid13();
1598
1598
  for (let selection2 of Object.values(selections)) {
1599
1599
  let fields4 = dataProperties(selection2.value);
1600
- if (fields4.$ && Object.hasOwn(dataProperties(fields4.$.value), "after")) return invalid12();
1600
+ if (fields4.$ && Object.hasOwn(dataProperties(fields4.$.value), "after")) return invalid13();
1601
1601
  }
1602
1602
  return { query: detached, maxRecords };
1603
1603
  } catch {
1604
- return invalid12();
1604
+ return invalid13();
1605
1605
  }
1606
1606
  }
1607
1607
 
@@ -1870,8 +1870,8 @@ function recordPagination(queryRecords) {
1870
1870
  })), response2 = await queryRecords(request3), page;
1871
1871
  try {
1872
1872
  page = capture4(response2);
1873
- let keys6 = Object.keys(dataProperties(page));
1874
- (keys6.length !== active2.length + 1 || keys6.some((key) => key !== "$meta" && !active2.includes(key))) && unavailable();
1873
+ let keys7 = Object.keys(dataProperties(page));
1874
+ (keys7.length !== active2.length + 1 || keys7.some((key) => key !== "$meta" && !active2.includes(key))) && unavailable();
1875
1875
  let meta = page.$meta;
1876
1876
  (Object.keys(dataProperties(meta)).sort().join(",") !== "collections,version" || !text2(meta.version)) && unavailable(), version = meta.version, Object.keys(dataProperties(meta.collections)).some((key) => !active2.includes(key)) && unavailable();
1877
1877
  for (let name2 of active2) {
@@ -2174,8 +2174,8 @@ function selectionTree(value, schema2, collectionsByType, depth = 0, many = !1)
2174
2174
  if (condition !== null && typeof condition == "object") {
2175
2175
  let expression = mapping2(condition);
2176
2176
  if (!Object.hasOwn(expression, "$in")) {
2177
- let keys6 = Object.keys(expression);
2178
- if (keys6.length === 0 || keys6.some((key) => !boundOperators.includes(key)) || Object.hasOwn(expression, "$gt") && Object.hasOwn(expression, "$gte") || Object.hasOwn(expression, "$lt") && Object.hasOwn(expression, "$lte")) return fail3("invalid bounds");
2177
+ let keys7 = Object.keys(expression);
2178
+ if (keys7.length === 0 || keys7.some((key) => !boundOperators.includes(key)) || Object.hasOwn(expression, "$gt") && Object.hasOwn(expression, "$gte") || Object.hasOwn(expression, "$lt") && Object.hasOwn(expression, "$lte")) return fail3("invalid bounds");
2179
2179
  if (field.name === "$ref" || !["integer", "number", "date", "datetime"].includes(field.kind))
2180
2180
  return fail3(`ineligible range field: ${name2}`);
2181
2181
  let bounds = boundOperators.filter((operator) => Object.hasOwn(expression, operator)).map((operator) => {
@@ -2365,32 +2365,140 @@ function* evaluateRecordsQuery(query, catalogue, context, maxRecords, cloneValue
2365
2365
 
2366
2366
  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";
2367
2367
 
2368
- var snapshotCollection = (catalogue, ref) => catalogue.filter((c) => ref.startsWith(`${c.name}/`)).sort((a, b) => b.name.length - a.name.length)[0], invalid7 = () => {
2368
+ var invalid7 = () => {
2369
2369
  throw new DataOperationError("unavailable", !0);
2370
- }, object4 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid7() : value;
2370
+ }, object4 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid7() : value, keys3 = (value, expected) => Object.keys(value).sort().join(",") === expected, hash = (value) => typeof value == "string" && /^[0-9a-f]{40}$/.test(value), time = (value) => typeof value == "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(value) && Number.isFinite(Date.parse(value)), sorted = (values) => values.every((value, i) => i === 0 || values[i - 1] < value);
2371
+ function json(value) {
2372
+ if (!(value === null || typeof value == "boolean" || typeof value == "number" && Number.isFinite(value) || dataText(value))) {
2373
+ if (Array.isArray(value)) {
2374
+ for (let item of value) json(item);
2375
+ return;
2376
+ }
2377
+ for (let [key, item] of Object.entries(object4(value))) {
2378
+ if (!dataText(key)) return invalid7();
2379
+ json(item);
2380
+ }
2381
+ }
2382
+ }
2371
2383
  function stable(value) {
2372
- return Array.isArray(value) ? `[${value.map(stable).join(",")}]` : value && typeof value == "object" ? `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${stable(entry)}`).join(",")}}` : JSON.stringify(value);
2384
+ return Array.isArray(value) ? `[${value.map(stable).join(",")}]` : value && typeof value == "object" ? `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => `${JSON.stringify(key)}:${stable(item)}`).join(",")}}` : JSON.stringify(value);
2385
+ }
2386
+ var slot = (values, field) => Object.hasOwn(values, field) ? { present: !0, value: values[field] } : { present: !1 };
2387
+ function apply(book, event) {
2388
+ let records = book.get(event.collection), prior = records.get(event.ref);
2389
+ if (event.kind === "create") {
2390
+ if (prior) return invalid7();
2391
+ records.set(event.ref, structuredClone(event.values));
2392
+ } else if (event.kind === "delete") {
2393
+ if (!prior || stable(prior) !== stable(event.values)) return invalid7();
2394
+ records.delete(event.ref);
2395
+ } else if (event.kind === "rename") {
2396
+ let before = records.get(event.previousRef);
2397
+ if (!before || prior) return invalid7();
2398
+ records.delete(event.previousRef), records.set(event.ref, before);
2399
+ } else if (event.kind === "update") {
2400
+ if (!prior || stable(slot(prior, event.field)) !== stable(event.before) || stable(event.before) === stable(event.after)) return invalid7();
2401
+ event.after.present ? Object.defineProperty(prior, event.field, { value: structuredClone(event.after.value), enumerable: !0, configurable: !0, writable: !0 }) : delete prior[event.field];
2402
+ }
2403
+ }
2404
+ function validateSnapshotHistory(input, collections, version) {
2405
+ let row = object4(input), selections = object4(row.fields);
2406
+ if (!keys3(row, "commits,fields,through") || !hash(row.through) || version !== `current-${row.through}` || !Array.isArray(row.commits) || !row.commits.length || !Object.keys(selections).length || !sorted(Object.keys(selections))) return invalid7();
2407
+ let book = /* @__PURE__ */ new Map();
2408
+ for (let [collection, selection2] of Object.entries(selections)) {
2409
+ let selected = object4(selection2), fields4 = selected.fields;
2410
+ if (!Object.hasOwn(collections, collection) || !keys3(selected, "fields") || !Array.isArray(fields4) || !fields4.length || fields4.some((field) => typeof field != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(field)) || !sorted(fields4)) return invalid7();
2411
+ book.set(collection, /* @__PURE__ */ new Map());
2412
+ }
2413
+ let history = row, seen = /* @__PURE__ */ new Set(), parent = null;
2414
+ for (let group of history.commits) {
2415
+ if (!keys3(object4(group), "authoredAt,commit,committedAt,events,firstParent") || !hash(group.commit) || seen.has(group.commit) || group.firstParent !== parent || !time(group.authoredAt) || !time(group.committedAt) || !Array.isArray(group.events)) return invalid7();
2416
+ seen.add(group.commit), parent = group.commit;
2417
+ let previous, created = /* @__PURE__ */ new Set();
2418
+ for (let event of group.events) {
2419
+ if (object4(event), !book.has(event.collection) || !validRecordRef(event.ref) || !event.ref.startsWith(`${event.collection}/`)) return invalid7();
2420
+ let fields4 = history.fields[event.collection].fields;
2421
+ if (event.kind === "create" || event.kind === "delete") {
2422
+ if (!keys3(event, "collection,kind,ref,values") || Object.keys(object4(event.values)).some((field) => !fields4.includes(field))) return invalid7();
2423
+ json(event.values), event.kind === "create" && created.add(event.ref);
2424
+ } else if (event.kind === "rename") {
2425
+ if (!keys3(event, "collection,kind,previousRef,ref") || !validRecordRef(event.previousRef) || !event.previousRef.startsWith(`${event.collection}/`) || event.previousRef === event.ref) return invalid7();
2426
+ } else if (event.kind === "update") {
2427
+ if (!keys3(event, "after,before,collection,field,kind,ref") || !fields4.includes(event.field) || created.has(event.ref)) return invalid7();
2428
+ for (let value of [event.before, event.after]) {
2429
+ if (object4(value), value.present === !1 ? !keys3(value, "present") : value.present !== !0 || !keys3(value, "present,value")) return invalid7();
2430
+ value.present && json(value.value);
2431
+ }
2432
+ } else return invalid7();
2433
+ let order = [event.kind === "delete" ? 0 : 1, event.ref, event.kind === "update" ? 1 : 0, event.kind === "update" ? event.field : ""];
2434
+ if (previous) {
2435
+ let index = order.findIndex((value, i) => value !== previous[i]);
2436
+ if (index === -1 || order[index] < previous[index]) return invalid7();
2437
+ }
2438
+ previous = order, apply(book, event);
2439
+ }
2440
+ let refs = /* @__PURE__ */ new Set();
2441
+ for (let records of book.values()) for (let ref of records.keys()) {
2442
+ if (refs.has(ref)) return invalid7();
2443
+ refs.add(ref);
2444
+ }
2445
+ }
2446
+ if (parent !== history.through) return invalid7();
2447
+ for (let [collection, records] of book) {
2448
+ 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]]))]);
2449
+ if (stable([...records].sort(([a], [b]) => a < b ? -1 : 1)) !== stable(expected)) return invalid7();
2450
+ }
2451
+ return history;
2452
+ }
2453
+ function captureHistoryInput(input, operation2) {
2454
+ let properties = dataProperties(input), row = Object.fromEntries(Object.entries(properties).map(([key, property]) => [key, property.value]));
2455
+ if (Object.keys(row).some((key) => !(operation2 === "records" ? ["collection", "at"] : ["collection", "ref", "field"]).includes(key)) || typeof row.collection != "string" || operation2 === "records" && !time(row.at) || Object.hasOwn(row, "ref") && !validRecordRef(row.ref) || Object.hasOwn(row, "field") && typeof row.field != "string")
2456
+ throw new DataOperationError("invalid_query");
2457
+ return row;
2458
+ }
2459
+ function readSnapshotHistory(history, input, operation2) {
2460
+ if (!history || !Object.hasOwn(history.fields, input.collection) || input.field !== void 0 && !history.fields[input.collection].fields.includes(input.field))
2461
+ throw new DataOperationError("invalid_query");
2462
+ if (operation2 === "changes") return structuredClone(history.commits.flatMap(({ firstParent: _parent, ...group }) => {
2463
+ let events = group.events.filter((event) => event.collection === input.collection && (input.ref === void 0 || event.ref === input.ref) && (input.field === void 0 || event.kind === "update" && event.field === input.field));
2464
+ return events.length ? [{ ...group, events }] : [];
2465
+ }));
2466
+ let index = history.commits.length - 1;
2467
+ for (; index >= 0 && Date.parse(history.commits[index].committedAt) > Date.parse(input.at); ) index--;
2468
+ let book = /* @__PURE__ */ new Map([[input.collection, /* @__PURE__ */ new Map()]]), selected = !1;
2469
+ for (let i = 0; i <= index; i++) for (let event of history.commits[i].events) event.collection === input.collection && (selected = !0, apply(book, event));
2470
+ return {
2471
+ commit: selected ? history.commits[index].commit : null,
2472
+ records: [...book.get(input.collection)].sort(([a], [b]) => a < b ? -1 : 1).map(([$ref, values]) => ({ $ref, values }))
2473
+ };
2474
+ }
2475
+
2476
+ var snapshotCollection = (catalogue, ref) => catalogue.filter((c) => ref.startsWith(`${c.name}/`)).sort((a, b) => b.name.length - a.name.length)[0], invalid8 = () => {
2477
+ throw new DataOperationError("unavailable", !0);
2478
+ }, object5 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid8() : value;
2479
+ function stable2(value) {
2480
+ 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);
2373
2481
  }
2374
2482
  function schemaText(value) {
2375
- if (typeof value == "string" && !dataText(value)) return invalid7();
2483
+ if (typeof value == "string" && !dataText(value)) return invalid8();
2376
2484
  if (value && typeof value == "object") for (let [key, entry] of Object.entries(value)) {
2377
- if (!dataText(key)) return invalid7();
2485
+ if (!dataText(key)) return invalid8();
2378
2486
  schemaText(entry);
2379
2487
  }
2380
2488
  }
2381
2489
  function validateSnapshotEnvelope(input, repository, name2, bodies = []) {
2382
2490
  try {
2383
- let row = object4(input);
2384
- if (Object.keys(row).sort().join(",") !== "collections,format,name,repository,schemas,version" || row.format !== "data-snapshot.v1" || row.repository !== repository || row.name !== name2 || !dataVersion(row.version)) return invalid7();
2385
- let schemas2 = object4(row.schemas), collections = object4(row.collections);
2491
+ let row = object5(input);
2492
+ if (!["collections,format,name,repository,schemas,version", "collections,format,history,name,repository,schemas,version"].includes(Object.keys(row).sort().join(",")) || row.format !== "data-snapshot.v1" || row.repository !== repository || row.name !== name2 || !dataVersion(row.version)) return invalid8();
2493
+ let schemas2 = object5(row.schemas), collections = object5(row.collections);
2386
2494
  schemaText(schemas2);
2387
2495
  let names = Object.keys(collections);
2388
- if (!names.length || names.join("\0") !== [...names].sort().join("\0") || Object.keys(schemas2).join("\0") !== names.join("\0")) return invalid7();
2496
+ if (!names.length || names.join("\0") !== [...names].sort().join("\0") || Object.keys(schemas2).join("\0") !== names.join("\0")) return invalid8();
2389
2497
  let catalogue = names.map((name3) => {
2390
- let schema2 = object4(schemas2[name3]);
2391
- if (!validRecordRef(`${name3}/example`) || schema2.name !== name3 || typeof schema2.type != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(schema2.type) || schema2.description !== void 0 && !dataText(schema2.description) || Object.keys(schema2).some((key) => !["name", "type", "description", "fields"].includes(key))) return invalid7();
2498
+ let schema2 = object5(schemas2[name3]);
2499
+ if (!validRecordRef(`${name3}/example`) || schema2.name !== name3 || typeof schema2.type != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(schema2.type) || schema2.description !== void 0 && !dataText(schema2.description) || Object.keys(schema2).some((key) => !["name", "type", "description", "fields"].includes(key))) return invalid8();
2392
2500
  let definitions2 = fields2(schema2.fields, 0, !0);
2393
- return stable(definitions2.map(publicField)) !== stable(schema2.fields) ? invalid7() : { name: name3, schema: {
2501
+ return stable2(definitions2.map(publicField)) !== stable2(schema2.fields) ? invalid8() : { name: name3, schema: {
2394
2502
  type: schema2.type,
2395
2503
  fields: definitions2,
2396
2504
  ...schema2.description === void 0 ? {} : { description: schema2.description }
@@ -2398,18 +2506,18 @@ function validateSnapshotEnvelope(input, repository, name2, bodies = []) {
2398
2506
  }), types = /* @__PURE__ */ new Map();
2399
2507
  for (let collection of catalogue) {
2400
2508
  let records = collections[collection.name];
2401
- if (!Array.isArray(records)) return invalid7();
2509
+ if (!Array.isArray(records)) return invalid8();
2402
2510
  let previous = "";
2403
2511
  for (let record4 of records) {
2404
- let value = object4(record4);
2405
- 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 invalid7();
2512
+ let value = object5(record4);
2513
+ if (!validRecordRef(value.$ref) || snapshotCollection(catalogue, value.$ref)?.name !== collection.name || value.$ref <= previous || types.has(value.$ref) || typeof value.$version != "string" || !/^record-v1:[0-9a-f]{64}$/.test(value.$version)) return invalid8();
2406
2514
  types.set(value.$ref, collection.schema.type), previous = value.$ref;
2407
2515
  }
2408
2516
  }
2409
2517
  for (let collection of catalogue) for (let record4 of collections[collection.name]) {
2410
2518
  let { $ref: _ref, $version: _version, $body, ...values } = record4;
2411
- if (Object.hasOwn(record4, "$body") && (!bodies.includes(collection.name) || typeof $body != "string")) return invalid7();
2412
- validateRecordFields(values, collection.schema.fields, (ref, targets) => catalogue.some((item) => ref.startsWith(`${item.name}/`)) ? types.get(ref) : targets[0], !0);
2519
+ if (Object.hasOwn(record4, "$body") && (!bodies.includes(collection.name) || typeof $body != "string")) return invalid8();
2520
+ validateRecordFields(values, collection.schema.fields, (ref, targets) => types.get(ref) ?? targets[0], !0);
2413
2521
  }
2414
2522
  return {
2415
2523
  format: "data-snapshot.v1",
@@ -2418,51 +2526,52 @@ function validateSnapshotEnvelope(input, repository, name2, bodies = []) {
2418
2526
  version: row.version,
2419
2527
  bodyCollections: [...bodies],
2420
2528
  catalogue,
2421
- collections
2529
+ collections,
2530
+ ...Object.hasOwn(row, "history") ? { history: validateSnapshotHistory(row.history, collections, row.version) } : {}
2422
2531
  };
2423
2532
  } catch {
2424
- return invalid7();
2533
+ return invalid8();
2425
2534
  }
2426
2535
  }
2427
2536
 
2428
- var invalid8 = () => {
2537
+ var invalid9 = () => {
2429
2538
  throw new DataOperationError("unavailable", !0);
2430
- }, object5 = (v) => v && typeof v == "object" && !Array.isArray(v) ? v : invalid8(), uuid = (v) => typeof v == "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v), time = (v) => typeof v == "string" && Number.isFinite(Date.parse(v)), recordVersion = (v) => typeof v == "string" && /^record-v1:[0-9a-f]{64}$/.test(v), keys3 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
2539
+ }, object6 = (v) => v && typeof v == "object" && !Array.isArray(v) ? v : invalid9(), uuid = (v) => typeof v == "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v), time2 = (v) => typeof v == "string" && Number.isFinite(Date.parse(v)), recordVersion = (v) => typeof v == "string" && /^record-v1:[0-9a-f]{64}$/.test(v), keys4 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
2431
2540
  function validateAcquisition(input, repository, name2) {
2432
- let row = object5(input), snapshot = object5(row.snapshot);
2433
- if (Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== snapshotAcquisitionFormat || !["collections,id,name,refreshedAt,repository,version", "bodies,collections,id,name,refreshedAt,repository,version"].includes(Object.keys(snapshot).sort().join(",")) || !uuid(snapshot.id) || snapshot.repository !== repository || snapshot.name !== name2 || !dataVersion(snapshot.version) || !time(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 invalid8();
2541
+ let row = object6(input), snapshot = object6(row.snapshot);
2542
+ if (Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== snapshotAcquisitionFormat || !["collections,id,name,refreshedAt,repository,version", "bodies,collections,id,name,refreshedAt,repository,version"].includes(Object.keys(snapshot).sort().join(",")) || !uuid(snapshot.id) || snapshot.repository !== repository || snapshot.name !== name2 || !dataVersion(snapshot.version) || !time2(snapshot.refreshedAt) || !Array.isArray(snapshot.collections) || !snapshot.collections.length || !snapshot.collections.every((c) => typeof c == "string" && validRecordRef(`${c}/example`)) || snapshot.collections.join("\0") !== [...new Set(snapshot.collections)].sort().join("\0") || !Array.isArray(row.changes)) return invalid9();
2434
2543
  let bodies = snapshot.bodies === void 0 ? [] : snapshot.bodies;
2435
- return !Array.isArray(bodies) || bodies.some((c) => !snapshot.collections.includes(c)) || bodies.join("\0") !== [...new Set(bodies)].sort().join("\0") ? invalid8() : {
2544
+ return !Array.isArray(bodies) || bodies.some((c) => !snapshot.collections.includes(c)) || bodies.join("\0") !== [...new Set(bodies)].sort().join("\0") ? invalid9() : {
2436
2545
  snapshot: { ...snapshot, bodies },
2437
2546
  changes: validateSnapshotChanges(row.changes, snapshot.collections)
2438
2547
  };
2439
2548
  }
2440
2549
  function validateSnapshotChanges(input, collections) {
2441
- if (!Array.isArray(input)) return invalid8();
2550
+ if (!Array.isArray(input)) return invalid9();
2442
2551
  let ids = /* @__PURE__ */ new Set(), unpublished = !1;
2443
2552
  for (let value of input) {
2444
- let c = object5(value), effect = object5(c.effect);
2445
- if (!keys3(c, ["id", "version", "ref", "recordVersion", "effect", "updatedAt", "person", "source", "publication"]) || !uuid(c.id) || ids.has(c.id) || !dataVersion(c.version) || !validRecordRef(c.ref) || !collections.some((name2) => c.ref.startsWith(`${name2}/`)) || !recordVersion(c.recordVersion) || !time(c.updatedAt)) return invalid8();
2553
+ let c = object6(value), effect = object6(c.effect);
2554
+ if (!keys4(c, ["id", "version", "ref", "recordVersion", "effect", "updatedAt", "person", "source", "publication"]) || !uuid(c.id) || ids.has(c.id) || !dataVersion(c.version) || !validRecordRef(c.ref) || !collections.some((name2) => c.ref.startsWith(`${name2}/`)) || !recordVersion(c.recordVersion) || !time2(c.updatedAt)) return invalid9();
2446
2555
  if (ids.add(c.id), c.person !== void 0) {
2447
- let person = object5(c.person);
2448
- if (!keys3(person, ["id", "name", "email"]) || !uuid(person.id) || person.name !== void 0 && !dataText(person.name) || person.email !== void 0 && !dataText(person.email)) return invalid8();
2556
+ let person = object6(c.person);
2557
+ if (!keys4(person, ["id", "name", "email"]) || !uuid(person.id) || person.name !== void 0 && !dataText(person.name) || person.email !== void 0 && !dataText(person.email)) return invalid9();
2449
2558
  }
2450
2559
  if (c.source !== void 0) {
2451
- let source2 = object5(c.source);
2452
- if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid8();
2560
+ let source2 = object6(c.source);
2561
+ if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid9();
2453
2562
  }
2454
2563
  if (c.publication !== void 0) {
2455
- let publication = object5(c.publication);
2456
- if (unpublished || Object.keys(publication).sort().join(",") !== "commit,time" || typeof publication.commit != "string" || !/^[0-9a-f]{40}$/.test(publication.commit) || !time(publication.time)) return invalid8();
2564
+ let publication = object6(c.publication);
2565
+ if (unpublished || Object.keys(publication).sort().join(",") !== "commit,time" || typeof publication.commit != "string" || !/^[0-9a-f]{40}$/.test(publication.commit) || !time2(publication.time)) return invalid9();
2457
2566
  } else unpublished = !0;
2458
2567
  if (effect.kind === "set") {
2459
- if (Object.keys(effect).sort().join(",") !== "field,kind,value" || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field)) return invalid8();
2568
+ if (Object.keys(effect).sort().join(",") !== "field,kind,value" || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field)) return invalid9();
2460
2569
  } else if (effect.kind === "link" || effect.kind === "unlink") {
2461
- if (!keys3(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 invalid8();
2570
+ if (!keys4(effect, ["kind", "field", "refs", ...effect.kind === "link" ? ["remove"] : []]) || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field) || !Array.isArray(effect.refs) || !effect.refs.length || effect.refs.length > 1e5 || effect.refs.some((ref) => !validRecordRef(ref)) || new Set(effect.refs).size !== effect.refs.length || effect.remove !== void 0 && (!Array.isArray(effect.remove) || !effect.remove.length || effect.remove.length > 1e5 || effect.remove.some((ref) => !validRecordRef(ref)) || new Set(effect.remove).size !== effect.remove.length)) return invalid9();
2462
2571
  } else if (effect.kind === "create" || effect.kind === "delete") {
2463
- if (Object.keys(effect).sort().join(",") !== "fields,kind") return invalid8();
2464
- object5(effect.fields);
2465
- } else return invalid8();
2572
+ if (Object.keys(effect).sort().join(",") !== "fields,kind") return invalid9();
2573
+ object6(effect.fields);
2574
+ } else return invalid9();
2466
2575
  }
2467
2576
  return input;
2468
2577
  }
@@ -2472,17 +2581,17 @@ function materializeSnapshot(envelope, changes, version) {
2472
2581
  let rows = new Map(Object.values(envelope.collections).flat().map((r) => [r.$ref, structuredClone(r)]));
2473
2582
  for (let c of changes) {
2474
2583
  let schema2 = snapshotCollection(envelope.catalogue, c.ref);
2475
- if (!schema2) return invalid8();
2584
+ if (!schema2) return invalid9();
2476
2585
  let effect = c.effect, definitions2 = "field" in effect ? schema2.schema.fields.filter((f) => f.name === effect.field) : schema2.schema.fields;
2477
- if ("field" in effect && !definitions2.length) return invalid8();
2586
+ if ("field" in effect && !definitions2.length) return invalid9();
2478
2587
  let values;
2479
2588
  if (effect.kind === "link" || effect.kind === "unlink") {
2480
2589
  let field = definitions2[0];
2481
- if (field.kind !== "link" || !field.many && effect.kind === "link" && effect.refs.length !== 1) return invalid8();
2590
+ if (field.kind !== "link" || !field.many && effect.kind === "link" && effect.refs.length !== 1) return invalid9();
2482
2591
  let targets = [...effect.refs, ...effect.kind === "link" ? effect.remove ?? [] : []];
2483
2592
  for (let ref of targets) validateRecordFields({ [effect.field]: field.many ? [ref] : ref }, definitions2, (_ref, allowed) => allowed[0], !0);
2484
2593
  values = { [effect.field]: field.many ? effect.refs : effect.refs[0] };
2485
- } else values = effect.kind === "set" ? { [effect.field]: effect.value } : "fields" in effect ? effect.fields : invalid8();
2594
+ } else values = effect.kind === "set" ? { [effect.field]: effect.value } : "fields" in effect ? effect.fields : invalid9();
2486
2595
  if (validateRecordFields(
2487
2596
  values,
2488
2597
  definitions2,
@@ -2491,17 +2600,17 @@ function materializeSnapshot(envelope, changes, version) {
2491
2600
  ), !c.publication) continue;
2492
2601
  let prior = rows.get(c.ref);
2493
2602
  if (effect.kind === "set") {
2494
- if (!prior) return invalid8();
2603
+ if (!prior) return invalid9();
2495
2604
  rows.set(c.ref, { ...prior, [effect.field]: effect.value, $version: c.recordVersion });
2496
2605
  } else if (effect.kind === "link" || effect.kind === "unlink") {
2497
- if (!prior) return invalid8();
2606
+ if (!prior) return invalid9();
2498
2607
  let field = definitions2[0], current2 = prior[effect.field], value = field.many ? effect.kind === "link" ? [.../* @__PURE__ */ new Set([...Array.isArray(current2) ? current2 : [], ...effect.refs])].filter((ref) => !effect.remove?.includes(String(ref))) : (Array.isArray(current2) ? current2 : []).filter((ref) => !effect.refs.includes(String(ref))) : effect.kind === "link" ? effect.remove?.includes(effect.refs[0]) ? null : effect.refs[0] : effect.refs.includes(String(current2)) ? null : current2;
2499
2608
  rows.set(c.ref, { ...prior, [effect.field]: value, $version: c.recordVersion });
2500
2609
  } else if (effect.kind === "create") {
2501
- if (prior) return invalid8();
2610
+ if (prior) return invalid9();
2502
2611
  rows.set(c.ref, { ...effect.fields, $ref: c.ref, $version: c.recordVersion });
2503
2612
  } else {
2504
- if (!prior) return invalid8();
2613
+ if (!prior) return invalid9();
2505
2614
  rows.delete(c.ref);
2506
2615
  }
2507
2616
  }
@@ -2519,7 +2628,7 @@ function materializeSnapshot(envelope, changes, version) {
2519
2628
  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)]))
2520
2629
  }, envelope.repository, envelope.name, envelope.bodyCollections);
2521
2630
  } catch {
2522
- return invalid8();
2631
+ return invalid9();
2523
2632
  }
2524
2633
  }
2525
2634
 
@@ -2767,10 +2876,10 @@ async function openSnapshotStore() {
2767
2876
  function unavailable3() {
2768
2877
  throw new DataOperationError("unavailable", !0);
2769
2878
  }
2770
- function stable2(value) {
2771
- return Array.isArray(value) ? `[${value.map(stable2).join(",")}]` : value && typeof value == "object" ? `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${stable2(v)}`).join(",")}}` : JSON.stringify(value);
2879
+ function stable3(value) {
2880
+ return Array.isArray(value) ? `[${value.map(stable3).join(",")}]` : value && typeof value == "object" ? `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${stable3(v)}`).join(",")}}` : JSON.stringify(value);
2772
2881
  }
2773
- var facts = (changes, records = !1) => stable2(changes.filter((c) => !records || c.publication).map((c) => records ? { id: c.id, version: c.version, recordVersion: c.recordVersion, effect: c.effect, publication: c.publication } : c).sort((a, b) => a.id.localeCompare(b.id)));
2882
+ var facts = (changes, records = !1) => stable3(changes.filter((c) => !records || c.publication).map((c) => records ? { id: c.id, version: c.version, recordVersion: c.recordVersion, effect: c.effect, publication: c.publication } : c).sort((a, b) => a.id.localeCompare(b.id)));
2774
2883
  function snapshotDifference(before, after) {
2775
2884
  return { records: facts(before, !0) !== facts(after, !0), changes: facts(before) !== facts(after) };
2776
2885
  }
@@ -2999,19 +3108,19 @@ function captureSelection(input) {
2999
3108
  }
3000
3109
  }
3001
3110
 
3002
- var invalid9 = () => {
3111
+ var invalid10 = () => {
3003
3112
  throw new DataOperationError("invalid_query");
3004
3113
  };
3005
3114
  function captureSnapshotAll(query, options) {
3006
3115
  let properties = dataProperties(options);
3007
- return Object.keys(properties).some((key) => key !== "maxRecords" && key !== "body") || properties.body && properties.body.value !== !0 ? invalid9() : { ...captureRecordsAll(query, { maxRecords: properties.maxRecords?.value }), body: properties.body?.value === !0 };
3116
+ return Object.keys(properties).some((key) => key !== "maxRecords" && key !== "body") || properties.body && properties.body.value !== !0 ? invalid10() : { ...captureRecordsAll(query, { maxRecords: properties.maxRecords?.value }), body: properties.body?.value === !0 };
3008
3117
  }
3009
3118
  var safeName = (value) => typeof value == "string" && /^[a-z0-9][a-z0-9._-]{0,127}$/.test(value) && !value.includes("..");
3010
3119
  function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore, connect = (url, protocols) => new WebSocket(url, protocols)) {
3011
3120
  let pending = /* @__PURE__ */ new WeakMap();
3012
3121
  return async function(input) {
3013
3122
  let properties = dataProperties(input), repository = properties.repository?.value, snapshot = properties.snapshot?.value;
3014
- if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid9();
3123
+ if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid10();
3015
3124
  let authority2 = await resolve(), invalidated = !1, stopLive, assertCurrent = () => {
3016
3125
  if (invalidated || authority2.signal.aborted || !authority2.isCurrent() || !authority2.refresh && authority2.expiresAt <= Date.now())
3017
3126
  throw invalidated = !0, stopLive?.(), new DataOperationError("context_unavailable");
@@ -3199,8 +3308,21 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
3199
3308
  } catch (error) {
3200
3309
  return Promise.reject(error);
3201
3310
  }
3311
+ }, historyRead = (input2, operation2) => {
3312
+ let captured = captureHistoryInput(input2, operation2);
3313
+ return writes.then(() => {
3314
+ let pinned = installation;
3315
+ return localRead(async (store) => {
3316
+ let base = await store.base(pinned);
3317
+ if (!base) throw new DataOperationError("unavailable", !0);
3318
+ return readSnapshotHistory(base.history, captured, operation2);
3319
+ });
3320
+ });
3321
+ }, history = {
3322
+ records: async (input2) => await historyRead(input2, "records"),
3323
+ changes: async (input2) => await historyRead(input2, "changes")
3202
3324
  };
3203
- return { subscribe: live2.subscribe, transact, changes: {
3325
+ return { subscribe: live2.subscribe, transact, history, changes: {
3204
3326
  list: () => writes.then(() => {
3205
3327
  let pinned = installation;
3206
3328
  return localRead((store) => store.changes(pinned));
@@ -3398,7 +3520,7 @@ async function hostedContent(url, init2, parent, upstream = fetch, check = async
3398
3520
  }
3399
3521
  }
3400
3522
 
3401
- 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 = [], invalid10 = () => new FileOperationError("invalid_input", 400), unavailable4 = () => new FileOperationError("unavailable", 503, !0), failures = {
3523
+ var MAX_BYTES = 16 * 1024 * 1024, PART_BYTES = 8 * 1024 * 1024, METADATA_BYTES = 4096, RESULT_BYTES = 16 * 1024, CONTROL_RESULT_BYTES = 128 * 1024, TIMEOUT_MS = 3e4, MAX_ACTIVE = 4, ATTEMPTS = 2, active = 0, waiters = [], invalid11 = () => new FileOperationError("invalid_input", 400), unavailable4 = () => new FileOperationError("unavailable", 503, !0), failures = {
3402
3524
  400: ["invalid_input", "unsupported_context"],
3403
3525
  401: ["unauthenticated"],
3404
3526
  403: ["access_denied"],
@@ -3550,7 +3672,7 @@ async function send(suffix, init2, descriptor, initial, parent) {
3550
3672
  throw unavailable4();
3551
3673
  }
3552
3674
  function idPath(id3) {
3553
- if (typeof id3 != "string" || !FILE_ID_PATTERN.test(id3)) throw invalid10();
3675
+ if (typeof id3 != "string" || !FILE_ID_PATTERN.test(id3)) throw invalid11();
3554
3676
  return `/${id3}`;
3555
3677
  }
3556
3678
  async function multipartCreate(input, metadata, exchange, release, upload, expectedSha256) {
@@ -3593,18 +3715,18 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
3593
3715
  if (!chunk || offset === chunk.byteLength) {
3594
3716
  chunk = void 0, offset = 0;
3595
3717
  let value2 = await next();
3596
- if (value2.done || !(value2.value instanceof Uint8Array) || (chunk = value2.value, chunk.byteLength > metadata.size - sent - filled)) throw invalid10();
3718
+ if (value2.done || !(value2.value instanceof Uint8Array) || (chunk = value2.value, chunk.byteLength > metadata.size - sent - filled)) throw invalid11();
3597
3719
  }
3598
3720
  let take = Math.min(length - filled, chunk.byteLength - offset);
3599
3721
  part.set(chunk.subarray(offset, offset + take), filled), filled += take, offset += take, offset === chunk.byteLength && (chunk = void 0, offset = 0);
3600
3722
  }
3601
3723
  }
3602
- if (part.byteLength !== length) throw invalid10();
3724
+ if (part.byteLength !== length) throw invalid11();
3603
3725
  if (reader && sent + length === metadata.size)
3604
3726
  for (lastProgress = Date.now(); ; ) {
3605
3727
  let value2 = await next();
3606
3728
  if (value2.done) break;
3607
- if (!(value2.value instanceof Uint8Array) || value2.value.byteLength) throw invalid10();
3729
+ if (!(value2.value instanceof Uint8Array) || value2.value.byteLength) throw invalid11();
3608
3730
  }
3609
3731
  let value = await request3((signal) => exchange(`${route}/part`, {
3610
3732
  method: "POST",
@@ -3618,7 +3740,7 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
3618
3740
  }
3619
3741
  if (upload) for (let name2 of Object.keys(upload.file.enrichments)) {
3620
3742
  let bytes = await request3(() => upload.enrichment(name2));
3621
- if (bytes.byteLength !== upload.file.enrichments[name2].size || bytes.byteLength > MAX_BYTES) throw invalid10();
3743
+ if (bytes.byteLength !== upload.file.enrichments[name2].size || bytes.byteLength > MAX_BYTES) throw invalid11();
3622
3744
  await request3((signal) => exchange(`${route}/enrichments/${encodeURIComponent(name2)}`, {
3623
3745
  method: "POST",
3624
3746
  headers: { "content-type": "application/octet-stream", "x-os-transfer": ticket },
@@ -3660,7 +3782,7 @@ async function operation(work, initial, parent) {
3660
3782
  function contentPath(id3, name2) {
3661
3783
  let path = idPath(id3);
3662
3784
  if (name2 === void 0) return `${path}/content`;
3663
- if (!safeEnrichmentName(name2)) throw invalid10();
3785
+ if (!safeEnrichmentName(name2)) throw invalid11();
3664
3786
  return `${path}/enrichments/${encodeURIComponent(name2)}/content`;
3665
3787
  }
3666
3788
  async function read(id3, names) {
@@ -3669,12 +3791,12 @@ async function read(id3, names) {
3669
3791
  let path = contentPath(id3, names);
3670
3792
  return operation((context2, signal) => send(path, { method: "GET" }, !1, context2, signal), context);
3671
3793
  }
3672
- if (!Array.isArray(names)) throw invalid10();
3794
+ if (!Array.isArray(names)) throw invalid11();
3673
3795
  let distinct = [], seen = /* @__PURE__ */ new Set();
3674
3796
  for (let name2 of names) {
3675
- if (typeof name2 != "string" || !safeEnrichmentName(name2)) throw invalid10();
3797
+ if (typeof name2 != "string" || !safeEnrichmentName(name2)) throw invalid11();
3676
3798
  if (!seen.has(name2)) {
3677
- if (seen.size === 16) throw invalid10();
3799
+ if (seen.size === 16) throw invalid11();
3678
3800
  seen.add(name2), distinct.push(name2);
3679
3801
  }
3680
3802
  }
@@ -3706,9 +3828,9 @@ var files = {
3706
3828
  async create(input, options) {
3707
3829
  let context = await resolveFilesContext();
3708
3830
  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")))
3709
- throw invalid10();
3831
+ throw invalid11();
3710
3832
  let blob = input.file instanceof Blob, array3 = input.file instanceof Uint8Array, stream = input.file instanceof ReadableStream;
3711
- if (!blob && !array3 && !stream) throw invalid10();
3833
+ if (!blob && !array3 && !stream) throw invalid11();
3712
3834
  let intrinsic = blob ? input.file.size : array3 ? input.file.byteLength : void 0;
3713
3835
  if (intrinsic !== void 0 && input.size !== void 0 && input.size !== intrinsic)
3714
3836
  throw !Number.isSafeInteger(input.size) || input.size < 0 ? new FileOperationError("invalid_input", 400, !1, { reason: "invalid_size" }) : new FileOperationError(
@@ -3729,7 +3851,7 @@ var files = {
3729
3851
  }, FILE_ORIGINAL_MAX_BYTES);
3730
3852
  if (!context.local && !context.localFiles && metadata.storage === "local") throw new FileOperationError("unsupported_context", 400);
3731
3853
  let header = encodeURIComponent(JSON.stringify(metadata));
3732
- if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid10();
3854
+ if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid11();
3733
3855
  let release = await acquireSlot(context.signal);
3734
3856
  if (context.localFiles && !routineTransport() && metadata.size > MAX_BYTES)
3735
3857
  try {
@@ -3778,7 +3900,7 @@ var files = {
3778
3900
  },
3779
3901
  async enrich(input) {
3780
3902
  let context = await resolveFilesContext();
3781
- 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 invalid10();
3903
+ if (!input || typeof input != "object" || Array.isArray(input) || Object.keys(input).some((key) => !["file", "name", "content", "mediaType", "replace"].includes(key)) || typeof input.content != "string" && !(input.content instanceof Uint8Array)) throw invalid11();
3782
3904
  let path = `${idPath(input.file)}/enrichments`;
3783
3905
  if (typeof input.content == "string" ? input.content.length > MAX_BYTES : input.content.byteLength > MAX_BYTES)
3784
3906
  throw new FileOperationError("request_too_large", 413);
@@ -3795,7 +3917,7 @@ var files = {
3795
3917
  ...input.mediaType === void 0 ? {} : { mediaType: input.mediaType },
3796
3918
  ...input.replace === void 0 ? {} : { replace: input.replace }
3797
3919
  }, MAX_BYTES), header = encodeURIComponent(JSON.stringify(metadata));
3798
- if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid10();
3920
+ if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid11();
3799
3921
  let result2 = await send(path, { method: "POST", headers: {
3800
3922
  "content-type": "application/octet-stream",
3801
3923
  "x-os-enrichment": header
@@ -3905,17 +4027,17 @@ var recordId = (v) => typeof v == "string" && /^rec[A-Za-z0-9]+$/.test(v), table
3905
4027
  function fail5(message2) {
3906
4028
  throw new AirtableOperationError(message2);
3907
4029
  }
3908
- function object6(v) {
4030
+ function object7(v) {
3909
4031
  return (!v || typeof v != "object" || Array.isArray(v) || ![null, Object.prototype].includes(Object.getPrototypeOf(v))) && fail5("Invalid Airtable data"), v;
3910
4032
  }
3911
- function keys4(v, allowed, required = allowed) {
4033
+ function keys5(v, allowed, required = allowed) {
3912
4034
  (Object.keys(v).some((k) => !allowed.includes(k)) || required.some((k) => !Object.hasOwn(v, k))) && fail5("Invalid Airtable input");
3913
4035
  }
3914
4036
  function text3(v) {
3915
4037
  return typeof v == "string" && v.length > 0 && v.length <= 1024;
3916
4038
  }
3917
4039
  function fields3(v, nonempty = !1) {
3918
- let result2 = object6(v);
4040
+ let result2 = object7(v);
3919
4041
  (nonempty && !Object.keys(result2).length || Object.keys(result2).some((k) => !text3(k))) && fail5("Invalid Airtable fields");
3920
4042
  try {
3921
4043
  return serializable(result2);
@@ -3924,7 +4046,7 @@ function fields3(v, nonempty = !1) {
3924
4046
  }
3925
4047
  }
3926
4048
  function record2(v) {
3927
- let r = object6(v);
4049
+ let r = object7(v);
3928
4050
  return (!recordId(r.id) || r.createdTime !== void 0 && (typeof r.createdTime != "string" || !Number.isFinite(Date.parse(r.createdTime)))) && fail5("Malformed Airtable record"), { id: r.id, ...r.createdTime === void 0 ? {} : { createdTime: r.createdTime }, fields: fields3(r.fields) };
3929
4051
  }
3930
4052
  function equal(a, b) {
@@ -3959,7 +4081,7 @@ async function executeAirtableOperation(authority2, operation2, raw, options = {
3959
4081
  (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(name2) || !/^app[A-Za-z0-9]+$/.test(baseId) || !/^[A-Za-z0-9._~+/-]{1,8192}={0,2}$/.test(accessToken)) && fail5("Airtable connection unavailable");
3960
4082
  let input;
3961
4083
  try {
3962
- input = object6(serializable(raw));
4084
+ input = object7(serializable(raw));
3963
4085
  } catch {
3964
4086
  return fail5("Invalid Airtable input");
3965
4087
  }
@@ -3988,7 +4110,7 @@ async function executeAirtableOperation(authority2, operation2, raw, options = {
3988
4110
  }), new AirtableOperationError("Airtable request rejected", write && (response2.status >= 500 || response2.status === 408 || response2.status < 400) ? "uncertain" : "unapplied");
3989
4111
  try {
3990
4112
  if (!response2.headers.get("content-type")?.toLowerCase().includes("application/json")) throw new Error();
3991
- let value = object6(await response2.json()), safe = serializable(value);
4113
+ let value = object7(await response2.json()), safe = serializable(value);
3992
4114
  if (Object.hasOwn(value, "error") || JSON.stringify(safe).includes(accessToken)) throw new Error();
3993
4115
  return value;
3994
4116
  } catch {
@@ -3996,16 +4118,16 @@ async function executeAirtableOperation(authority2, operation2, raw, options = {
3996
4118
  }
3997
4119
  }
3998
4120
  if (operation2 === "tables.list") {
3999
- keys4(input, []);
4121
+ keys5(input, []);
4000
4122
  let tables = [], seen = /* @__PURE__ */ new Set(), offset;
4001
4123
  do {
4002
4124
  let query2 = new URLSearchParams(offset ? { offset } : {}), page = await request3(`meta/bases/${baseId}/tables?${query2}`);
4003
4125
  Array.isArray(page.tables) || fail5("Malformed Airtable tables");
4004
4126
  for (let value of page.tables) {
4005
- let t = object6(value);
4127
+ let t = object7(value);
4006
4128
  (!tableId(t.id) || !text3(t.name) || !text3(t.primaryFieldId) || !Array.isArray(t.fields) || tables.some((existing) => existing.id === t.id)) && fail5("Malformed Airtable table");
4007
4129
  let metadata = t.fields.map((value2) => {
4008
- let f = object6(value2);
4130
+ let f = object7(value2);
4009
4131
  return (typeof f.id != "string" || !/^fld[A-Za-z0-9]+$/.test(f.id) || !text3(f.name) || !text3(f.type)) && fail5("Malformed Airtable field"), { id: f.id, name: f.name, type: f.type, ...f.options === void 0 ? {} : { options: serializable(f.options) } };
4010
4132
  });
4011
4133
  (!metadata.some((f) => f.id === t.primaryFieldId) || new Set(metadata.map((f) => f.id)).size !== metadata.length) && fail5("Malformed Airtable fields"), tables.push({ id: t.id, name: t.name, primaryFieldId: t.primaryFieldId, fields: metadata });
@@ -4017,12 +4139,12 @@ async function executeAirtableOperation(authority2, operation2, raw, options = {
4017
4139
  (!text3(input.table) || input.table === "." || input.table === "..") && fail5("Invalid Airtable table"), mutation && !tableId(input.table) && fail5("Airtable writes require a stable table ID");
4018
4140
  let path = `${baseId}/${encodeURIComponent(input.table)}`;
4019
4141
  if (operation2 === "records.get") {
4020
- keys4(input, ["table", "id"]), recordId(input.id) || fail5("Invalid Airtable record ID");
4142
+ keys5(input, ["table", "id"]), recordId(input.id) || fail5("Invalid Airtable record ID");
4021
4143
  let result3 = record2(await request3(`${path}/${input.id}`));
4022
4144
  return result3.id !== input.id && fail5("Malformed Airtable record"), result3;
4023
4145
  }
4024
4146
  if (operation2 === "records.list") {
4025
- keys4(input, ["table", "fields"], ["table"]), input.fields !== void 0 && (!Array.isArray(input.fields) || !input.fields.length || input.fields.some((f) => !text3(f)) || new Set(input.fields).size !== input.fields.length) && fail5("Invalid Airtable field selection");
4147
+ keys5(input, ["table", "fields"], ["table"]), input.fields !== void 0 && (!Array.isArray(input.fields) || !input.fields.length || input.fields.some((f) => !text3(f)) || new Set(input.fields).size !== input.fields.length) && fail5("Invalid Airtable field selection");
4026
4148
  let records2 = [], ids2 = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set(), offset;
4027
4149
  do {
4028
4150
  let query2 = new URLSearchParams();
@@ -4038,10 +4160,10 @@ async function executeAirtableOperation(authority2, operation2, raw, options = {
4038
4160
  } while (offset);
4039
4161
  return records2;
4040
4162
  }
4041
- mutation || fail5("Unsupported Airtable operation"), keys4(input, ["table", "records"]), (!Array.isArray(input.records) || !input.records.length || input.records.length > 10) && fail5("Invalid Airtable batch");
4163
+ mutation || fail5("Unsupported Airtable operation"), keys5(input, ["table", "records"]), (!Array.isArray(input.records) || !input.records.length || input.records.length > 10) && fail5("Invalid Airtable batch");
4042
4164
  let kind = operation2.slice(8), ids = /* @__PURE__ */ new Set(), records = input.records.map((value) => {
4043
- let r = object6(value);
4044
- if (keys4(r, kind === "create" ? ["fields"] : kind === "update" ? ["id", "expected", "set"] : ["id", "expected"]), kind === "create") return { fields: fields3(r.fields, !0) };
4165
+ let r = object7(value);
4166
+ if (keys5(r, kind === "create" ? ["fields"] : kind === "update" ? ["id", "expected", "set"] : ["id", "expected"]), kind === "create") return { fields: fields3(r.fields, !0) };
4045
4167
  (!recordId(r.id) || ids.has(r.id)) && fail5("Invalid Airtable batch record ID"), ids.add(r.id);
4046
4168
  let set = kind === "update" ? fields3(r.set, !0) : void 0;
4047
4169
  return set && Object.values(set).some((value2) => value2 === null) && fail5("Airtable guard null cannot be an update value"), { id: r.id, expected: fields3(r.expected), ...set ? { set } : {} };
@@ -4063,7 +4185,7 @@ async function executeAirtableOperation(authority2, operation2, raw, options = {
4063
4185
  try {
4064
4186
  if (!Array.isArray(result2.records)) throw new Error();
4065
4187
  for (let value of result2.records) {
4066
- let r = object6(value);
4188
+ let r = object7(value);
4067
4189
  if (!recordId(r.id) || acknowledged.includes(r.id) || kind !== "create" && !ids.has(r.id) || kind === "delete" && r.deleted !== !0) throw new Error();
4068
4190
  acknowledged.push(r.id), kind !== "delete" && returned.push(record2(r));
4069
4191
  }
@@ -4324,8 +4446,8 @@ var InboxOperationError = class extends Error {
4324
4446
  reason;
4325
4447
  };
4326
4448
  function parseQuestionAvailability(value, available = !1) {
4327
- let state = object7(value);
4328
- return keys5(state, ["unavailableReason"], []), "unavailableReason" in state ? (assert(!available && state.unavailableReason === "handler_unavailable"), { unavailableReason: state.unavailableReason }) : {};
4449
+ let state = object8(value);
4450
+ return keys6(state, ["unavailableReason"], []), "unavailableReason" in state ? (assert(!available && state.unavailableReason === "handler_unavailable"), { unavailableReason: state.unavailableReason }) : {};
4329
4451
  }
4330
4452
  function questionAvailability(value, available = !1) {
4331
4453
  return parseQuestionAvailability({
@@ -4334,9 +4456,9 @@ function questionAvailability(value, available = !1) {
4334
4456
  }
4335
4457
  function parseInboxUnavailableFailure(value, status) {
4336
4458
  try {
4337
- let envelope = object7(value);
4459
+ let envelope = object8(value);
4338
4460
  if (status === 409) {
4339
- keys5(envelope, ["error"]);
4461
+ keys6(envelope, ["error"]);
4340
4462
  for (let reason of ["action_processing", "action_failed"]) {
4341
4463
  let error = new InboxOperationError(409, reason);
4342
4464
  if (envelope.error === error.message) return error;
@@ -4344,7 +4466,7 @@ function parseInboxUnavailableFailure(value, status) {
4344
4466
  return;
4345
4467
  }
4346
4468
  if (status !== 503) return;
4347
- keys5(envelope, ["error", "unavailableReason"], ["error", "unavailableReason"]), assert(text4(envelope.error));
4469
+ keys6(envelope, ["error", "unavailableReason"], ["error", "unavailableReason"]), assert(text4(envelope.error));
4348
4470
  let state = questionAvailability(envelope);
4349
4471
  return new InboxOperationError(503, state.unavailableReason);
4350
4472
  } catch {
@@ -4373,13 +4495,13 @@ var operations = {
4373
4495
  function assert(value) {
4374
4496
  if (!value) throw new Error("Invalid Inbox result");
4375
4497
  }
4376
- function object7(value) {
4498
+ function object8(value) {
4377
4499
  return assert(value && typeof value == "object" && !Array.isArray(value) && [Object.prototype, null].includes(Object.getPrototypeOf(value)) && Reflect.ownKeys(value).every((key) => {
4378
4500
  let descriptor = typeof key == "string" ? Object.getOwnPropertyDescriptor(value, key) : void 0;
4379
4501
  return !!descriptor?.enumerable && "value" in descriptor;
4380
4502
  })), value;
4381
4503
  }
4382
- function keys5(value, allowed, required = allowed) {
4504
+ function keys6(value, allowed, required = allowed) {
4383
4505
  assert(Object.keys(value).every((key) => allowed.includes(key)) && required.every((key) => Object.hasOwn(value, key)));
4384
4506
  }
4385
4507
  function text4(value, empty2 = !1) {
@@ -4403,69 +4525,69 @@ function array2(value) {
4403
4525
  return !!descriptor?.enumerable && "value" in descriptor;
4404
4526
  })), value;
4405
4527
  }
4406
- function json(value, ancestors = /* @__PURE__ */ new Set()) {
4528
+ function json2(value, ancestors = /* @__PURE__ */ new Set()) {
4407
4529
  if (value === null || typeof value == "boolean" || typeof value == "string" || typeof value == "number" && Number.isFinite(value)) return value;
4408
4530
  assert(value && typeof value == "object" && !ancestors.has(value)), ancestors.add(value);
4409
4531
  try {
4410
- return Array.isArray(value) ? array2(value).map((entry) => json(entry, ancestors)) : Object.fromEntries(Object.entries(object7(value)).map(([key, entry]) => [key, json(entry, ancestors)]));
4532
+ return Array.isArray(value) ? array2(value).map((entry) => json2(entry, ancestors)) : Object.fromEntries(Object.entries(object8(value)).map(([key, entry]) => [key, json2(entry, ancestors)]));
4411
4533
  } finally {
4412
4534
  ancestors.delete(value);
4413
4535
  }
4414
4536
  }
4415
4537
  function recordReference(value) {
4416
- let record4 = object7(value);
4417
- return keys5(record4, ["repository", "ref"]), assert(text4(record4.repository) && record4.repository === record4.repository.trim() && /^[a-z0-9][a-z0-9._/-]{0,127}$/.test(record4.repository) && !/\.\.|\/\//.test(record4.repository) && text4(record4.ref) && record4.ref === record4.ref.trim() && record4.ref.length <= 512 && /^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(record4.ref)), record4;
4538
+ let record4 = object8(value);
4539
+ return keys6(record4, ["repository", "ref"]), assert(text4(record4.repository) && record4.repository === record4.repository.trim() && /^[a-z0-9][a-z0-9._/-]{0,127}$/.test(record4.repository) && !/\.\.|\/\//.test(record4.repository) && text4(record4.ref) && record4.ref === record4.ref.trim() && record4.ref.length <= 512 && /^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(record4.ref)), record4;
4418
4540
  }
4419
4541
  function responseDefinition(value) {
4420
- let definition = object7(value);
4421
- keys5(definition, ["type", "source"]), assert(definition.type === "selection");
4422
- let source2 = object7(definition.source);
4542
+ let definition = object8(value);
4543
+ keys6(definition, ["type", "source"]), assert(definition.type === "selection");
4544
+ let source2 = object8(definition.source);
4423
4545
  if (source2.type === "authored") {
4424
- keys5(source2, ["type", "options", "suggestions", "search"], ["type", "options"]);
4546
+ keys6(source2, ["type", "options", "suggestions", "search"], ["type", "options"]);
4425
4547
  let options = array2(source2.options);
4426
4548
  assert(options.length > 0);
4427
4549
  let values = options.map((value2) => {
4428
- let option = object7(value2);
4429
- if (keys5(option, ["value", "label", "description", "note"], ["value", "label"]), assert(text4(option.value) && option.value === option.value.trim() && text4(option.label)), "description" in option && assert(text4(option.description)), "note" in option) {
4430
- let note = object7(option.note);
4431
- keys5(note, ["placeholder"]), assert(text4(note.placeholder));
4550
+ let option = object8(value2);
4551
+ if (keys6(option, ["value", "label", "description", "note"], ["value", "label"]), assert(text4(option.value) && option.value === option.value.trim() && text4(option.label)), "description" in option && assert(text4(option.description)), "note" in option) {
4552
+ let note = object8(option.note);
4553
+ keys6(note, ["placeholder"]), assert(text4(note.placeholder));
4432
4554
  }
4433
4555
  return option.value;
4434
4556
  });
4435
4557
  if (assert(new Set(values).size === values.length), "search" in source2 || "suggestions" in source2) {
4436
- let search = object7(source2.search);
4437
- keys5(search, ["triggerLabel", "placeholder", "emptyLabel"]), assert(text4(search.triggerLabel) && text4(search.placeholder) && text4(search.emptyLabel));
4558
+ let search = object8(source2.search);
4559
+ keys6(search, ["triggerLabel", "placeholder", "emptyLabel"]), assert(text4(search.triggerLabel) && text4(search.placeholder) && text4(search.emptyLabel));
4438
4560
  let suggestions2 = array2(source2.suggestions);
4439
4561
  assert(suggestions2.length <= 8 && suggestions2.every((value2) => text4(value2) && values.includes(value2)) && new Set(suggestions2).size === suggestions2.length);
4440
4562
  } else assert(options.length <= 9);
4441
4563
  return;
4442
4564
  }
4443
- assert(source2.type === "records"), keys5(source2, ["type", "collection", "refPrefix", "where", "display", "suggestions"], ["type", "collection", "display"]);
4444
- let collection = object7(source2.collection);
4445
- keys5(collection, ["repository", "name"]), recordReference({ repository: collection.repository, ref: "records/example" }), assert(text4(collection.name) && /^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(collection.name)), "refPrefix" in source2 && assert(text4(source2.refPrefix) && source2.refPrefix.length <= 512 && /^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)*\/$/.test(source2.refPrefix));
4446
- let where = object7(source2.where ?? {});
4565
+ assert(source2.type === "records"), keys6(source2, ["type", "collection", "refPrefix", "where", "display", "suggestions"], ["type", "collection", "display"]);
4566
+ let collection = object8(source2.collection);
4567
+ keys6(collection, ["repository", "name"]), recordReference({ repository: collection.repository, ref: "records/example" }), assert(text4(collection.name) && /^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(collection.name)), "refPrefix" in source2 && assert(text4(source2.refPrefix) && source2.refPrefix.length <= 512 && /^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)*\/$/.test(source2.refPrefix));
4568
+ let where = object8(source2.where ?? {});
4447
4569
  assert(Object.entries(where).every(([name2, value2]) => /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name2) && !["constructor", "prototype"].includes(name2) && (value2 === null || typeof value2 == "string" || typeof value2 == "boolean" || typeof value2 == "number" && Number.isFinite(value2))));
4448
- let display = object7(source2.display);
4449
- keys5(display, ["labelFields"]);
4570
+ let display = object8(source2.display);
4571
+ keys6(display, ["labelFields"]);
4450
4572
  let labels = array2(display.labelFields);
4451
4573
  assert(labels.length > 0 && labels.length <= 2 && new Set(labels).size === labels.length && labels.every((value2) => text4(value2) && /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(value2)));
4452
4574
  let suggestions = array2(source2.suggestions ?? []), refs = suggestions.map((value2) => {
4453
- let suggestion = object7(value2);
4454
- keys5(suggestion, ["record", "reason"], ["record"]);
4575
+ let suggestion = object8(value2);
4576
+ keys6(suggestion, ["record", "reason"], ["record"]);
4455
4577
  let record4 = recordReference(suggestion.record);
4456
4578
  return assert(record4.repository === collection.repository), "reason" in suggestion && assert(text4(suggestion.reason)), record4.ref;
4457
4579
  });
4458
4580
  assert(suggestions.length <= 8 && new Set(refs).size === refs.length);
4459
4581
  }
4460
4582
  function response(value) {
4461
- let answer = object7(value);
4583
+ let answer = object8(value);
4462
4584
  return assert(Object.keys(answer).every((key) => ["selection", "note"].includes(key))), typeof answer.selection == "string" ? assert(text4(answer.selection) && answer.selection === answer.selection.trim()) : recordReference(answer.selection), Object.hasOwn(answer, "note") && assert(text4(answer.note)), answer;
4463
4585
  }
4464
4586
  function parseInboxRequest(value) {
4465
4587
  try {
4466
- let envelope = object7(value);
4588
+ let envelope = object8(value);
4467
4589
  assert(Object.keys(envelope).sort().join(",") === "input,operation"), assert(typeof envelope.operation == "string" && Object.hasOwn(operations, envelope.operation));
4468
- let operation2 = envelope.operation, input = { ...object7(envelope.input) }, required = operations[operation2];
4590
+ let operation2 = envelope.operation, input = { ...object8(envelope.input) }, required = operations[operation2];
4469
4591
  assert(required.every((key) => Object.hasOwn(input, key)) && Object.keys(input).every((key) => required.includes(key) || operation2 === "questions.answer" && key === "label" || operation2 === "questions.searchRecords" && key === "selected" || (operation2 === "items.list" || operation2 === "questions.list") && key === "beforeNumber" || operation2 === "questions.list" && key === "routines")), operation2 === "questions.list" && (assert(Object.hasOwn(input, "routines")), assert(array2(input.routines).every(isAppRoutineName)));
4470
4592
  for (let key of ["itemId", "personId", "fileId"]) key in input && assert(id2(input[key]));
4471
4593
  return "revision" in input && assert(integer(input.revision)), "beforeNumber" in input && assert(integer(input.beforeNumber)), "questionId" in input && assert(text4(input.questionId) && input.questionId === input.questionId.trim()), "title" in input && assert(text4(input.title)), "lifecycle" in input && assert(input.lifecycle === "open" || input.lifecycle === "closed"), "query" in input && assert(text4(input.query, !0) && input.query.length <= 256), "records" in input && (input.records = parseInboxRecordRefs(input.records)), "selected" in input && recordReference(input.selected), "response" in input && response(input.response), "label" in input && assert(text4(input.label) && typeof input.response?.selection == "object"), assert(new TextEncoder().encode(JSON.stringify(envelope)).byteLength <= INBOX_INPUT_BYTES), "routines" in input && (input.routines = [...new Set(input.routines)]), { operation: operation2, input };
@@ -4474,54 +4596,54 @@ function parseInboxRequest(value) {
4474
4596
  }
4475
4597
  }
4476
4598
  function parseInboxCurrent(value) {
4477
- let current2 = object7(value), workspace = object7(current2.workspace), viewer = object7(current2.viewer);
4599
+ let current2 = object8(value), workspace = object8(current2.workspace), viewer = object8(current2.viewer);
4478
4600
  return assert(id2(workspace.id) && text4(workspace.slug) && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(workspace.slug) && text4(workspace.name) && text4(workspace.locale) && text4(workspace.timezone)), assert(id2(viewer.id) && text4(viewer.name) && text4(viewer.email)), {
4479
4601
  workspace: { id: workspace.id, slug: workspace.slug, name: workspace.name, locale: workspace.locale, timezone: workspace.timezone },
4480
4602
  viewer: { id: viewer.id, name: viewer.name, email: viewer.email }
4481
4603
  };
4482
4604
  }
4483
4605
  function parseInboxItem(value) {
4484
- let item = object7(json(value));
4485
- return assert(id2(item.id) && id2(item.workspaceId) && integer(item.number) && integer(item.revision) && integer(item.activityVersion, 0) && ["ask", "digest"].includes(String(item.kind)) && ["open", "closed"].includes(String(item.lifecycle)) && text4(item.title) && text4(item.description, !0) && text4(item.author) && date(item.publishedAt) && optionalDate(item.seenAt) && optionalDate(item.digestReadAt)), item.outcome !== null && assert(text4(object7(item.outcome).outcome)), "canonicalRoutineId" in item && assert(item.canonicalRoutineId === null || isAppRoutineName(item.canonicalRoutineId)), item.kind === "ask" ? askMetadata(item) : assert(!("tags" in item) && !("recordRefs" in item)), array2(item.body).forEach(validateBlock), array2(item.views).forEach((value2) => {
4486
- let view = object7(value2);
4487
- assert(text4(view.id) && text4(view.view) && text4(view.implementation)), json(view.input);
4606
+ let item = object8(json2(value));
4607
+ return assert(id2(item.id) && id2(item.workspaceId) && integer(item.number) && integer(item.revision) && integer(item.activityVersion, 0) && ["ask", "digest"].includes(String(item.kind)) && ["open", "closed"].includes(String(item.lifecycle)) && text4(item.title) && text4(item.description, !0) && text4(item.author) && date(item.publishedAt) && optionalDate(item.seenAt) && optionalDate(item.digestReadAt)), item.outcome !== null && assert(text4(object8(item.outcome).outcome)), "canonicalRoutineId" in item && assert(item.canonicalRoutineId === null || isAppRoutineName(item.canonicalRoutineId)), item.kind === "ask" ? askMetadata(item) : assert(!("tags" in item) && !("recordRefs" in item)), array2(item.body).forEach(validateBlock), array2(item.views).forEach((value2) => {
4608
+ let view = object8(value2);
4609
+ assert(text4(view.id) && text4(view.view) && text4(view.implementation)), json2(view.input);
4488
4610
  }), array2(item.people).forEach((value2) => {
4489
- let person = object7(value2);
4611
+ let person = object8(value2);
4490
4612
  assert(id2(person.id) && text4(person.name));
4491
4613
  }), array2(item.questions).forEach((value2) => {
4492
- let question2 = object7(value2);
4614
+ let question2 = object8(value2);
4493
4615
  if (assert(text4(question2.id) && id2(question2.to) && text4(question2.prompt) && (question2.instructions === null || text4(question2.instructions, !0)) && typeof question2.available == "boolean"), questionAvailability(question2, question2.available), assert(!("requirements" in question2) && !("requirementsRepository" in question2) && !("handler" in question2)), responseDefinition(question2.response), assert(array2(question2.allowedResponders).every(id2)), question2.acceptedResponse !== null) {
4494
- let accepted = object7(question2.acceptedResponse);
4616
+ let accepted = object8(question2.acceptedResponse);
4495
4617
  assert(id2(accepted.id) && id2(accepted.userId) && date(accepted.acceptedAt)), response(accepted.response), accepted.label === null ? delete accepted.label : "label" in accepted && assert(text4(accepted.label)), "acceptanceOrder" in accepted && assert(integer(accepted.acceptanceOrder));
4496
4618
  }
4497
4619
  if (question2.execution !== null) {
4498
- let execution = object7(question2.execution);
4620
+ let execution = object8(question2.execution);
4499
4621
  if (assert(id2(execution.id) && ["pending", "running", "completed", "failed"].includes(String(execution.state)) && integer(execution.attempt, 0)), "consequence" in execution) {
4500
- let consequence = object7(execution.consequence);
4622
+ let consequence = object8(execution.consequence);
4501
4623
  assert(["pending", "running", "applied", "no-write", "stopped", "partial", "uncertain"].includes(String(consequence.state)) && (consequence.phase === null || ["loading", "invoking", "committing"].includes(String(consequence.phase))) && date(consequence.updatedAt) && typeof consequence.needsReconciliation == "boolean" && (consequence.reason === null || text4(consequence.reason, !0))), array2(consequence.evidence).forEach((value3) => {
4502
- let receipt = object7(value3);
4624
+ let receipt = object8(value3);
4503
4625
  assert(text4(receipt.repository) && text4(receipt.commit) && text4(receipt.diff, !0));
4504
4626
  });
4505
4627
  }
4506
4628
  }
4507
4629
  }), array2(item.linkedAsks).forEach((value2) => {
4508
- let linked = object7(value2);
4630
+ let linked = object8(value2);
4509
4631
  if (assert(id2(linked.id)), linked.state === "unavailable") assert(typeof linked.done == "boolean");
4510
4632
  else if (assert(["yours", "done", "open", "theirs"].includes(String(linked.state)) && text4(linked.title)), linked.state === "theirs") {
4511
- let assignee = object7(linked.assignee);
4633
+ let assignee = object8(linked.assignee);
4512
4634
  assert(id2(assignee.id) && text4(assignee.name));
4513
4635
  }
4514
4636
  }), array2(item.activity).forEach((value2) => {
4515
- let event = object7(value2);
4516
- assert(integer(event.id) && text4(event.type) && (event.actorId === null || id2(event.actorId)) && (event.questionId === null || text4(event.questionId)) && integer(event.revision) && date(event.createdAt)), object7(event.data);
4637
+ let event = object8(value2);
4638
+ assert(integer(event.id) && text4(event.type) && (event.actorId === null || id2(event.actorId)) && (event.questionId === null || text4(event.questionId)) && integer(event.revision) && date(event.createdAt)), object8(event.data);
4517
4639
  }), array2(item.work).forEach((value2) => {
4518
- let work = object7(value2);
4640
+ let work = object8(value2);
4519
4641
  assert(id2(work.id) && text4(work.questionId) && text4(work.reason) && optionalDate(work.settledAt));
4520
4642
  }), item;
4521
4643
  }
4522
4644
  function parseAnswerableQuestion(value) {
4523
- let entry = object7(json(value));
4524
- keys5(
4645
+ let entry = object8(json2(value));
4646
+ keys6(
4525
4647
  entry,
4526
4648
  ["itemId", "number", "revision", "title", "inboxUrl", "questionId", "routine", "prompt", "response", "answerable", "tags", "recordRefs", "instructions", "unavailableReason"],
4527
4649
  ["itemId", "number", "revision", "title", "inboxUrl", "questionId", "routine", "prompt", "response", "answerable"]
@@ -4534,29 +4656,29 @@ function askMetadata(entry) {
4534
4656
  assert(tags.length <= 32 && tags.every((tag) => text4(tag) && new TextEncoder().encode(tag).byteLength <= 64)), assert(new Set(tags).size === tags.length);
4535
4657
  let refs = array2(entry.recordRefs === void 0 ? [] : entry.recordRefs);
4536
4658
  refs.forEach((value) => {
4537
- let ref = object7(value);
4538
- keys5(ref, ["repository", "id"]), recordReference({ repository: ref.repository, ref: ref.id });
4659
+ let ref = object8(value);
4660
+ keys6(ref, ["repository", "id"]), recordReference({ repository: ref.repository, ref: ref.id });
4539
4661
  }), assert(new Set(refs.map((value) => {
4540
- let ref = object7(value);
4662
+ let ref = object8(value);
4541
4663
  return JSON.stringify([ref.repository, ref.id]);
4542
4664
  })).size === refs.length), entry.tags = tags, entry.recordRefs = refs;
4543
4665
  }
4544
4666
  function parseInboxAcceptance(value) {
4545
- let accepted = object7(value);
4667
+ let accepted = object8(value);
4546
4668
  return assert(id2(accepted.responseId) && date(accepted.acceptedAt)), "executionId" in accepted && assert(id2(accepted.executionId)), "acceptanceOrder" in accepted && assert(integer(accepted.acceptanceOrder)), "label" in accepted && assert(text4(accepted.label)), accepted;
4547
4669
  }
4548
4670
  function parseInboxResult(operation2, value) {
4549
4671
  if (operation2 === "current") return parseInboxCurrent(value);
4550
4672
  if (operation2 === "questions.list") {
4551
- let page = object7(value);
4552
- keys5(page, ["questions", "nextBeforeNumber"]);
4673
+ let page = object8(value);
4674
+ keys6(page, ["questions", "nextBeforeNumber"]);
4553
4675
  let questions = array2(page.questions).map(parseAnswerableQuestion);
4554
4676
  return assert(page.nextBeforeNumber === null || integer(page.nextBeforeNumber)), { questions, nextBeforeNumber: page.nextBeforeNumber };
4555
4677
  }
4556
4678
  if (operation2 === "items.readRecords") return parseInboxRecords(value);
4557
4679
  if (operation2 === "items.read") return parseInboxItem(value);
4558
4680
  if (operation2 === "items.list") {
4559
- let page = object7(value), items = array2(page.items).map(parseInboxItem);
4681
+ let page = object8(value), items = array2(page.items).map(parseInboxItem);
4560
4682
  return assert(items.length <= 100 && (page.nextBeforeNumber === null || integer(page.nextBeforeNumber))), { items, nextBeforeNumber: page.nextBeforeNumber };
4561
4683
  }
4562
4684
  if (operation2 === "items.see") {
@@ -4564,30 +4686,30 @@ function parseInboxResult(operation2, value) {
4564
4686
  return;
4565
4687
  }
4566
4688
  if (operation2 === "items.markDigestRead") {
4567
- let read2 = object7(value);
4689
+ let read2 = object8(value);
4568
4690
  return assert(integer(read2.activityId) && date(read2.readAt)), read2;
4569
4691
  }
4570
4692
  if (operation2 === "items.rename" || operation2 === "items.setLifecycle") {
4571
- let update = object7(value), item = parseInboxItem(update.item);
4693
+ let update = object8(value), item = parseInboxItem(update.item);
4572
4694
  return assert((update.activityId === null || integer(update.activityId)) && optionalDate(update.changedAt)), { ...update, item };
4573
4695
  }
4574
4696
  if (operation2 === "items.listRecipientCandidates") {
4575
4697
  let candidates = array2(value);
4576
4698
  return candidates.forEach((value2) => {
4577
- let person = object7(value2);
4699
+ let person = object8(value2);
4578
4700
  assert(id2(person.id) && text4(person.name) && text4(person.email));
4579
- }), assert(new Set(candidates.map((value2) => object7(value2).id)).size === candidates.length), candidates;
4701
+ }), assert(new Set(candidates.map((value2) => object8(value2).id)).size === candidates.length), candidates;
4580
4702
  }
4581
4703
  if (operation2 === "items.addRecipient") {
4582
- let addition = object7(value), item = parseInboxItem(addition.item);
4704
+ let addition = object8(value), item = parseInboxItem(addition.item);
4583
4705
  return assert(id2(addition.addedPersonId) && item.people.some((person) => person.id === addition.addedPersonId)), { ...addition, item };
4584
4706
  }
4585
4707
  if (operation2 === "questions.answer") return parseInboxAcceptance(value);
4586
4708
  if (operation2 === "questions.searchRecords") {
4587
- let result2 = object7(value);
4709
+ let result2 = object8(value);
4588
4710
  assert(text4(result2.recordType) && integer(result2.eligibleCount, 0) && integer(result2.matchCount, 0) && Number(result2.matchCount) <= Number(result2.eligibleCount));
4589
4711
  let labeled = (value2) => {
4590
- let record4 = object7(value2);
4712
+ let record4 = object8(value2);
4591
4713
  recordReference({ repository: record4.repository, ref: record4.ref }), assert(text4(record4.label)), "reason" in record4 && assert(text4(record4.reason));
4592
4714
  };
4593
4715
  return array2(result2.matches).forEach(labeled), array2(result2.suggestions).forEach(labeled), "selected" in result2 && labeled(result2.selected), result2;
@@ -6020,9 +6142,9 @@ async function provider(configuration, guard) {
6020
6142
  let result2 = new Response(
6021
6143
  [204, 205, 304].includes(response2.status) ? null : body,
6022
6144
  { status: response2.status, statusText: response2.statusText, headers: response2.headers }
6023
- ), json2 = result2.json.bind(result2);
6145
+ ), json3 = result2.json.bind(result2);
6024
6146
  return result2.json = async () => {
6025
- let value = await json2();
6147
+ let value = await json3();
6026
6148
  return (!guard.current(revision) || !alive() || request3 && !request3.current()) && rejectStale(), value && typeof value.access_token == "string" && provenance.set(value.access_token, revision), value;
6027
6149
  }, result2;
6028
6150
  }, { preconnect: fetch.preconnect })
@@ -6141,29 +6263,29 @@ function routineRunHandle(operations2) {
6141
6263
  });
6142
6264
  }
6143
6265
 
6144
- 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}$/, invalid11 = () => {
6266
+ var name = /^[a-z0-9][a-z0-9-]{0,62}$/, uuid2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, invalid12 = () => {
6145
6267
  throw new Error("Run state unavailable");
6146
- }, record3 = (value) => value && typeof value == "object" && !Array.isArray(value) ? value : invalid11();
6147
- function time2(value) {
6148
- return typeof value != "string" || value.length > 40 || !Number.isFinite(Date.parse(value)) ? invalid11() : value;
6268
+ }, record3 = (value) => value && typeof value == "object" && !Array.isArray(value) ? value : invalid12();
6269
+ function time3(value) {
6270
+ return typeof value != "string" || value.length > 40 || !Number.isFinite(Date.parse(value)) ? invalid12() : value;
6149
6271
  }
6150
6272
  function times(value) {
6151
6273
  return {
6152
- ...value.startedAt === void 0 ? {} : { startedAt: time2(value.startedAt) },
6153
- ...value.finishedAt === void 0 ? {} : { finishedAt: time2(value.finishedAt) }
6274
+ ...value.startedAt === void 0 ? {} : { startedAt: time3(value.startedAt) },
6275
+ ...value.finishedAt === void 0 ? {} : { finishedAt: time3(value.finishedAt) }
6154
6276
  };
6155
6277
  }
6156
6278
  function bounded(value) {
6157
- return assertRoutineJson(value), new TextEncoder().encode(JSON.stringify(value)).byteLength > 256 * 1024 ? invalid11() : value;
6279
+ return assertRoutineJson(value), new TextEncoder().encode(JSON.stringify(value)).byteLength > 256 * 1024 ? invalid12() : value;
6158
6280
  }
6159
6281
  function progress(value) {
6160
6282
  if (value === void 0) return {};
6161
6283
  let v = record3(value);
6162
- return Object.keys(v).sort().join(",") !== "completed,total" || !Number.isSafeInteger(v.completed) || !Number.isSafeInteger(v.total) || v.completed < 1 || v.completed > v.total ? invalid11() : { progress: { completed: v.completed, total: v.total } };
6284
+ return Object.keys(v).sort().join(",") !== "completed,total" || !Number.isSafeInteger(v.completed) || !Number.isSafeInteger(v.total) || v.completed < 1 || v.completed > v.total ? invalid12() : { progress: { completed: v.completed, total: v.total } };
6163
6285
  }
6164
6286
  function parseRunStep(value, expected) {
6165
6287
  let v = record3(value);
6166
- if (typeof v.id != "string" || !name.test(v.id) || expected !== void 0 && v.id !== expected || typeof v.title != "string" || !v.title.trim() || v.title.length > 256 || !["pending", "running", "completed", "failed", "skipped"].includes(v.status)) return invalid11();
6288
+ if (typeof v.id != "string" || !name.test(v.id) || expected !== void 0 && v.id !== expected || typeof v.title != "string" || !v.title.trim() || v.title.length > 256 || !["pending", "running", "completed", "failed", "skipped"].includes(v.status)) return invalid12();
6167
6289
  let output = captureRetainedStepOutput(v.id, {
6168
6290
  ...Object.hasOwn(v, "summary") ? { summary: v.summary } : {},
6169
6291
  ...Object.hasOwn(v, "data") ? { data: v.data } : {}
@@ -6180,28 +6302,28 @@ function parseRunStep(value, expected) {
6180
6302
  }
6181
6303
  function parseRemoteRun(value, expected = {}) {
6182
6304
  let v = record3(value);
6183
- if (typeof v.id != "string" || !uuid2.test(v.id) || expected.id !== void 0 && v.id !== expected.id || typeof v.routine != "string" || !name.test(v.routine) || expected.routine !== void 0 && v.routine !== expected.routine || v.placement !== "remote" || !["queued", "running", "succeeded", "failed"].includes(v.status) || !Array.isArray(v.steps) || v.steps.length > 64) return invalid11();
6305
+ if (typeof v.id != "string" || !uuid2.test(v.id) || expected.id !== void 0 && v.id !== expected.id || typeof v.routine != "string" || !name.test(v.routine) || expected.routine !== void 0 && v.routine !== expected.routine || v.placement !== "remote" || !["queued", "running", "succeeded", "failed"].includes(v.status) || !Array.isArray(v.steps) || v.steps.length > 64) return invalid12();
6184
6306
  let steps = v.steps.map((value2) => {
6185
6307
  let step = record3(value2);
6186
- return typeof step.detailAvailable != "boolean" || Object.hasOwn(step, "data") ? invalid11() : { ...parseRunStep(step), detailAvailable: step.detailAvailable };
6308
+ return typeof step.detailAvailable != "boolean" || Object.hasOwn(step, "data") ? invalid12() : { ...parseRunStep(step), detailAvailable: step.detailAvailable };
6187
6309
  });
6188
- if (new Set(steps.map((step) => step.id)).size !== steps.length) return invalid11();
6310
+ if (new Set(steps.map((step) => step.id)).size !== steps.length) return invalid12();
6189
6311
  let failure;
6190
6312
  if (v.failure !== void 0) {
6191
6313
  let f = record3(v.failure);
6192
- if (v.status !== "failed" || typeof f.message != "string" || !f.message || f.message.length > 512) return invalid11();
6314
+ if (v.status !== "failed" || typeof f.message != "string" || !f.message || f.message.length > 512) return invalid12();
6193
6315
  if (f.code === "step_output_too_large") {
6194
6316
  let { code, message: message2, ...facts2 } = f, detail = parseRoutineStepOutputDetail(facts2);
6195
- if (!steps.some((step) => step.id === detail.step && step.status === "failed") || message2 !== routineStepOutputMessage(detail)) return invalid11();
6317
+ if (!steps.some((step) => step.id === detail.step && step.status === "failed") || message2 !== routineStepOutputMessage(detail)) return invalid12();
6196
6318
  failure = { code, message: message2, ...detail };
6197
6319
  } else failure = { message: f.message };
6198
6320
  }
6199
- return Object.hasOwn(v, "result") && v.status !== "succeeded" ? invalid11() : {
6321
+ return Object.hasOwn(v, "result") && v.status !== "succeeded" ? invalid12() : {
6200
6322
  id: v.id,
6201
6323
  routine: v.routine,
6202
6324
  placement: "remote",
6203
6325
  status: v.status,
6204
- createdAt: time2(v.createdAt),
6326
+ createdAt: time3(v.createdAt),
6205
6327
  ...times(v),
6206
6328
  steps,
6207
6329
  ...Object.hasOwn(v, "result") ? { result: bounded(v.result) } : {},
@@ -6331,10 +6453,10 @@ function validLocalActivity(value) {
6331
6453
  function jsonInput(value, ancestors = /* @__PURE__ */ new Set()) {
6332
6454
  if (value === null || typeof value == "string" || typeof value == "boolean" || typeof value == "number" && Number.isFinite(value)) return;
6333
6455
  if (!value || typeof value != "object" || ancestors.has(value)) return fail6("invalid_input");
6334
- let array3 = Array.isArray(value), keys6 = Reflect.ownKeys(value);
6335
- if (!array3 && ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || array3 && (keys6.length !== value.length + 1 || !Array.from({ length: value.length }, (_, index) => Object.hasOwn(value, index)).every(Boolean))) return fail6("invalid_input");
6456
+ let array3 = Array.isArray(value), keys7 = Reflect.ownKeys(value);
6457
+ if (!array3 && ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || array3 && (keys7.length !== value.length + 1 || !Array.from({ length: value.length }, (_, index) => Object.hasOwn(value, index)).every(Boolean))) return fail6("invalid_input");
6336
6458
  ancestors.add(value);
6337
- for (let key of keys6) {
6459
+ for (let key of keys7) {
6338
6460
  if (array3 && key === "length") continue;
6339
6461
  let descriptor = Object.getOwnPropertyDescriptor(value, key);
6340
6462
  if (typeof key != "string" || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) return fail6("invalid_input");