@oddington/sdk 0.1.54 → 0.1.56

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 invalid9 = () => {
100
+ let invalid12 = () => {
101
101
  throw new FileOperationError("unavailable", 503, !0);
102
102
  };
103
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid9();
103
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid12();
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 invalid9();
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();
106
106
  for (let [name2, descriptor] of Object.entries(f.enrichments)) {
107
- if (!safeEnrichmentName(name2)) return invalid9();
107
+ if (!safeEnrichmentName(name2)) return invalid12();
108
108
  parseEnrichmentDescriptor(descriptor);
109
109
  }
110
- return new TextEncoder().encode(JSON.stringify(f)).byteLength > 16 * 1024 ? invalid9() : f;
110
+ return new TextEncoder().encode(JSON.stringify(f)).byteLength > 16 * 1024 ? invalid12() : f;
111
111
  }
112
112
  function parseEnrichmentDescriptor(value) {
113
- let invalid9 = () => {
113
+ let invalid12 = () => {
114
114
  throw new FileOperationError("unavailable", 503, !0);
115
115
  };
116
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid9();
116
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid12();
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) ? invalid9() : 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) ? invalid12() : 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 invalid9 = (reason = "invalid_metadata") => {
124
+ let invalid12 = (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 invalid9();
127
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid12();
128
128
  let d = value;
129
- if (Object.keys(d).some((key) => !["name", "size", "mediaType", "replace"].includes(key))) return invalid9();
130
- if (!safeEnrichmentName(d.name)) return invalid9("invalid_enrichment_name");
131
- if (!Number.isSafeInteger(d.size) || d.size < 0) return invalid9("invalid_size");
132
- if (d.mediaType !== void 0 && (typeof d.mediaType != "string" || d.mediaType.length > 255 || /[\u0000-\u001f\u007f]/.test(d.mediaType))) return invalid9("invalid_media_type");
133
- if (d.replace !== void 0 && (typeof d.replace != "string" || !/^[0-9a-f]{64}$/.test(d.replace))) return invalid9("invalid_replacement");
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");
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 invalid9 = (reason = "invalid_metadata") => {
166
+ let invalid12 = (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 invalid9();
169
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid12();
170
170
  let input = value;
171
- if (Object.keys(input).some((key) => !["name", "path", "storage", "mediaType", "size", "requestKey"].includes(key))) return invalid9();
171
+ if (Object.keys(input).some((key) => !["name", "path", "storage", "mediaType", "size", "requestKey"].includes(key))) return invalid12();
172
172
  let path = input.path === void 0 ? "Files" : input.path;
173
- if (!safeFileName(input.name)) return invalid9("invalid_name");
174
- if (!safeManagedFilePath(path)) return invalid9("invalid_path");
175
- if (input.storage !== void 0 && input.storage !== "remote" && input.storage !== "local") return invalid9("invalid_storage");
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");
176
176
  let mediaType = input.mediaType === void 0 ? "application/octet-stream" : declaredOriginalMediaType(input.mediaType);
177
- if (!Number.isSafeInteger(input.size) || input.size < 0) return invalid9("invalid_size");
177
+ if (!Number.isSafeInteger(input.size) || input.size < 0) return invalid12("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) ? invalid9("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) ? invalid12("invalid_request_key") : {
185
185
  name: input.name,
186
186
  path,
187
187
  ...input.storage ? { storage: input.storage } : {},
@@ -280,39 +280,39 @@ function jsonData(value, ancestors = /* @__PURE__ */ new Set()) {
280
280
  function validateRoutineSchemaValue(schema2, value, rejected) {
281
281
  let type = (value2) => value2 === null ? "null" : Array.isArray(value2) ? "array" : ["object", "boolean", "string", "number"].includes(typeof value2) ? typeof value2 : "other";
282
282
  function check(schema3, value2, path) {
283
- let fail4 = (reason, extra = {}) => (rejected?.({ reason, path: path.length <= 256 ? path : "$", expected: schema3.type, received: type(value2), ...extra }), invalidValue());
283
+ let fail7 = (reason, extra = {}) => (rejected?.({ reason, path: path.length <= 256 ? path : "$", expected: schema3.type, received: type(value2), ...extra }), invalidValue());
284
284
  switch (schema3.type) {
285
285
  case "object":
286
- if (!record(value2)) return fail4("wrong_type");
287
- for (let key of schema3.required ?? []) if (!owns(value2, key)) return fail4("missing_field", {
286
+ if (!record(value2)) return fail7("wrong_type");
287
+ for (let key of schema3.required ?? []) if (!owns(value2, key)) return fail7("missing_field", {
288
288
  path: `${path}.${key}`.length <= 256 ? `${path}.${key}` : "$",
289
289
  expected: schema3.properties[key].type,
290
290
  received: "missing"
291
291
  });
292
- if (Object.keys(value2).some((key) => !owns(schema3.properties, key))) return fail4("unexpected_field");
292
+ if (Object.keys(value2).some((key) => !owns(schema3.properties, key))) return fail7("unexpected_field");
293
293
  for (let [key, child] of Object.entries(value2)) check(schema3.properties[key], child, `${path}.${key}`);
294
294
  return;
295
295
  case "array":
296
- if (!denseArray(value2)) return fail4("wrong_type");
296
+ if (!denseArray(value2)) return fail7("wrong_type");
297
297
  if (schema3.maxItems !== void 0 && value2.length > schema3.maxItems)
298
- return fail4("out_of_bounds", { constraint: "maxItems", limit: schema3.maxItems });
298
+ return fail7("out_of_bounds", { constraint: "maxItems", limit: schema3.maxItems });
299
299
  value2.forEach((child, index) => check(schema3.items, child, `${path}[${index}]`));
300
300
  return;
301
301
  case "boolean":
302
- return typeof value2 != "boolean" ? fail4("wrong_type") : void 0;
302
+ return typeof value2 != "boolean" ? fail7("wrong_type") : void 0;
303
303
  case "string":
304
- return typeof value2 != "string" ? fail4("wrong_type") : Array.from(value2).length > (schema3.maxLength ?? 4096) ? fail4("out_of_bounds", { constraint: "maxLength", limit: schema3.maxLength ?? 4096 }) : void 0;
304
+ return typeof value2 != "string" ? fail7("wrong_type") : Array.from(value2).length > (schema3.maxLength ?? 4096) ? fail7("out_of_bounds", { constraint: "maxLength", limit: schema3.maxLength ?? 4096 }) : void 0;
305
305
  case "integer":
306
306
  case "number":
307
- return typeof value2 != "number" || !(schema3.type === "integer" ? Number.isSafeInteger(value2) : Number.isFinite(value2)) ? fail4("wrong_type") : schema3.minimum !== void 0 && value2 < schema3.minimum ? fail4("out_of_bounds", { constraint: "minimum", limit: schema3.minimum }) : schema3.maximum !== void 0 && value2 > schema3.maximum ? fail4("out_of_bounds", { constraint: "maximum", limit: schema3.maximum }) : void 0;
307
+ return typeof value2 != "number" || !(schema3.type === "integer" ? Number.isSafeInteger(value2) : Number.isFinite(value2)) ? fail7("wrong_type") : schema3.minimum !== void 0 && value2 < schema3.minimum ? fail7("out_of_bounds", { constraint: "minimum", limit: schema3.minimum }) : schema3.maximum !== void 0 && value2 > schema3.maximum ? fail7("out_of_bounds", { constraint: "maximum", limit: schema3.maximum }) : void 0;
308
308
  case "file": {
309
309
  let file2;
310
310
  try {
311
311
  jsonData(value2), file2 = parseFileDescriptor(value2);
312
312
  } catch {
313
- return fail4("invalid_file");
313
+ return fail7("invalid_file");
314
314
  }
315
- if (schema3.path !== void 0 && file2.path !== schema3.path) return fail4("invalid_file");
315
+ if (schema3.path !== void 0 && file2.path !== schema3.path) return fail7("invalid_file");
316
316
  }
317
317
  }
318
318
  }
@@ -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 stable = (value2) => typeof value2 == "string" && /^[a-zA-Z0-9][a-zA-Z0-9_./-]{0,127}$/.test(value2);
600
- stable(source2.id) || fail("Handler ID must be stable");
599
+ let stable2 = (value2) => typeof value2 == "string" && /^[a-zA-Z0-9][a-zA-Z0-9_./-]{0,127}$/.test(value2);
600
+ stable2(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) => !stable(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) => !stable2(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 });
@@ -726,7 +726,7 @@ function createInboxPublisher(transport) {
726
726
  var ROUTINE_DECLARATION_SCHEMA = "https://schemas.oddington.ai/routine/v1.json", ROUTINE_SOURCE_LIMITS = { files: 2e4, bytes: 256 * 1024 * 1024, declarationBytes: 64 * 1024 };
727
727
  var invalid = (field) => {
728
728
  throw new Error(`Invalid routine declaration: ${field}`);
729
- }, object2 = (value, fields3, field) => ((!value || typeof value != "object" || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null || Reflect.ownKeys(value).some((key) => typeof key != "string" || !fields3.includes(key) || !Object.getOwnPropertyDescriptor(value, key).enumerable || !Object.hasOwn(Object.getOwnPropertyDescriptor(value, key), "value"))) && invalid(field), value), routineAlias = (value) => typeof value == "string" && /^[a-z][a-z0-9-]{0,62}$/.test(value), list = (value, field, allowed, qualified = !1) => value === void 0 ? [] : ((!Array.isArray(value) || value.length > 64 || value.some((item) => !(routineAlias(item) || qualified && typeof item == "string" && item.split("/").length === 2 && item.split("/").every(routineAlias)) || allowed && !allowed.includes(item)) || new Set(value).size !== value.length) && invalid(field), [...value].sort());
729
+ }, object2 = (value, fields4, field) => ((!value || typeof value != "object" || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null || Reflect.ownKeys(value).some((key) => typeof key != "string" || !fields4.includes(key) || !Object.getOwnPropertyDescriptor(value, key).enumerable || !Object.hasOwn(Object.getOwnPropertyDescriptor(value, key), "value"))) && invalid(field), value), routineAlias = (value) => typeof value == "string" && /^[a-z][a-z0-9-]{0,62}$/.test(value), list = (value, field, allowed, qualified = !1) => value === void 0 ? [] : ((!Array.isArray(value) || value.length > 64 || value.some((item) => !(routineAlias(item) || qualified && typeof item == "string" && item.split("/").length === 2 && item.split("/").every(routineAlias)) || allowed && !allowed.includes(item)) || new Set(value).size !== value.length) && invalid(field), [...value].sort());
730
730
  function routineAssetPattern(value) {
731
731
  return typeof value == "string" && value.length <= 512 && !value.startsWith("/") && !value.includes("\\") && !value.includes(":") && value.split("/").every((part) => !!part && part !== "." && part !== ".." && /^[a-zA-Z0-9_.*-]+$/.test(part));
732
732
  }
@@ -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 keys4 = Reflect.ownKeys(value);
786
- if (array3 && (keys4.length !== value.length + 1 || !Array.from({ length: value.length }, (_, index) => Object.hasOwn(value, index)).every(Boolean))) 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();
787
787
  ancestors.add(value);
788
- for (let key of keys4) {
788
+ for (let key of keys6) {
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 = (...keys4) => Object.keys(v).every((key) => ["reason", ...keys4].includes(key));
876
+ let v = value, only2 = (...keys6) => Object.keys(v).every((key) => ["reason", ...keys6].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, invalid9, oversized, limit = ROUTINE_AI_VALUE_BYTES) {
956
+ function capture(value, invalid12, 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(invalid9);
963
+ throw error instanceof AIError ? error : new AIError(invalid12);
964
964
  }
965
965
  }
966
966
  function parseRoutineAIRequest(value) {
@@ -980,57 +980,57 @@ function parseRoutineAIRequest(value) {
980
980
  throw error instanceof AIError ? error : new AIError("invalid_input");
981
981
  }
982
982
  }
983
- function parseRoutineAIResult(request2, value) {
983
+ function parseRoutineAIResult(request3, value) {
984
984
  let v;
985
985
  try {
986
986
  if (v = capture(
987
987
  value,
988
988
  "invalid_output",
989
989
  "output_too_large",
990
- request2.kind === "generateText" ? ROUTINE_AI_RESULT_BYTES : ROUTINE_AI_VALUE_BYTES
991
- ), assertRoutineFields(v, request2.kind === "generateText" ? ["text"] : ["object"]), request2.kind === "generateText") {
990
+ request3.kind === "generateText" ? ROUTINE_AI_RESULT_BYTES : ROUTINE_AI_VALUE_BYTES
991
+ ), assertRoutineFields(v, request3.kind === "generateText" ? ["text"] : ["object"]), request3.kind === "generateText") {
992
992
  if (typeof v.text != "string") throw new Error();
993
- return acceptText(request2, v.text);
993
+ return acceptText(request3, v.text);
994
994
  }
995
995
  if (!Object.hasOwn(v, "object")) throw new Error();
996
996
  } catch (error) {
997
997
  throw error instanceof AIError ? error : new AIError("invalid_output", { detail: { reason: "invalid_response" } });
998
998
  }
999
- return validateObject(request2.schema, v.object), freezeRoutineMetadata({ object: v.object });
999
+ return validateObject(request3.schema, v.object), freezeRoutineMetadata({ object: v.object });
1000
1000
  }
1001
- function validateObject(schema2, object5, text5) {
1001
+ function validateObject(schema2, object8, text5) {
1002
1002
  let detail = { reason: "invalid_response" };
1003
1003
  try {
1004
- validateRoutineSchemaValue(schema2, object5, (issue) => {
1004
+ validateRoutineSchemaValue(schema2, object8, (issue) => {
1005
1005
  detail = issue;
1006
1006
  });
1007
1007
  } catch {
1008
1008
  throw new AIError("invalid_output", { ...text5 === void 0 ? {} : { text: text5 }, detail });
1009
1009
  }
1010
1010
  }
1011
- function acceptText(request2, text5) {
1011
+ function acceptText(request3, text5) {
1012
1012
  if (new TextEncoder().encode(text5).byteLength > ROUTINE_AI_VALUE_BYTES) throw new AIError("output_too_large");
1013
- if (request2.kind === "generateText") {
1013
+ if (request3.kind === "generateText") {
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 object5, trimmed = text5.trim(), fenced = /^(`{3,}|~{3,})(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n\1[ \t]*$/i.exec(trimmed);
1017
+ let object8, trimmed = text5.trim(), fenced = /^(`{3,}|~{3,})(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n\1[ \t]*$/i.exec(trimmed);
1018
1018
  try {
1019
- object5 = JSON.parse(fenced ? fenced[2] : text5);
1019
+ object8 = 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(request2.schema, object5, text5), capture({ object: object5 }, "invalid_output", "output_too_large");
1023
+ return validateObject(request3.schema, object8, text5), capture({ object: object8 }, "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 invalid9 = () => {
1028
+ let invalid12 = () => {
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 ? invalid9() : 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 ? invalid12() : 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.";
@@ -1203,9 +1203,9 @@ function createCapabilityRuntime(contract, runtime, current2, owner) {
1203
1203
  let operation2 = (async () => {
1204
1204
  if (!current2() || contract.access.ai !== !0) throw new AIError("access_denied");
1205
1205
  if (!runtime.ai) throw new AIError("capability_unavailable");
1206
- let request2;
1206
+ let request3;
1207
1207
  try {
1208
- assertRoutineFields(value, kind === "generateObject" ? ["instructions", "input", "schema", "tools"] : ["instructions", "input", "tools"]), request2 = parseRoutineAIRequest({
1208
+ assertRoutineFields(value, kind === "generateObject" ? ["instructions", "input", "schema", "tools"] : ["instructions", "input", "tools"]), request3 = parseRoutineAIRequest({
1209
1209
  kind,
1210
1210
  instructions: value.instructions,
1211
1211
  input: value.input,
@@ -1215,9 +1215,9 @@ function createCapabilityRuntime(contract, runtime, current2, owner) {
1215
1215
  } catch (error) {
1216
1216
  throw error instanceof AIError ? error : new AIError("invalid_input");
1217
1217
  }
1218
- let result2 = await runtime.ai[kind](request2);
1218
+ let result2 = await runtime.ai[kind](request3);
1219
1219
  if (!current2()) throw new AIError("access_denied");
1220
- return parseRoutineAIResult(request2, result2);
1220
+ return parseRoutineAIResult(request3, result2);
1221
1221
  })();
1222
1222
  return aiWork.add(operation2), operation2.then(() => aiWork.delete(operation2), () => aiWork.delete(operation2)), operation2;
1223
1223
  }, guarded = (value, receiver) => typeof value == "function" ? (...args) => {
@@ -1257,9 +1257,9 @@ async function executeRoutineDefinition(definition, input, runtime) {
1257
1257
  ...capabilities.guarded({
1258
1258
  run: freezeRoutineMetadata({ id: runtime.run.id, async progress(value) {
1259
1259
  assertRoutineFields(value, ["completed", "total"]);
1260
- let { completed, total } = value, prior = activeStep ? progress2.get(activeStep) : void 0;
1261
- if (!active2 || broken || !activeStep || !Number.isSafeInteger(completed) || !Number.isSafeInteger(total) || completed < 1 || completed > total || prior && (prior.total !== total || completed <= prior.completed)) return invalid3();
1262
- let accepted = freezeRoutineMetadata({ step: activeStep, completed, total });
1260
+ let { completed: completed2, total } = value, prior = activeStep ? progress2.get(activeStep) : void 0;
1261
+ if (!active2 || broken || !activeStep || !Number.isSafeInteger(completed2) || !Number.isSafeInteger(total) || completed2 < 1 || completed2 > total || prior && (prior.total !== total || completed2 <= prior.completed)) return invalid3();
1262
+ let accepted = freezeRoutineMetadata({ step: activeStep, completed: completed2, total });
1263
1263
  await runtime.run.progress(accepted), progress2.set(activeStep, accepted);
1264
1264
  } }),
1265
1265
  ...runtime.artifact ? { artifact: runtime.artifact } : {}
@@ -1372,6 +1372,16 @@ function parseDataValidationDetail(value) {
1372
1372
  ...expected ? { expected } : {}
1373
1373
  };
1374
1374
  }
1375
+ function recordFieldDetail(record4, field, problem, schemaFile, expectation) {
1376
+ let expected = problem === "source_schema" ? { type: "string", many: !1, nullable: !1 } : expectation;
1377
+ return parseDataValidationDetail({
1378
+ record: record4,
1379
+ field,
1380
+ reason: reasons[problem],
1381
+ ...schemaFile ? { schemaFile } : {},
1382
+ ...expected ? { expected } : {}
1383
+ });
1384
+ }
1375
1385
  function recordFieldMessage(record4, field, problem, schemaPath, expected) {
1376
1386
  if (!validRecordRef(record4) || !/^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/.test(field) || schemaPath !== void 0 && (schemaPath.length > 256 || !/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*\/_schema\.yaml$/.test(schemaPath) || schemaPath.split("/").some((part) => [".", "..", ".git", "routines"].includes(part)))) return;
1377
1387
  let prefix = `Record "${record4}" isn't valid.`, schema2 = schemaPath ? `"${schemaPath}"` : "the collection schema";
@@ -1421,20 +1431,20 @@ var localDataPath = (value, repository) => typeof value == "string" && value.len
1421
1431
  return Object.keys(row).sort().join(",") === "action,path" && ["created", "updated", "deleted"].includes(String(row.action)) && localDataPath(row.path, repository);
1422
1432
  };
1423
1433
  function parseDataFailureDetail(value) {
1424
- let invalid9 = () => {
1434
+ let invalid12 = () => {
1425
1435
  throw new Error("Invalid local Data failure detail");
1426
1436
  };
1427
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid9();
1437
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid12();
1428
1438
  let row = value;
1429
- 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 invalid9();
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();
1430
1440
  let repository = row.repository;
1431
- if (!row.cause || typeof row.cause != "object" || Array.isArray(row.cause)) return invalid9();
1441
+ if (!row.cause || typeof row.cause != "object" || Array.isArray(row.cause)) return invalid12();
1432
1442
  let cause = row.cause;
1433
- 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 invalid9();
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();
1434
1444
  let files3 = row.files;
1435
- 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 invalid9();
1436
- for (let key of ["savedOmitted", "notAttemptedOmitted"]) if (files3[key] !== void 0 && (!Number.isSafeInteger(files3[key]) || Number(files3[key]) < 1 || Number(files3[key]) > 1e4)) return invalid9();
1437
- 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" ? invalid9() : 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 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);
1438
1448
  }
1439
1449
  function parseDataOperationDetail(value) {
1440
1450
  let validation = parseDataValidationDetail(value);
@@ -1493,7 +1503,7 @@ var DataOperationError = class extends Error {
1493
1503
 
1494
1504
  var invalid4 = () => {
1495
1505
  throw new DataOperationError("invalid_query");
1496
- }, dataText = (value) => typeof value == "string" && !/[\u0000\uD800-\uDFFF]/u.test(value);
1506
+ }, dataText = (value) => typeof value == "string" && !/[\u0000\uD800-\uDFFF]/u.test(value), dataVersion = (value) => dataText(value) && value.length > 0 && new TextEncoder().encode(value).length <= 1024 && !/[\u0000-\u001f\u007f-\u009f]/.test(value) && !/^[0-9a-f]{40}$/i.test(value);
1497
1507
  function dataProperties(value) {
1498
1508
  if (!value || typeof value != "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return invalid4();
1499
1509
  let descriptors = Object.getOwnPropertyDescriptors(value);
@@ -1573,22 +1583,25 @@ function capture3(value, ancestors = /* @__PURE__ */ new Set(), depth = 0) {
1573
1583
  ancestors.delete(value);
1574
1584
  }
1575
1585
  }
1586
+ function captureRecordsQuery(query) {
1587
+ return capture3(query);
1588
+ }
1576
1589
  function captureRecordsAll(query, options) {
1577
- let invalid9 = () => {
1590
+ let invalid12 = () => {
1578
1591
  throw new DataOperationError("invalid_query");
1579
1592
  };
1580
1593
  try {
1581
1594
  let properties = dataProperties(options), maxRecords = properties.maxRecords?.value;
1582
- if (Object.keys(properties).join(",") !== "maxRecords" || !Number.isSafeInteger(maxRecords) || maxRecords < 1) return invalid9();
1595
+ if (Object.keys(properties).join(",") !== "maxRecords" || !Number.isSafeInteger(maxRecords) || maxRecords < 1) return invalid12();
1583
1596
  let detached = capture3(query), selections = dataProperties(detached);
1584
- if (Object.keys(selections).length < 1 || Object.keys(selections).length > 16) return invalid9();
1597
+ if (Object.keys(selections).length < 1 || Object.keys(selections).length > 16) return invalid12();
1585
1598
  for (let selection2 of Object.values(selections)) {
1586
- let fields3 = dataProperties(selection2.value);
1587
- if (fields3.$ && Object.hasOwn(dataProperties(fields3.$.value), "after")) return invalid9();
1599
+ let fields4 = dataProperties(selection2.value);
1600
+ if (fields4.$ && Object.hasOwn(dataProperties(fields4.$.value), "after")) return invalid12();
1588
1601
  }
1589
1602
  return { query: detached, maxRecords };
1590
1603
  } catch {
1591
- return invalid9();
1604
+ return invalid12();
1592
1605
  }
1593
1606
  }
1594
1607
 
@@ -1635,8 +1648,8 @@ function captureDataDelete(record4) {
1635
1648
  }
1636
1649
  function captureDataUpdate(record4, set) {
1637
1650
  if (!validRecordRef(record4)) return invalidChange();
1638
- let input = mapping(set), { $body, ...fields3 } = input, body = Object.hasOwn(input, "$body");
1639
- return body && !validRecordBody($body) || !Object.keys(fields3).length && !body || Object.keys(fields3).some((key) => key.startsWith("$") || ["id", "type"].includes(key)) ? invalidChange() : { ref: record4, set: captureValue(fields3), ...body ? { body: $body } : {} };
1651
+ let input = mapping(set), { $body, ...fields4 } = input, body = Object.hasOwn(input, "$body");
1652
+ return body && !validRecordBody($body) || !Object.keys(fields4).length && !body || Object.keys(fields4).some((key) => key.startsWith("$") || ["id", "type"].includes(key)) ? invalidChange() : { ref: record4, set: captureValue(fields4), ...body ? { body: $body } : {} };
1640
1653
  }
1641
1654
  function captureIdentities(value, update, allowEmpty = !0) {
1642
1655
  if (!Array.isArray(value) || !allowEmpty && !value.length || value.length > 1e4) return invalidChange();
@@ -1658,7 +1671,7 @@ function captureDataCreate(value) {
1658
1671
  let row = mapping(value);
1659
1672
  if (!validRecordRef(row.$ref) || Object.keys(row).some((key) => key.startsWith("$") && !["$ref", "$filing", "$body"].includes(key)))
1660
1673
  return invalidChange();
1661
- let { $ref: ref, $filing, $body, ...fields3 } = row, body = Object.hasOwn(row, "$body");
1674
+ let { $ref: ref, $filing, $body, ...fields4 } = row, body = Object.hasOwn(row, "$body");
1662
1675
  if (body && !validRecordBody($body)) return invalidChange();
1663
1676
  let filing;
1664
1677
  if ($filing !== void 0) {
@@ -1667,7 +1680,7 @@ function captureDataCreate(value) {
1667
1680
  return invalidChange();
1668
1681
  filing = { ...components };
1669
1682
  }
1670
- return { ref, fields: captureValue(fields3), ...filing ? { filing } : {}, ...body ? { body: $body } : {} };
1683
+ return { ref, fields: captureValue(fields4), ...filing ? { filing } : {}, ...body ? { body: $body } : {} };
1671
1684
  }
1672
1685
  function captureDataChanges(updatesValue, createsValue = [], deletesValue = []) {
1673
1686
  let updates = captureDataUpdates(updatesValue, !0);
@@ -1675,9 +1688,9 @@ function captureDataChanges(updatesValue, createsValue = [], deletesValue = [])
1675
1688
  let creates = createsValue.map((item) => {
1676
1689
  let row = mapping(item);
1677
1690
  if (Object.keys(row).some((key) => !["ref", "fields", "filing", "body"].includes(key)) || !Object.hasOwn(row, "ref") || !Object.hasOwn(row, "fields")) return invalidChange();
1678
- let fields3 = mapping(row.fields);
1679
- return Object.keys(fields3).some((key) => key.startsWith("$")) ? invalidChange() : captureDataCreate({
1680
- ...fields3,
1691
+ let fields4 = mapping(row.fields);
1692
+ return Object.keys(fields4).some((key) => key.startsWith("$")) ? invalidChange() : captureDataCreate({
1693
+ ...fields4,
1681
1694
  $ref: row.ref,
1682
1695
  ...Object.hasOwn(row, "filing") ? { $filing: row.filing } : {},
1683
1696
  ...Object.hasOwn(row, "body") ? { $body: row.body } : {}
@@ -1732,6 +1745,23 @@ async function resolveAppContext(retained = !1) {
1732
1745
  throw new Error("App context unavailable.");
1733
1746
  return context;
1734
1747
  }
1748
+ async function resolveSnapshotContext() {
1749
+ try {
1750
+ let context = await resolveAppContext();
1751
+ if (context.kind === "local" || !context.memberId || !context.binding || context.endpoint !== globalThis.location.origin || context.endpoint !== `https://${context.workspace}.oddington.ai`) throw new Error();
1752
+ let host = memberContext;
1753
+ return {
1754
+ workspace: context.workspace,
1755
+ endpoint: context.endpoint,
1756
+ memberId: context.memberId,
1757
+ binding: context.binding,
1758
+ headers: { authorization: `Bearer ${context.accessToken}` },
1759
+ isCurrent: () => host === memberContext && context.isCurrent() && context.expiresAt > Date.now()
1760
+ };
1761
+ } catch {
1762
+ throw new DataOperationError("context_unavailable");
1763
+ }
1764
+ }
1735
1765
  async function resolveDataContext() {
1736
1766
  try {
1737
1767
  let host = memberContext;
@@ -1820,14 +1850,14 @@ function recordPagination(queryRecords) {
1820
1850
  next: void 0
1821
1851
  }])), active2 = names, version;
1822
1852
  do {
1823
- let request2 = Object.fromEntries(active2.map((name2) => {
1853
+ let request3 = Object.fromEntries(active2.map((name2) => {
1824
1854
  let selection2 = captured[name2], next = state.get(name2).next;
1825
1855
  return [name2, next === void 0 ? selection2 : { ...selection2, $: { ...selection2.$, after: next } }];
1826
- })), response2 = await queryRecords(request2), page;
1856
+ })), response2 = await queryRecords(request3), page;
1827
1857
  try {
1828
1858
  page = capture4(response2);
1829
- let keys4 = Object.keys(dataProperties(page));
1830
- (keys4.length !== active2.length + 1 || keys4.some((key) => key !== "$meta" && !active2.includes(key))) && unavailable();
1859
+ let keys6 = Object.keys(dataProperties(page));
1860
+ (keys6.length !== active2.length + 1 || keys6.some((key) => key !== "$meta" && !active2.includes(key))) && unavailable();
1831
1861
  let meta = page.$meta;
1832
1862
  (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();
1833
1863
  for (let name2 of active2) {
@@ -1858,7 +1888,863 @@ function recordPagination(queryRecords) {
1858
1888
  return { pages };
1859
1889
  }
1860
1890
 
1891
+ var FRAGMENT = /^(?:[a-zA-Z0-9._~!$&'()*+,;=:@/?-]|%[0-9a-fA-F]{2})+(?![\s\S])/;
1892
+ function parseRecordLink(value) {
1893
+ if (typeof value != "string") return;
1894
+ let separator = value.indexOf("#"), ref = separator < 0 ? value : value.slice(0, separator);
1895
+ if (!validRecordRef(ref)) return;
1896
+ if (separator < 0) return { ref };
1897
+ let fragment = value.slice(separator + 1);
1898
+ return FRAGMENT.test(fragment) ? { ref, fragment } : void 0;
1899
+ }
1900
+ function parseStoredRecordLink(value) {
1901
+ return typeof value == "string" && value.startsWith("[[") && value.endsWith("]]") ? parseRecordLink(value.slice(2, -2)) : void 0;
1902
+ }
1903
+
1904
+ var RecordValidationError = class extends Error {
1905
+ constructor(message2, path) {
1906
+ super(message2);
1907
+ this.path = path;
1908
+ this.name = "RecordValidationError";
1909
+ }
1910
+ path;
1911
+ }, RecordFieldValidationError = class extends RecordValidationError {
1912
+ constructor(problem, field, expected) {
1913
+ super(`${problem} record field: ${field}`);
1914
+ this.problem = problem;
1915
+ this.field = field;
1916
+ this.expected = expected;
1917
+ }
1918
+ problem;
1919
+ field;
1920
+ expected;
1921
+ detail;
1922
+ atRecord(ref, schemaPath, fileSource = !1) {
1923
+ let problem = fileSource && this.problem === "unknown" && this.field === "media_type" ? "source_schema" : this.problem;
1924
+ return this.message = recordFieldMessage(ref, this.field, problem, schemaPath, this.expected) ?? recordFieldMessage(ref, this.field, this.problem) ?? this.message, this.detail = recordFieldDetail(ref, this.field, problem, schemaPath, this.expected) ?? recordFieldDetail(ref, this.field, this.problem, void 0, this.expected), Object.assign(this, dataValidationMessageFacts({ code: "invalid_change", message: this.message, detail: this.detail })), this;
1925
+ }
1926
+ };
1927
+ function fieldExpectation(field) {
1928
+ return {
1929
+ type: field.kind,
1930
+ many: field.many,
1931
+ nullable: field.nullable,
1932
+ ...field.kind === "number" && field.precision !== void 0 ? { decimalPlaces: field.precision } : {},
1933
+ ...field.kind === "date" && field.format ? { format: field.format } : {}
1934
+ };
1935
+ }
1936
+ var NAME = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
1937
+ function fail2(message2) {
1938
+ throw new RecordValidationError(message2);
1939
+ }
1940
+ function validateRecordText(value) {
1941
+ /[\u0000\uD800-\uDFFF]/u.test(value) && fail2("Record text must contain Unicode scalar values excluding U+0000");
1942
+ }
1943
+ function object3(value) {
1944
+ return (!value || typeof value != "object" || Array.isArray(value)) && fail2("Expected a field mapping"), value;
1945
+ }
1946
+ function keys2(row, allowed, required) {
1947
+ (Object.keys(row).some((key) => !allowed.includes(key)) || required.some((key) => !Object.hasOwn(row, key))) && fail2("Unsupported or missing schema/record fields");
1948
+ }
1949
+ function valueDefinition(value, depth, native, named = !1) {
1950
+ depth > 8 && fail2("Invalid field definitions");
1951
+ let row = { ...object3(value) };
1952
+ switch (["enum_list", "links", "list"].includes(String(row.kind)) && row.many !== void 0 && row.many !== !0 && fail2("Conflicting cardinality"), Object.hasOwn(row, "inline") && ((row.kind !== "list" || typeof row.inline != "boolean" || Object.hasOwn(row, "style")) && fail2("Unsupported or conflicting inline style"), row.inline && (row.style = "inline"), delete row.inline), row.kind) {
1953
+ case "bool":
1954
+ row.kind = "boolean";
1955
+ break;
1956
+ case "constant":
1957
+ row.kind = "const";
1958
+ break;
1959
+ case "enum_list":
1960
+ row.kind = "enum", row.many = !0;
1961
+ break;
1962
+ case "links":
1963
+ row.kind = "link", row.many = !0;
1964
+ break;
1965
+ case "month":
1966
+ row.format !== void 0 && row.format !== "month" && fail2("Conflicting date format"), row.kind = "date", row.format = "month";
1967
+ break;
1968
+ case "list": {
1969
+ Object.hasOwn(row, "items") && Object.hasOwn(row, "fields") && fail2("Conflicting list definitions");
1970
+ let nested = Object.hasOwn(row, "items") ? row.items : row.fields;
1971
+ row.kind = nested === void 0 ? "string" : "object", row.many = !0, Object.hasOwn(row, "items") && delete row.items, nested !== void 0 && (row.fields = nested);
1972
+ break;
1973
+ }
1974
+ case "map":
1975
+ (Object.hasOwn(row, "keys") || Object.hasOwn(row, "values")) && ((Object.hasOwn(row, "key") || Object.hasOwn(row, "value") || row.keys !== "YYYY-MM" || row.values !== "number") && fail2("Unsupported or conflicting map definitions"), row.key = { kind: "date", format: "month" }, row.value = { kind: "number", ...Object.hasOwn(row, "precision") ? { precision: row.precision } : {} }, delete row.keys, delete row.values, delete row.precision);
1976
+ break;
1977
+ }
1978
+ row.nullable !== void 0 && typeof row.nullable != "boolean" && fail2("Invalid nullability"), row.many !== void 0 && typeof row.many != "boolean" && fail2("Invalid cardinality"), ["description", "term"].some((key) => row[key] !== void 0 && typeof row[key] != "string") && fail2("Invalid field documentation");
1979
+ let base = {
1980
+ nullable: row.nullable === !0,
1981
+ many: row.many === !0,
1982
+ ...native && row.nullable === !0 ? { optional: !0 } : {},
1983
+ ...typeof row.description == "string" ? { description: row.description } : {},
1984
+ ...typeof row.term == "string" ? { term: row.term } : {},
1985
+ ...row.style === "inline" ? { style: "inline" } : {}
1986
+ };
1987
+ row.style !== void 0 && (row.style !== "inline" || !base.many) && fail2("Unsupported storage style");
1988
+ let common = ["kind", "nullable", "many", "style", "description", "term", ...named ? ["name"] : []], check = (owned = []) => keys2(row, [...common, ...owned], ["kind", ...owned]);
1989
+ switch (row.kind) {
1990
+ case "string":
1991
+ case "integer":
1992
+ case "boolean":
1993
+ case "datetime":
1994
+ return check(), { ...base, kind: row.kind };
1995
+ case "number":
1996
+ return keys2(row, [...common, "precision"], ["kind"]), row.precision !== void 0 && (!Number.isInteger(row.precision) || Number(row.precision) < 0 || Number(row.precision) > 6) && fail2("Unsupported decimal precision"), { ...base, kind: "number", ...row.precision !== void 0 ? { precision: row.precision } : {} };
1997
+ case "date":
1998
+ return keys2(row, [...common, "format"], ["kind"]), row.format !== void 0 && row.format !== "month" && fail2("Unsupported date format"), { ...base, kind: "date", ...row.format === "month" ? { format: "month" } : {} };
1999
+ case "const":
2000
+ return check(["value"]), (base.many || !["string", "number", "boolean"].includes(typeof row.value) || typeof row.value == "number" && !Number.isFinite(row.value)) && fail2("Invalid constant"), { ...base, kind: "const", value: row.value };
2001
+ case "enum":
2002
+ case "link": {
2003
+ let property = row.kind === "enum" ? "values" : "to";
2004
+ check([property]);
2005
+ let list2 = row.kind === "link" && typeof row.to == "string" ? [row.to] : row[property];
2006
+ return (!Array.isArray(list2) || !list2.length || list2.length > 1e5 || new Set(list2).size !== list2.length || list2.some((item) => typeof item != "string" || !item || row.kind === "link" && !NAME.test(item))) && fail2("Invalid enum/link definition"), row.kind === "enum" ? { ...base, kind: "enum", values: list2 } : { ...base, kind: "link", to: list2 };
2007
+ }
2008
+ case "object":
2009
+ return check(["fields"]), { ...base, kind: "object", fields: fields2(row.fields, depth + 1, native) };
2010
+ case "map": {
2011
+ check(["key", "value"]);
2012
+ let key = valueDefinition(row.key, depth + 1, native), value2 = valueDefinition(row.value, depth + 1, native);
2013
+ return (!["string", "integer", "date", "enum"].includes(key.kind) || key.nullable || key.many) && fail2("Unsupported map key definition"), { ...base, kind: "map", key, value: value2 };
2014
+ }
2015
+ default:
2016
+ return fail2("Unsupported field kind");
2017
+ }
2018
+ }
2019
+ function fields2(value, depth = 0, native = !1) {
2020
+ (depth > 8 || !Array.isArray(value) || !value.length || value.length > 256) && fail2("Invalid field definitions");
2021
+ let names = /* @__PURE__ */ new Set();
2022
+ return value.map((definition) => {
2023
+ let row = object3(definition);
2024
+ return (typeof row.name != "string" || !NAME.test(row.name) || ["constructor", "prototype"].includes(row.name) || names.has(row.name)) && fail2("Invalid or duplicate field name"), names.add(row.name), { name: row.name, ...valueDefinition(row, depth, native, !0) };
2025
+ });
2026
+ }
2027
+ function validateRecordFields(value, definitions2, resolveLink, canonical = !1) {
2028
+ let row = object3(value);
2029
+ for (let [key, entry] of Object.entries(row))
2030
+ validateRecordText(key), typeof entry == "string" && validateRecordText(entry);
2031
+ for (let name2 of Object.keys(row)) if (!definitions2.some((field) => field.name === name2))
2032
+ throw new RecordFieldValidationError("unknown", name2);
2033
+ for (let field of definitions2) if (!field.optional && !Object.hasOwn(row, field.name))
2034
+ throw new RecordFieldValidationError("missing", field.name, fieldExpectation(field));
2035
+ for (let field of definitions2) {
2036
+ let value2 = row[field.name];
2037
+ if (!Object.hasOwn(row, field.name) && field.optional || value2 === null && field.nullable) continue;
2038
+ if (field.many) {
2039
+ if (!Array.isArray(value2) || value2.length > 1e5 || ["enum", "link"].includes(field.kind) && new Set(value2).size !== value2.length)
2040
+ throw new RecordFieldValidationError("invalid", field.name, fieldExpectation(field));
2041
+ try {
2042
+ for (let entry of value2) validateRecordFields({ [field.name]: entry }, [{ ...field, many: !1, nullable: !1 }], resolveLink, canonical);
2043
+ } catch (error) {
2044
+ throw error instanceof RecordFieldValidationError && error.field === field.name && (error.expected = fieldExpectation(field)), error;
2045
+ }
2046
+ continue;
2047
+ }
2048
+ let valid = !1;
2049
+ switch (field.kind) {
2050
+ case "const":
2051
+ valid = value2 === field.value;
2052
+ break;
2053
+ case "string":
2054
+ valid = typeof value2 == "string";
2055
+ break;
2056
+ case "integer":
2057
+ valid = Number.isSafeInteger(value2);
2058
+ break;
2059
+ case "number": {
2060
+ if (valid = typeof value2 == "number" && Number.isFinite(value2), valid && field.precision !== void 0) {
2061
+ let scaled = value2 * 10 ** field.precision;
2062
+ valid = Number.isSafeInteger(Math.round(scaled)) && Math.abs(scaled - Math.round(scaled)) <= Math.min(1e-7, Number.EPSILON * Math.max(1, Math.abs(scaled)) * 4);
2063
+ }
2064
+ break;
2065
+ }
2066
+ case "boolean":
2067
+ valid = typeof value2 == "boolean";
2068
+ break;
2069
+ case "datetime":
2070
+ valid = typeof value2 == "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value2) && Number.isFinite(Date.parse(value2)) && new Date(value2).toISOString() === value2;
2071
+ break;
2072
+ case "date": {
2073
+ let day = typeof value2 == "string" && field.format === "month" ? `${value2}-01` : value2;
2074
+ valid = typeof value2 == "string" && (field.format === "month" ? /^\d{4}-\d{2}$/.test(value2) : /^\d{4}-\d{2}-\d{2}$/.test(value2)) && typeof day == "string" && Number.isFinite(Date.parse(day)) && new Date(day).toISOString().slice(0, 10) === day;
2075
+ break;
2076
+ }
2077
+ case "enum":
2078
+ valid = typeof value2 == "string" && field.values.includes(value2);
2079
+ break;
2080
+ case "link": {
2081
+ let link = (canonical ? parseRecordLink : parseStoredRecordLink)(value2);
2082
+ valid = !!link && (!resolveLink || field.to.includes(resolveLink(link.ref, field.to) ?? ""));
2083
+ break;
2084
+ }
2085
+ case "object":
2086
+ if (!value2 || typeof value2 != "object" || Array.isArray(value2)) break;
2087
+ validateRecordFields(value2, field.fields, resolveLink, canonical), valid = !0;
2088
+ break;
2089
+ case "map": {
2090
+ if (!value2 || typeof value2 != "object" || Array.isArray(value2)) break;
2091
+ let entries = Object.entries(value2);
2092
+ entries.length > 1e5 && fail2("Record map is too large");
2093
+ for (let [key, entry] of entries) {
2094
+ ["<<", "__proto__", "constructor", "prototype"].includes(key) && fail2("Unsupported record map key");
2095
+ let keyValue = field.key.kind === "integer" ? Number(key) : key;
2096
+ field.key.kind === "integer" && String(keyValue) !== key && fail2("Invalid integer map key"), validateRecordFields({ key: keyValue }, [{ ...field.key, name: "key" }], resolveLink, canonical), validateRecordFields({ value: entry }, [{ ...field.value, name: "value" }], resolveLink, canonical);
2097
+ }
2098
+ valid = !0;
2099
+ break;
2100
+ }
2101
+ }
2102
+ if (!valid) throw new RecordFieldValidationError("invalid", field.name, fieldExpectation(field));
2103
+ }
2104
+ }
2105
+
2106
+ var boundOperators = ["$gt", "$gte", "$lt", "$lte"], compare = (a, b) => a < b ? -1 : a > b ? 1 : 0, fail3 = (message2) => {
2107
+ throw new RecordValidationError(`Invalid Records query: ${message2}`);
2108
+ };
2109
+ function mapping2(value) {
2110
+ return !value || typeof value != "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value)) ? fail3("expected a mapping") : value;
2111
+ }
2112
+ function publicDefinition(field) {
2113
+ let { optional: _optional, style: _style, ...definition } = field;
2114
+ return definition.kind === "object" ? { ...definition, fields: definition.fields.map(publicField) } : definition.kind === "map" ? {
2115
+ ...definition,
2116
+ key: publicDefinition(definition.key),
2117
+ value: publicDefinition(definition.value)
2118
+ } : structuredClone(definition);
2119
+ }
2120
+ function publicField(field) {
2121
+ return { ...publicDefinition(field), name: field.name };
2122
+ }
2123
+ function scalarField(name2, schema2) {
2124
+ if (name2 === "$ref") return { name: name2, kind: "string", nullable: !1, many: !1 };
2125
+ let field = schema2.fields.find((field2) => field2.name === name2);
2126
+ return !field || field.many || field.kind === "object" || field.kind === "map" ? fail3(`ineligible scalar field: ${name2}`) : field;
2127
+ }
2128
+ function conditionValue(value, field) {
2129
+ return (field.kind === "link" || field.name === "$ref") && value !== null && !(field.kind === "link" ? parseRecordLink(value) : validRecordRef(value)) ? fail3(`invalid reference: ${field.name}`) : (validateRecordFields(
2130
+ { [field.name]: field.kind === "link" && typeof value == "string" ? `[[${value}]]` : value },
2131
+ [{ ...field, optional: !1 }]
2132
+ ), value);
2133
+ }
2134
+ function queryEntries(query) {
2135
+ let entries = Object.entries(mapping2(query));
2136
+ return preflightSelections(entries), entries;
2137
+ }
2138
+ function preflightSelections(entries) {
2139
+ if (entries.length < 1 || entries.length > 16) return fail3("expected 1\u201316 collections");
2140
+ let nodes = 0, visit = (value, depth) => {
2141
+ if (++nodes > 256) return fail3("too many selection nodes");
2142
+ let selection2 = mapping2(value);
2143
+ for (let [name2, nested] of Object.entries(selection2))
2144
+ if (name2 !== "$") {
2145
+ if (depth >= 4) return fail3("too many link levels");
2146
+ visit(nested, depth + 1);
2147
+ }
2148
+ };
2149
+ for (let [, value] of entries) visit(value, 0);
2150
+ }
2151
+ function selectionTree(value, schema2, collectionsByType, depth = 0, many = !1) {
2152
+ let selection2 = mapping2(value), options = Object.hasOwn(selection2, "$") ? mapping2(selection2.$) : {}, allowed = depth === 0 ? ["where", "fields", "order", "limit", "count", "after"] : many ? ["where", "fields", "order", "limit"] : ["where", "fields"];
2153
+ if (Object.keys(options).some((key) => !allowed.includes(key)))
2154
+ return fail3("unsupported option");
2155
+ let fields4 = Object.hasOwn(options, "fields") ? options.fields : schema2.fields.map((field) => field.name);
2156
+ if (!Array.isArray(fields4) || fields4.some((name2) => typeof name2 != "string" || !["$ref", "$version"].includes(name2) && !schema2.fields.some((field) => field.name === name2)) || new Set(fields4).size !== fields4.length) return fail3("invalid projection");
2157
+ let conditions = [];
2158
+ if (Object.hasOwn(options, "where")) for (let [name2, condition] of Object.entries(mapping2(options.where))) {
2159
+ let field = scalarField(name2, schema2), values = [condition];
2160
+ if (condition !== null && typeof condition == "object") {
2161
+ let expression = mapping2(condition);
2162
+ if (!Object.hasOwn(expression, "$in")) {
2163
+ let keys6 = Object.keys(expression);
2164
+ 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");
2165
+ if (field.name === "$ref" || !["integer", "number", "date", "datetime"].includes(field.kind))
2166
+ return fail3(`ineligible range field: ${name2}`);
2167
+ let bounds = boundOperators.filter((operator) => Object.hasOwn(expression, operator)).map((operator) => {
2168
+ let value2 = expression[operator];
2169
+ return value2 === null ? fail3("null bound") : [operator, conditionValue(value2, field)];
2170
+ });
2171
+ conditions.push([name2, { bounds }]);
2172
+ continue;
2173
+ }
2174
+ if (Object.keys(expression).length !== 1 || !Object.hasOwn(expression, "$in") || !Array.isArray(expression.$in) || expression.$in.length < 1 || expression.$in.length > 100)
2175
+ return fail3("invalid $in");
2176
+ values = expression.$in;
2177
+ }
2178
+ let checked2 = values.map((value2) => conditionValue(value2, field));
2179
+ if (new Set(checked2).size !== checked2.length) return fail3("duplicate $in value");
2180
+ conditions.push([name2, checked2]);
2181
+ }
2182
+ let order = { field: "$ref", direction: "asc" };
2183
+ if (Object.hasOwn(options, "order")) {
2184
+ let entries = Object.entries(mapping2(options.order));
2185
+ if (entries.length !== 1) return fail3("order requires one field");
2186
+ let [name2, direction] = entries[0];
2187
+ if (scalarField(name2, schema2), direction !== "asc" && direction !== "desc") return fail3("invalid order direction");
2188
+ order = { field: name2, direction };
2189
+ }
2190
+ let limit = Object.hasOwn(options, "limit") ? options.limit : 100;
2191
+ if (typeof limit != "number" || !Number.isInteger(limit) || limit < 1 || limit > (depth === 0 ? 500 : 100))
2192
+ return fail3("invalid limit");
2193
+ if (Object.hasOwn(options, "count") && typeof options.count != "boolean") return fail3("invalid count");
2194
+ if (Object.hasOwn(options, "after") && (typeof options.after != "string" || options.after.length === 0))
2195
+ return fail3("invalid cursor");
2196
+ let links = [];
2197
+ for (let [name2, nested] of Object.entries(selection2)) {
2198
+ if (name2 === "$") continue;
2199
+ let field = schema2.fields.find((field2) => field2.name === name2);
2200
+ if (!field || field.kind !== "link") return fail3(`ineligible link field: ${name2}`);
2201
+ if (depth >= 4) return fail3("too many link levels");
2202
+ let targets = new Map(field.to.flatMap((type) => (collectionsByType.get(type) ?? fail3(`unknown link target type: ${type}`)).map((target) => [
2203
+ target.name,
2204
+ selectionTree(nested, target.schema, collectionsByType, depth + 1, field.many)
2205
+ ])));
2206
+ links.push({ name: name2, many: field.many, targets });
2207
+ }
2208
+ return {
2209
+ fields: fields4,
2210
+ conditions,
2211
+ order,
2212
+ limit,
2213
+ count: options.count === !0,
2214
+ ...Object.hasOwn(options, "after") ? { after: options.after } : {},
2215
+ explicitOrder: Object.hasOwn(options, "order"),
2216
+ explicitLimit: Object.hasOwn(options, "limit"),
2217
+ links
2218
+ };
2219
+ }
2220
+ function selectionBinding(selection2, top = !0, many = !1) {
2221
+ return {
2222
+ fields: selection2.fields,
2223
+ conditions: [...selection2.conditions].sort(([a], [b]) => compare(a, b)),
2224
+ order: top || many && selection2.explicitOrder ? selection2.order : null,
2225
+ limit: top || many && selection2.explicitLimit ? selection2.limit : null,
2226
+ count: selection2.count,
2227
+ links: [...selection2.links].sort((a, b) => compare(a.name, b.name)).map((link) => ({
2228
+ name: link.name,
2229
+ many: link.many,
2230
+ targets: [...link.targets].sort(([a], [b]) => compare(a, b)).map(([collection, nested]) => [collection, selectionBinding(nested, !1, link.many)])
2231
+ }))
2232
+ };
2233
+ }
2234
+ function planIndexQuery(query, catalogue) {
2235
+ let entries = queryEntries(query), collections = new Map(catalogue.map((collection) => [collection.name, collection])), byType = /* @__PURE__ */ new Map();
2236
+ for (let collection of catalogue) {
2237
+ let targets = byType.get(collection.schema.type) ?? [];
2238
+ targets.push(collection), byType.set(collection.schema.type, targets);
2239
+ }
2240
+ return entries.map(([name2, value]) => {
2241
+ let target = collections.get(name2) ?? fail3(`unknown collection: ${name2}`);
2242
+ return { name: name2, selection: selectionTree(value, target.schema, byType) };
2243
+ });
2244
+ }
2245
+ function indexSelectionBinding(context, collection, selection2) {
2246
+ return JSON.stringify({ ...context, collection, selection: selectionBinding(selection2) });
2247
+ }
2248
+ function cursorPosition(value, binding, limit) {
2249
+ let payload;
2250
+ try {
2251
+ payload = mapping2(value);
2252
+ } catch {
2253
+ return fail3("invalid cursor");
2254
+ }
2255
+ let { position, ref } = payload;
2256
+ return Object.keys(payload).length !== 4 || payload.format !== 1 || payload.binding !== binding || typeof position != "number" || !Number.isSafeInteger(position) || position <= 0 || position % limit !== 0 || typeof ref != "string" || !validRecordRef(ref) ? fail3("incompatible cursor") : { position, ref };
2257
+ }
2258
+
2259
+ var invalid7 = () => {
2260
+ throw new DataOperationError("unavailable", !0);
2261
+ }, object4 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid7() : value;
2262
+ function stable(value) {
2263
+ 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);
2264
+ }
2265
+ function schemaText(value) {
2266
+ if (typeof value == "string" && !dataText(value)) return invalid7();
2267
+ if (value && typeof value == "object") for (let [key, entry] of Object.entries(value)) {
2268
+ if (!dataText(key)) return invalid7();
2269
+ schemaText(entry);
2270
+ }
2271
+ }
2272
+ function validateSnapshotEnvelope(input, repository, name2) {
2273
+ try {
2274
+ let row = object4(input);
2275
+ 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();
2276
+ let schemas2 = object4(row.schemas), collections = object4(row.collections);
2277
+ schemaText(schemas2);
2278
+ let names = Object.keys(collections);
2279
+ if (!names.length || names.join("\0") !== [...names].sort().join("\0") || Object.keys(schemas2).join("\0") !== names.join("\0")) return invalid7();
2280
+ let catalogue = names.map((name3) => {
2281
+ let schema2 = object4(schemas2[name3]);
2282
+ 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();
2283
+ let definitions2 = fields2(schema2.fields, 0, !0);
2284
+ return stable(definitions2.map(publicField)) !== stable(schema2.fields) ? invalid7() : { name: name3, schema: {
2285
+ type: schema2.type,
2286
+ fields: definitions2,
2287
+ ...schema2.description === void 0 ? {} : { description: schema2.description }
2288
+ } };
2289
+ }), types = /* @__PURE__ */ new Map();
2290
+ for (let collection of catalogue) {
2291
+ let records = collections[collection.name];
2292
+ if (!Array.isArray(records)) return invalid7();
2293
+ let previous = "";
2294
+ for (let record4 of records) {
2295
+ let value = object4(record4);
2296
+ if (!validRecordRef(value.$ref) || !value.$ref.startsWith(`${collection.name}/`) || value.$ref <= previous || types.has(value.$ref) || typeof value.$version != "string" || !/^record-v1:[0-9a-f]{64}$/.test(value.$version)) return invalid7();
2297
+ types.set(value.$ref, collection.schema.type), previous = value.$ref;
2298
+ }
2299
+ }
2300
+ for (let collection of catalogue) for (let record4 of collections[collection.name]) {
2301
+ let { $ref: _ref, $version: _version, ...values } = record4;
2302
+ validateRecordFields(values, collection.schema.fields, (ref, targets) => catalogue.some((item) => ref.startsWith(`${item.name}/`)) ? types.get(ref) : targets[0], !0);
2303
+ }
2304
+ return {
2305
+ format: "data-snapshot.v1",
2306
+ repository,
2307
+ name: name2,
2308
+ version: row.version,
2309
+ catalogue,
2310
+ collections
2311
+ };
2312
+ } catch {
2313
+ return invalid7();
2314
+ }
2315
+ }
2316
+
2317
+ var compare2 = (a, b) => a < b ? -1 : a > b ? 1 : 0, fail4 = (message2) => {
2318
+ throw new RecordValidationError(`Invalid Records query: ${message2}`);
2319
+ };
2320
+ function continuation(value, binding, matching, limit) {
2321
+ let { position, ref } = cursorPosition(value, binding, limit);
2322
+ return position >= matching.length || ref !== matching[position - 1]?.$ref ? fail4("incompatible cursor") : position;
2323
+ }
2324
+ function matches(record4, selection2) {
2325
+ return selection2.conditions.every(([field, condition]) => {
2326
+ if (!Object.hasOwn(record4, field)) return !1;
2327
+ let value = record4[field];
2328
+ return Array.isArray(condition) ? condition.some((candidate) => candidate === value) : value === null ? !1 : condition.bounds.every(([operator, bound]) => {
2329
+ let result2 = typeof value == "number" && typeof bound == "number" ? value - bound : compare2(value, bound);
2330
+ switch (operator) {
2331
+ case "$gt":
2332
+ return result2 > 0;
2333
+ case "$gte":
2334
+ return result2 >= 0;
2335
+ case "$lt":
2336
+ return result2 < 0;
2337
+ case "$lte":
2338
+ return result2 <= 0;
2339
+ }
2340
+ });
2341
+ });
2342
+ }
2343
+ function ordered(a, b, { field, direction }) {
2344
+ let left = a[field], right = b[field], missingLeft = left == null, missingRight = right == null, result2 = 0;
2345
+ return missingLeft !== missingRight ? missingLeft ? 1 : -1 : (!missingLeft && !missingRight && (result2 = typeof left == "number" && typeof right == "number" ? left - right : typeof left == "boolean" && typeof right == "boolean" ? Number(left) - Number(right) : compare2(left, right), direction === "desc" && (result2 = -result2)), result2 || compare2(a.$ref, b.$ref));
2346
+ }
2347
+ function* evaluateRecordsQuery(query, catalogue, context, maxRecords) {
2348
+ let { version } = context, selections = planIndexQuery(query, catalogue), scanned = /* @__PURE__ */ new Map();
2349
+ for (let { name: name2 } of selections) scanned.set(name2, yield { operation: "scan", collection: name2 });
2350
+ if (maxRecords !== void 0 && selections.reduce((sum, { name: name2, selection: selection2 }) => sum + scanned.get(name2).filter((record4) => matches(record4, selection2)).length, 0) > maxRecords)
2351
+ throw new DataOperationError(
2352
+ "capacity",
2353
+ !1,
2354
+ void 0,
2355
+ void 0,
2356
+ { code: "record_limit_exceeded", maxRecords, collections: selections.map((row) => row.name) }
2357
+ );
2358
+ let occurrences = 0;
2359
+ function* expand(record4, selection2, fragment) {
2360
+ if (++occurrences > 2e3) return fail4("too many returned Record occurrences");
2361
+ let result2 = Object.fromEntries(["$ref", "$version", ...selection2.fields.filter((field) => !["$ref", "$version"].includes(field))].filter((field) => Object.hasOwn(record4, field)).map((field) => [field, structuredClone(record4[field])]));
2362
+ fragment !== void 0 && (result2.$fragment = fragment);
2363
+ for (let link of selection2.links) {
2364
+ if (!Object.hasOwn(record4, link.name)) continue;
2365
+ let value = record4[link.name], expanded;
2366
+ if (value === null) expanded = null;
2367
+ else {
2368
+ let refs = link.many ? value : [value], matching = [];
2369
+ for (let value2 of refs) {
2370
+ let { ref, fragment: fragment2 } = parseRecordLink(value2) ?? fail4("invalid stored link"), target = yield { operation: "lookup", ref };
2371
+ if (!target) return fail4("unresolved stored link");
2372
+ let nested = link.targets.get(target.collection) ?? fail4("incompatible stored link");
2373
+ matches(target.record, nested) && matching.push({ record: target.record, selection: nested, fragment: fragment2 });
2374
+ }
2375
+ let options = link.targets.values().next().value;
2376
+ if (options.explicitOrder && matching.sort((a, b) => ordered(a.record, b.record, options.order)), link.many && !options.explicitLimit && matching.length > 100) return fail4("too many matching linked Records");
2377
+ options.explicitLimit && (matching = matching.slice(0, options.limit));
2378
+ let records = [];
2379
+ for (let { record: record5, selection: selection3, fragment: fragment2 } of matching) records.push(yield* expand(record5, selection3, fragment2));
2380
+ expanded = link.many ? records : records[0] ?? null;
2381
+ }
2382
+ Object.defineProperty(result2, link.name, { value: expanded, enumerable: !0, writable: !0, configurable: !0 });
2383
+ }
2384
+ return result2;
2385
+ }
2386
+ let metadata = { version, collections: {} }, results = [];
2387
+ for (let { name: name2, selection: selection2 } of selections) {
2388
+ let matching = scanned.get(name2).filter((record4) => matches(record4, selection2)).sort((a, b) => ordered(a, b, selection2.order)), binding = indexSelectionBinding(context, name2, selection2), start = selection2.after === void 0 ? 0 : continuation(yield { operation: "open", token: selection2.after }, binding, matching, selection2.limit), end = maxRecords === void 0 ? Math.min(start + selection2.limit, matching.length) : matching.length, records = [];
2389
+ for (let index = start; index < end; index++)
2390
+ maxRecords !== void 0 && (index - start) % selection2.limit === 0 && (occurrences = 0), records.push(yield* expand(matching[index], selection2));
2391
+ let page = selection2.count ? { count: matching.length } : {};
2392
+ if (maxRecords === void 0 && end < matching.length) {
2393
+ let token = yield { operation: "seal", payload: { format: 1, binding, position: end, ref: matching[end - 1].$ref } };
2394
+ if (typeof token != "string" || token.length === 0) return fail4("invalid sealed cursor");
2395
+ page.next = token;
2396
+ }
2397
+ Object.keys(page).length && Object.defineProperty(metadata.collections, name2, {
2398
+ value: page,
2399
+ enumerable: !0,
2400
+ writable: !0,
2401
+ configurable: !0
2402
+ }), results.push([name2, records]);
2403
+ }
2404
+ return { ...Object.fromEntries(results), $meta: metadata };
2405
+ }
2406
+
2407
+ 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);
2408
+
2409
+ var unavailable2 = () => {
2410
+ throw new DataOperationError("unavailable", !0);
2411
+ };
2412
+ function request(value) {
2413
+ return new Promise((resolve, reject) => {
2414
+ value.onsuccess = () => resolve(value.result), value.onerror = () => reject(new DataOperationError("unavailable", !0));
2415
+ });
2416
+ }
2417
+ function completed(transaction) {
2418
+ let done = new Promise((resolve, reject) => {
2419
+ transaction.oncomplete = () => resolve(), transaction.onabort = transaction.onerror = () => reject(new DataOperationError("unavailable", !0));
2420
+ });
2421
+ return done.catch(() => {
2422
+ }), done;
2423
+ }
2424
+ function encode(bytes) {
2425
+ return btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""));
2426
+ }
2427
+ async function openSnapshotStore() {
2428
+ let opening = indexedDB.open("oddington.data.snapshots.v2", 1);
2429
+ opening.onupgradeneeded = () => {
2430
+ opening.result.createObjectStore("current"), opening.result.createObjectStore("changes"), opening.result.createObjectStore("records", { keyPath: ["installation", "ref"] }).createIndex("collection", ["installation", "collection"]);
2431
+ };
2432
+ let database = await request(opening);
2433
+ return database.onversionchange = () => database.close(), {
2434
+ close() {
2435
+ database.close();
2436
+ },
2437
+ async current(partition) {
2438
+ let transaction = database.transaction(["current", "records", "changes"], "readonly"), done = completed(transaction), value = await request(transaction.objectStore("current").get(partition));
2439
+ if (!value) {
2440
+ await done;
2441
+ return;
2442
+ }
2443
+ if (value.partition !== partition || !value.id || !validSnapshotPairToken(value.pairToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
2444
+ await done;
2445
+ return;
2446
+ }
2447
+ let changes = await request(transaction.objectStore("changes").get(value.id)), complete = Array.isArray(changes) && changes.length === value.changeCount;
2448
+ for (let collection of value.catalogue)
2449
+ await request(transaction.objectStore("records").index("collection").count([value.id, collection.name])) !== value.counts[collection.name] && (complete = !1);
2450
+ return await done, complete ? value : void 0;
2451
+ },
2452
+ async install(partition, pairToken, envelope, changes, assertCurrent) {
2453
+ let installation = {
2454
+ id: crypto.randomUUID(),
2455
+ partition,
2456
+ pairToken,
2457
+ version: envelope.version,
2458
+ catalogue: envelope.catalogue,
2459
+ changeCount: changes.length,
2460
+ cursorKey: crypto.getRandomValues(new Uint8Array(32)),
2461
+ counts: Object.fromEntries(Object.entries(envelope.collections).map(([name2, rows]) => [name2, rows.length]))
2462
+ }, transaction = database.transaction(["current", "records", "changes"], "readwrite"), done = completed(transaction);
2463
+ try {
2464
+ assertCurrent();
2465
+ let records = transaction.objectStore("records");
2466
+ for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
2467
+ records.put({ installation: installation.id, collection, ref: record4.$ref, record: record4 });
2468
+ return await request(transaction.objectStore("changes").put(changes, installation.id)), await request(transaction.objectStore("current").put(installation, partition)), assertCurrent(), await done, assertCurrent(), installation;
2469
+ } catch (error) {
2470
+ try {
2471
+ transaction.abort();
2472
+ } catch {
2473
+ }
2474
+ throw await done.catch(() => {
2475
+ }), error;
2476
+ }
2477
+ },
2478
+ async read(installation, ref) {
2479
+ let transaction = database.transaction("records", "readonly"), done = completed(transaction), row = await request(transaction.objectStore("records").get([installation.id, ref])), collection = ref.split("/")[0], count = await request(transaction.objectStore("records").index("collection").count([installation.id, collection]));
2480
+ return await done, count !== installation.counts[collection] ? unavailable2() : row?.record ?? null;
2481
+ },
2482
+ async changes(installation) {
2483
+ let transaction = database.transaction("changes", "readonly"), done = completed(transaction), rows = await request(transaction.objectStore("changes").get(installation.id));
2484
+ return await done, !rows || rows.length !== installation.changeCount ? unavailable2() : rows;
2485
+ },
2486
+ async query(installation, query, maxRecords) {
2487
+ let key = await crypto.subtle.importKey("raw", installation.cursorKey, "AES-GCM", !1, ["encrypt", "decrypt"]), transaction, done, records = () => (transaction || (transaction = database.transaction("records", "readonly"), done = completed(transaction)), transaction.objectStore("records")), finish = async () => {
2488
+ await done, transaction = void 0, done = void 0;
2489
+ }, evaluation = evaluateRecordsQuery(query, installation.catalogue, {
2490
+ workspaceId: installation.partition,
2491
+ repository: installation.partition,
2492
+ identity: installation.id,
2493
+ version: installation.version
2494
+ }, maxRecords);
2495
+ try {
2496
+ let step = evaluation.next();
2497
+ for (; !step.done; ) {
2498
+ let work = step.value, value;
2499
+ if (work.operation === "scan") {
2500
+ let rows = await request(records().index("collection").getAll([installation.id, work.collection]));
2501
+ if (rows.length !== installation.counts[work.collection]) return unavailable2();
2502
+ value = rows.map((row) => row.record);
2503
+ } else if (work.operation === "lookup") {
2504
+ let row = await request(records().get([installation.id, work.ref]));
2505
+ value = row && { record: row.record, collection: row.collection };
2506
+ } else if (await finish(), work.operation === "seal") {
2507
+ let iv = crypto.getRandomValues(new Uint8Array(12)), sealed = new Uint8Array(await crypto.subtle.encrypt(
2508
+ { name: "AES-GCM", iv },
2509
+ key,
2510
+ new TextEncoder().encode(JSON.stringify(work.payload))
2511
+ ));
2512
+ value = encode(new Uint8Array([...iv, ...sealed]));
2513
+ } else
2514
+ try {
2515
+ let bytes = Uint8Array.from(atob(work.token), (c) => c.charCodeAt(0)), opened = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12) }, key, bytes.slice(12));
2516
+ value = JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(opened));
2517
+ } catch {
2518
+ throw new DataOperationError("invalid_query");
2519
+ }
2520
+ step = evaluation.next(value);
2521
+ }
2522
+ return await finish(), step.value;
2523
+ } catch (error) {
2524
+ try {
2525
+ transaction?.abort();
2526
+ } catch {
2527
+ }
2528
+ throw await done?.catch(() => {
2529
+ }), error;
2530
+ }
2531
+ }
2532
+ };
2533
+ }
2534
+
2535
+ var invalid8 = () => {
2536
+ throw new DataOperationError("unavailable", !0);
2537
+ }, 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));
2538
+ function validateAcquisition(input, repository, name2) {
2539
+ let row = object5(input), snapshot = object5(row.snapshot);
2540
+ if (Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== snapshotAcquisitionFormat || Object.keys(snapshot).sort().join(",") !== "collections,id,name,refreshedAt,repository,version" || !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 ids = /* @__PURE__ */ new Set(), unpublished = !1;
2542
+ for (let value of row.changes) {
2543
+ let c = object5(value), effect = object5(c.effect);
2544
+ if (!keys3(c, ["id", "version", "ref", "recordVersion", "effect", "updatedAt", "personId", "source", "publication"]) || !uuid(c.id) || ids.has(c.id) || !dataVersion(c.version) || !validRecordRef(c.ref) || !snapshot.collections.includes(c.ref.split("/")[0]) || !recordVersion(c.recordVersion) || !time(c.updatedAt) || c.personId !== void 0 && !uuid(c.personId)) return invalid8();
2545
+ if (ids.add(c.id), c.source !== void 0) {
2546
+ let source2 = object5(c.source);
2547
+ if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid8();
2548
+ }
2549
+ if (c.publication !== void 0) {
2550
+ let publication = object5(c.publication);
2551
+ 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();
2552
+ } else unpublished = !0;
2553
+ if (effect.kind === "set") {
2554
+ 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();
2555
+ } else if (effect.kind === "create" || effect.kind === "delete") {
2556
+ if (Object.keys(effect).sort().join(",") !== "fields,kind") return invalid8();
2557
+ object5(effect.fields);
2558
+ } else return invalid8();
2559
+ }
2560
+ return {
2561
+ snapshot,
2562
+ changes: row.changes
2563
+ };
2564
+ }
2565
+ function materializeSnapshot(envelope, changes, version) {
2566
+ try {
2567
+ if (!changes.length) return envelope;
2568
+ let rows = new Map(Object.values(envelope.collections).flat().map((r) => [r.$ref, structuredClone(r)]));
2569
+ for (let c of changes) {
2570
+ let schema2 = envelope.catalogue.find((s) => c.ref.startsWith(`${s.name}/`));
2571
+ if (!schema2) return invalid8();
2572
+ let effect = c.effect, definitions2 = effect.kind === "set" ? schema2.schema.fields.filter((f) => f.name === effect.field) : schema2.schema.fields;
2573
+ if (effect.kind === "set" && !definitions2.length) return invalid8();
2574
+ if (validateRecordFields(
2575
+ effect.kind === "set" ? { [effect.field]: effect.value } : effect.fields,
2576
+ definitions2,
2577
+ (_ref, targets) => targets[0],
2578
+ !0
2579
+ ), !c.publication) continue;
2580
+ let prior = rows.get(c.ref);
2581
+ if (effect.kind === "set") {
2582
+ if (!prior) return invalid8();
2583
+ rows.set(c.ref, { ...prior, [effect.field]: effect.value, $version: c.recordVersion });
2584
+ } else if (effect.kind === "create") {
2585
+ if (prior) return invalid8();
2586
+ rows.set(c.ref, { ...effect.fields, $ref: c.ref, $version: c.recordVersion });
2587
+ } else {
2588
+ if (!prior) return invalid8();
2589
+ rows.delete(c.ref);
2590
+ }
2591
+ }
2592
+ return validateSnapshotEnvelope({
2593
+ format: envelope.format,
2594
+ repository: envelope.repository,
2595
+ name: envelope.name,
2596
+ version,
2597
+ schemas: Object.fromEntries(envelope.catalogue.map((c) => [c.name, {
2598
+ name: c.name,
2599
+ type: c.schema.type,
2600
+ ...c.schema.description === void 0 ? {} : { description: c.schema.description },
2601
+ fields: c.schema.fields.map(publicField)
2602
+ }])),
2603
+ collections: Object.fromEntries(envelope.catalogue.map((c) => [c.name, [...rows.values()].filter((r) => r.$ref.startsWith(`${c.name}/`)).sort((a, b) => a.$ref < b.$ref ? -1 : 1)]))
2604
+ }, envelope.repository, envelope.name);
2605
+ } catch {
2606
+ return invalid8();
2607
+ }
2608
+ }
2609
+
2610
+ var invalid9 = () => {
2611
+ throw new DataOperationError("invalid_query");
2612
+ }, safeName = (value) => typeof value == "string" && /^[a-z0-9][a-z0-9._-]{0,127}$/.test(value) && !value.includes("..");
2613
+ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore) {
2614
+ let pending = /* @__PURE__ */ new WeakMap();
2615
+ return async function(input) {
2616
+ let properties = dataProperties(input), repository = properties.repository?.value, snapshot = properties.snapshot?.value;
2617
+ if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid9();
2618
+ let authority2 = await resolve(), invalidated = !1, assertCurrent = () => {
2619
+ if (invalidated || !authority2.isCurrent())
2620
+ throw invalidated = !0, new DataOperationError("context_unavailable");
2621
+ };
2622
+ assertCurrent();
2623
+ let partition = JSON.stringify([authority2.endpoint, authority2.memberId, authority2.workspace, repository, snapshot]), work = pending.get(authority2.binding);
2624
+ work || (work = /* @__PURE__ */ new Map(), pending.set(authority2.binding, work));
2625
+ let installing = work.get(partition);
2626
+ installing || (installing = (async () => {
2627
+ let store = await open();
2628
+ try {
2629
+ let current2 = await store.current(partition), cached = current2 && validSnapshotPairToken(current2.pairToken) ? current2 : void 0;
2630
+ assertCurrent();
2631
+ let url = `${authority2.endpoint}/api/data/snapshots/${repository}/${snapshot}`;
2632
+ for (let attempt = 0; attempt < 3; attempt++) {
2633
+ let response2 = await fetch(url, {
2634
+ method: "GET",
2635
+ redirect: "error",
2636
+ cache: "no-store",
2637
+ headers: {
2638
+ ...authority2.headers,
2639
+ accept: snapshotAcquisitionType,
2640
+ ...cached ? { [snapshotPairHeader]: cached.pairToken } : {}
2641
+ }
2642
+ });
2643
+ if (assertCurrent(), response2.status === 409) {
2644
+ await response2.body?.cancel();
2645
+ continue;
2646
+ }
2647
+ let pairToken = response2.headers.get(snapshotPairHeader);
2648
+ if (response2.status === 204) {
2649
+ if (!cached || pairToken !== cached.pairToken) throw new DataOperationError("unavailable", !0);
2650
+ return cached;
2651
+ }
2652
+ if (!response2.ok) throw dataTransportError(response2.status, await response2.json().catch(() => {
2653
+ }));
2654
+ if (response2.status !== 200 || !validSnapshotPairToken(pairToken) || response2.headers.get("content-type")?.split(";")[0] !== "application/json") throw new DataOperationError("unavailable", !0);
2655
+ let acquired = validateAcquisition(await response2.json(), repository, snapshot);
2656
+ assertCurrent();
2657
+ let artifact = await fetch(url, {
2658
+ method: "GET",
2659
+ redirect: "error",
2660
+ cache: "no-store",
2661
+ headers: { ...authority2.headers, accept: "application/gzip", [snapshotPairHeader]: pairToken }
2662
+ });
2663
+ if (assertCurrent(), artifact.status === 409) {
2664
+ await artifact.body?.cancel();
2665
+ continue;
2666
+ }
2667
+ if (!artifact.ok) throw dataTransportError(artifact.status, await artifact.json().catch(() => {
2668
+ }));
2669
+ if (artifact.status !== 200 || artifact.headers.get(snapshotPairHeader) !== pairToken || !artifact.body || artifact.headers.get("content-type")?.split(";")[0] !== "application/gzip") throw new DataOperationError("unavailable", !0);
2670
+ let decompressed = artifact.body.pipeThrough(new DecompressionStream("gzip")), text5 = await new Response(decompressed).arrayBuffer(), envelope = validateSnapshotEnvelope(JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(text5)), repository, snapshot);
2671
+ if (envelope.version !== acquired.snapshot.version || envelope.catalogue.map((c) => c.name).join("\0") !== acquired.snapshot.collections.join("\0")) throw new DataOperationError("unavailable", !0);
2672
+ let published = acquired.changes.filter((c) => c.publication), version = envelope.version;
2673
+ if (published.length) {
2674
+ let digest = new Uint8Array(await crypto.subtle.digest(
2675
+ "SHA-256",
2676
+ new TextEncoder().encode(JSON.stringify([envelope.version, published]))
2677
+ ));
2678
+ version = `snapshot-${Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
2679
+ }
2680
+ let materialized = materializeSnapshot(envelope, acquired.changes, version);
2681
+ return assertCurrent(), await store.install(partition, pairToken, materialized, acquired.changes, assertCurrent);
2682
+ }
2683
+ throw new DataOperationError("unavailable", !0);
2684
+ } finally {
2685
+ store.close();
2686
+ }
2687
+ })(), work.set(partition, installing), installing.finally(() => {
2688
+ work.get(partition) === installing && work.delete(partition);
2689
+ }).catch(() => {
2690
+ }));
2691
+ let installation;
2692
+ try {
2693
+ installation = await installing, assertCurrent();
2694
+ } catch (error) {
2695
+ throw assertCurrent(), error instanceof DataOperationError ? error : new DataOperationError("unavailable", !0);
2696
+ }
2697
+ let query = async (query2, maxRecords) => {
2698
+ assertCurrent();
2699
+ let captured = captureRecordsQuery(query2);
2700
+ checkDataRequestSize({
2701
+ repository,
2702
+ operation: maxRecords === void 0 ? "records.query" : "records.all",
2703
+ query: captured,
2704
+ ...maxRecords === void 0 ? {} : { maxRecords }
2705
+ });
2706
+ let store;
2707
+ try {
2708
+ store = await open(), assertCurrent();
2709
+ let result2 = await store.query(installation, captured, maxRecords);
2710
+ return assertCurrent(), result2;
2711
+ } catch (error) {
2712
+ throw assertCurrent(), error instanceof DataOperationError ? error : error instanceof RecordValidationError ? new DataOperationError("invalid_query") : new DataOperationError("unavailable", !0);
2713
+ } finally {
2714
+ store?.close();
2715
+ }
2716
+ }, localRead = async (operation2) => {
2717
+ assertCurrent();
2718
+ let store;
2719
+ try {
2720
+ store = await open(), assertCurrent();
2721
+ let value = await operation2(store);
2722
+ return assertCurrent(), value;
2723
+ } catch (error) {
2724
+ throw assertCurrent(), error instanceof DataOperationError ? error : new DataOperationError("unavailable", !0);
2725
+ } finally {
2726
+ store?.close();
2727
+ }
2728
+ }, queryRecords = query;
2729
+ return { changes: { list: () => localRead((store) => store.changes(installation)) }, records: {
2730
+ read: async (ref, ...extra) => {
2731
+ if (typeof ref != "string" || extra.length) return Promise.reject(new DataOperationError("invalid_query"));
2732
+ let [captured] = captureRecordsReadRefs([ref]);
2733
+ return installation.catalogue.some((c) => captured.startsWith(`${c.name}/`)) ? localRead((store) => store.read(installation, captured)) : Promise.reject(new DataOperationError("invalid_query"));
2734
+ },
2735
+ query: queryRecords,
2736
+ ...recordPagination(queryRecords),
2737
+ all: (input2, options) => {
2738
+ let captured = captureRecordsAll(input2, options);
2739
+ return query(captured.query, captured.maxRecords);
2740
+ }
2741
+ } };
2742
+ };
2743
+ }
2744
+ var initializeSnapshot = /* @__PURE__ */ createSnapshotInitializer();
2745
+
1861
2746
  var genericData = {
2747
+ init: initializeSnapshot,
1862
2748
  repository(repository) {
1863
2749
  async function send3(input) {
1864
2750
  let context = await resolveDataContext(), envelope = { repository, ...input }, changing = "operation" in input && ["changes.validate", "changes.apply", "changes.publish"].includes(String(input.operation));
@@ -2015,7 +2901,7 @@ async function hostedContent(url, init2, parent, upstream = fetch, check = async
2015
2901
  }
2016
2902
  }
2017
2903
 
2018
- 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 = [], invalid7 = () => new FileOperationError("invalid_input", 400), unavailable2 = () => new FileOperationError("unavailable", 503, !0), failures = {
2904
+ 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), unavailable3 = () => new FileOperationError("unavailable", 503, !0), failures = {
2019
2905
  400: ["invalid_input", "unsupported_context"],
2020
2906
  401: ["unauthenticated"],
2021
2907
  403: ["access_denied"],
@@ -2044,7 +2930,7 @@ function heldSlot() {
2044
2930
  };
2045
2931
  }
2046
2932
  async function acquireSlot(signal) {
2047
- if (signal?.aborted) throw unavailable2();
2933
+ if (signal?.aborted) throw unavailable3();
2048
2934
  return active < MAX_ACTIVE ? (active++, heldSlot()) : new Promise((resolve, reject) => {
2049
2935
  let waiter = {
2050
2936
  signal,
@@ -2055,7 +2941,7 @@ async function acquireSlot(signal) {
2055
2941
  if (!waiter.waiting) return;
2056
2942
  waiter.waiting = !1;
2057
2943
  let index = waiters.indexOf(waiter);
2058
- index !== -1 && waiters.splice(index, 1), reject(unavailable2());
2944
+ index !== -1 && waiters.splice(index, 1), reject(unavailable3());
2059
2945
  }
2060
2946
  };
2061
2947
  waiters.push(waiter), signal?.addEventListener("abort", waiter.abort, { once: !0 }), signal?.aborted && waiter.abort();
@@ -2071,7 +2957,7 @@ async function boundedBytes(stream, limit, signal) {
2071
2957
  try {
2072
2958
  for (; ; ) {
2073
2959
  let { done, value } = await reader.read();
2074
- if (signal?.aborted) throw unavailable2();
2960
+ if (signal?.aborted) throw unavailable3();
2075
2961
  if (done) break;
2076
2962
  if (!(value instanceof Uint8Array)) throw new FileOperationError("invalid_input", 400, !1, { reason: "invalid_bytes" });
2077
2963
  if (size += value.byteLength, size > limit) throw new FileOperationError(
@@ -2092,7 +2978,7 @@ async function boundedBytes(stream, limit, signal) {
2092
2978
  async function timed(work, parent, timeout = TIMEOUT_MS) {
2093
2979
  let controller = new AbortController(), timer, abort, expiry = new Promise((_, reject) => {
2094
2980
  abort = () => {
2095
- controller.abort(), reject(unavailable2());
2981
+ controller.abort(), reject(unavailable3());
2096
2982
  }, timer = setTimeout(abort, timeout), parent?.addEventListener("abort", abort, { once: !0 }), parent?.aborted && abort();
2097
2983
  });
2098
2984
  try {
@@ -2106,12 +2992,12 @@ async function result(response2, maximum = RESULT_BYTES) {
2106
2992
  let bytes = await boundedBytes(response2.body, maximum);
2107
2993
  return JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes));
2108
2994
  } catch {
2109
- throw unavailable2();
2995
+ throw unavailable3();
2110
2996
  }
2111
2997
  }
2112
2998
  async function send(suffix, init2, descriptor, initial, parent) {
2113
2999
  let original = initial, checkCurrent = (context = original) => {
2114
- if (parent?.aborted) throw unavailable2();
3000
+ if (parent?.aborted) throw unavailable3();
2115
3001
  if (!original.isCurrent() || context.url !== original.url) throw new FileOperationError("unsupported_context", 400);
2116
3002
  };
2117
3003
  for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
@@ -2120,14 +3006,14 @@ async function send(suffix, init2, descriptor, initial, parent) {
2120
3006
  checkCurrent(context);
2121
3007
  try {
2122
3008
  let response2 = context.localFiles ? await context.localFiles(suffix, init2, parent) : await (async () => {
2123
- let url = `${context.url}${suffix}`, request2 = {
3009
+ let url = `${context.url}${suffix}`, request3 = {
2124
3010
  ...init2,
2125
3011
  signal: parent,
2126
3012
  headers: { ...context.headers, ...init2.headers },
2127
3013
  redirect: "error",
2128
3014
  cache: "no-store"
2129
3015
  };
2130
- return descriptor ? fetch(url, request2) : hostedContent(url, request2, parent);
3016
+ return descriptor ? fetch(url, request3) : hostedContent(url, request3, parent);
2131
3017
  })();
2132
3018
  if (!response2.ok) {
2133
3019
  let value2 = await result(response2), error = value2 && typeof value2 == "object" && "error" in value2 ? value2.error : void 0, received = error && typeof error == "object" && "code" in error ? error.code : void 0, code = failures[response2.status]?.find((code2) => code2 === received);
@@ -2136,11 +3022,11 @@ async function send(suffix, init2, descriptor, initial, parent) {
2136
3022
  response2.status,
2137
3023
  code === "capacity" || code === "unavailable",
2138
3024
  parseFileErrorDetail(error?.detail)
2139
- ) : unavailable2();
3025
+ ) : unavailable3();
2140
3026
  }
2141
3027
  if (response2.status !== 200)
2142
3028
  throw response2.body?.cancel().catch(() => {
2143
- }), unavailable2();
3029
+ }), unavailable3();
2144
3030
  try {
2145
3031
  checkCurrent();
2146
3032
  } catch (error) {
@@ -2153,25 +3039,25 @@ async function send(suffix, init2, descriptor, initial, parent) {
2153
3039
  return checkCurrent(), value;
2154
3040
  let parsed;
2155
3041
  if (descriptor === "enrichment") {
2156
- if (!value || typeof value != "object" || Array.isArray(value)) throw unavailable2();
3042
+ if (!value || typeof value != "object" || Array.isArray(value)) throw unavailable3();
2157
3043
  let { name: name2, ...metadata } = value;
2158
- if (!safeEnrichmentName(name2)) throw unavailable2();
3044
+ if (!safeEnrichmentName(name2)) throw unavailable3();
2159
3045
  parsed = { name: name2, ...parseEnrichmentDescriptor(metadata) };
2160
3046
  } else parsed = parseFileDescriptor(value);
2161
3047
  return checkCurrent(), parsed;
2162
3048
  } catch (error) {
2163
- let failure = error instanceof FileOperationError ? error : unavailable2();
3049
+ let failure = error instanceof FileOperationError ? error : unavailable3();
2164
3050
  if (init2.body instanceof ReadableStream || !failure.retryable || attempt + 1 === ATTEMPTS) throw failure;
2165
3051
  }
2166
3052
  }
2167
- throw unavailable2();
3053
+ throw unavailable3();
2168
3054
  }
2169
3055
  function idPath(id3) {
2170
- if (typeof id3 != "string" || !FILE_ID_PATTERN.test(id3)) throw invalid7();
3056
+ if (typeof id3 != "string" || !FILE_ID_PATTERN.test(id3)) throw invalid10();
2171
3057
  return `/${id3}`;
2172
3058
  }
2173
3059
  async function multipartCreate(input, metadata, exchange, release, upload, expectedSha256) {
2174
- let route = upload ? `${idPath(upload.file.id)}/upload/multipart` : "/multipart", ticket, reader, chunk, offset = 0, receipts = [], pending = /* @__PURE__ */ new Set(), request2 = (work, timeout = TIMEOUT_MS) => timed((signal) => {
3060
+ let route = upload ? `${idPath(upload.file.id)}/upload/multipart` : "/multipart", ticket, reader, chunk, offset = 0, receipts = [], pending = /* @__PURE__ */ new Set(), request3 = (work, timeout = TIMEOUT_MS) => timed((signal) => {
2175
3061
  let task = work(signal);
2176
3062
  return pending.add(task), task.then(() => pending.delete(task), () => pending.delete(task)), task;
2177
3063
  }, void 0, timeout), control = (body) => ({
@@ -2182,15 +3068,15 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
2182
3068
  try {
2183
3069
  let startRequest = control(upload?.file ?? metadata);
2184
3070
  expectedSha256 && (startRequest.headers["x-os-original-sha256"] = expectedSha256);
2185
- let start = await request2((signal) => exchange(`${route}/start`, startRequest, "control", signal));
2186
- if (!start || typeof start != "object" || Array.isArray(start)) throw unavailable2();
3071
+ let start = await request3((signal) => exchange(`${route}/start`, startRequest, "control", signal));
3072
+ if (!start || typeof start != "object" || Array.isArray(start)) throw unavailable3();
2187
3073
  let session = start;
2188
- if (Object.keys(session).sort().join(",") !== "partBytes,ticket" || session.partBytes !== PART_BYTES || typeof session.ticket != "string" || !session.ticket || session.ticket.length > 64 * 1024) throw unavailable2();
3074
+ if (Object.keys(session).sort().join(",") !== "partBytes,ticket" || session.partBytes !== PART_BYTES || typeof session.ticket != "string" || !session.ticket || session.ticket.length > 64 * 1024) throw unavailable3();
2189
3075
  ticket = session.ticket, input.file instanceof ReadableStream && (reader = input.file.getReader());
2190
3076
  let lastProgress = Date.now(), next = async () => {
2191
3077
  try {
2192
- if (Date.now() - lastProgress >= TIMEOUT_MS) throw unavailable2();
2193
- let value = await request2(() => reader.read(), Math.max(1, TIMEOUT_MS - (Date.now() - lastProgress)));
3078
+ if (Date.now() - lastProgress >= TIMEOUT_MS) throw unavailable3();
3079
+ let value = await request3(() => reader.read(), Math.max(1, TIMEOUT_MS - (Date.now() - lastProgress)));
2194
3080
  return value.value?.byteLength && (lastProgress = Date.now()), value;
2195
3081
  } catch (error) {
2196
3082
  throw await reader.cancel(error).catch(() => {
@@ -2202,7 +3088,7 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
2202
3088
  if (input.file instanceof Uint8Array) part = new Uint8Array(input.file.subarray(sent, sent + length));
2203
3089
  else if (input.file instanceof Blob) {
2204
3090
  let slice = input.file.slice(sent, sent + length);
2205
- part = new Uint8Array(await request2(() => slice.arrayBuffer()));
3091
+ part = new Uint8Array(await request3(() => slice.arrayBuffer()));
2206
3092
  } else {
2207
3093
  part = new Uint8Array(length);
2208
3094
  let filled = 0;
@@ -2210,33 +3096,33 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
2210
3096
  if (!chunk || offset === chunk.byteLength) {
2211
3097
  chunk = void 0, offset = 0;
2212
3098
  let value2 = await next();
2213
- if (value2.done || !(value2.value instanceof Uint8Array) || (chunk = value2.value, chunk.byteLength > metadata.size - sent - filled)) throw invalid7();
3099
+ if (value2.done || !(value2.value instanceof Uint8Array) || (chunk = value2.value, chunk.byteLength > metadata.size - sent - filled)) throw invalid10();
2214
3100
  }
2215
3101
  let take = Math.min(length - filled, chunk.byteLength - offset);
2216
3102
  part.set(chunk.subarray(offset, offset + take), filled), filled += take, offset += take, offset === chunk.byteLength && (chunk = void 0, offset = 0);
2217
3103
  }
2218
3104
  }
2219
- if (part.byteLength !== length) throw invalid7();
3105
+ if (part.byteLength !== length) throw invalid10();
2220
3106
  if (reader && sent + length === metadata.size)
2221
3107
  for (lastProgress = Date.now(); ; ) {
2222
3108
  let value2 = await next();
2223
3109
  if (value2.done) break;
2224
- if (!(value2.value instanceof Uint8Array) || value2.value.byteLength) throw invalid7();
3110
+ if (!(value2.value instanceof Uint8Array) || value2.value.byteLength) throw invalid10();
2225
3111
  }
2226
- let value = await request2((signal) => exchange(`${route}/part`, {
3112
+ let value = await request3((signal) => exchange(`${route}/part`, {
2227
3113
  method: "POST",
2228
3114
  headers: { "content-type": "application/octet-stream", "x-os-transfer": ticket, "x-os-part": String(partNumber) },
2229
3115
  body: part.buffer
2230
3116
  }, "control", signal));
2231
3117
  part = void 0;
2232
3118
  let receipt = value;
2233
- if (!receipt || typeof receipt != "object" || Object.keys(receipt).sort().join(",") !== "etag,partNumber" || receipt.partNumber !== partNumber || typeof receipt.etag != "string" || !receipt.etag || receipt.etag.length > 256 || /[\u0000-\u001f\u007f]/.test(receipt.etag)) throw unavailable2();
3119
+ if (!receipt || typeof receipt != "object" || Object.keys(receipt).sort().join(",") !== "etag,partNumber" || receipt.partNumber !== partNumber || typeof receipt.etag != "string" || !receipt.etag || receipt.etag.length > 256 || /[\u0000-\u001f\u007f]/.test(receipt.etag)) throw unavailable3();
2234
3120
  receipts.push({ partNumber, etag: receipt.etag }), sent += length, lastProgress = Date.now();
2235
3121
  }
2236
3122
  if (upload) for (let name2 of Object.keys(upload.file.enrichments)) {
2237
- let bytes = await request2(() => upload.enrichment(name2));
2238
- if (bytes.byteLength !== upload.file.enrichments[name2].size || bytes.byteLength > MAX_BYTES) throw invalid7();
2239
- await request2((signal) => exchange(`${route}/enrichments/${encodeURIComponent(name2)}`, {
3123
+ let bytes = await request3(() => upload.enrichment(name2));
3124
+ if (bytes.byteLength !== upload.file.enrichments[name2].size || bytes.byteLength > MAX_BYTES) throw invalid10();
3125
+ await request3((signal) => exchange(`${route}/enrichments/${encodeURIComponent(name2)}`, {
2240
3126
  method: "POST",
2241
3127
  headers: { "content-type": "application/octet-stream", "x-os-transfer": ticket },
2242
3128
  body: bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
@@ -2244,20 +3130,20 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
2244
3130
  }
2245
3131
  await upload?.beforeComplete();
2246
3132
  let completion = control({ parts: receipts });
2247
- if (new TextEncoder().encode(completion.body).byteLength > 128 * 1024) throw unavailable2();
2248
- let completed = parseFileDescriptor(await request2(
3133
+ if (new TextEncoder().encode(completion.body).byteLength > 128 * 1024) throw unavailable3();
3134
+ let completed2 = parseFileDescriptor(await request3(
2249
3135
  (signal) => exchange(`${route}/complete`, completion, !0, signal),
2250
3136
  TIMEOUT_MS + Math.ceil(metadata.size / (1024 * 1024)) * 1e3
2251
3137
  ));
2252
3138
  if (!upload) {
2253
- let acknowledged = await request2((signal) => exchange(`${route}/acknowledge`, control(completed), "control", signal));
2254
- if (!acknowledged || typeof acknowledged != "object" || Object.keys(acknowledged).join(",") !== "acknowledged" || acknowledged.acknowledged !== !0) throw unavailable2();
3139
+ let acknowledged = await request3((signal) => exchange(`${route}/acknowledge`, control(completed2), "control", signal));
3140
+ if (!acknowledged || typeof acknowledged != "object" || Object.keys(acknowledged).join(",") !== "acknowledged" || acknowledged.acknowledged !== !0) throw unavailable3();
2255
3141
  }
2256
- return completed;
3142
+ return completed2;
2257
3143
  } catch (error) {
2258
3144
  throw reader && await reader.cancel(error).catch(() => {
2259
- }), ticket && await request2((signal) => exchange(`${route}/abort`, control({}), "control", signal)).catch(() => {
2260
- }), error instanceof FileOperationError ? error : unavailable2();
3145
+ }), ticket && await request3((signal) => exchange(`${route}/abort`, control({}), "control", signal)).catch(() => {
3146
+ }), error instanceof FileOperationError ? error : unavailable3();
2261
3147
  } finally {
2262
3148
  chunk = void 0, reader?.releaseLock(), pending.size ? Promise.allSettled([...pending]).then(release) : release();
2263
3149
  }
@@ -2271,13 +3157,13 @@ async function operation(work, initial, parent) {
2271
3157
  }
2272
3158
  };
2273
3159
  return context.localFiles ? execute(signal ?? new AbortController().signal) : timed(execute, signal).catch((error) => {
2274
- throw error instanceof FileOperationError ? error : unavailable2();
3160
+ throw error instanceof FileOperationError ? error : unavailable3();
2275
3161
  });
2276
3162
  }
2277
3163
  function contentPath(id3, name2) {
2278
3164
  let path = idPath(id3);
2279
3165
  if (name2 === void 0) return `${path}/content`;
2280
- if (!safeEnrichmentName(name2)) throw invalid7();
3166
+ if (!safeEnrichmentName(name2)) throw invalid10();
2281
3167
  return `${path}/enrichments/${encodeURIComponent(name2)}/content`;
2282
3168
  }
2283
3169
  async function read(id3, names) {
@@ -2286,12 +3172,12 @@ async function read(id3, names) {
2286
3172
  let path = contentPath(id3, names);
2287
3173
  return operation((context2, signal) => send(path, { method: "GET" }, !1, context2, signal), context);
2288
3174
  }
2289
- if (!Array.isArray(names)) throw invalid7();
3175
+ if (!Array.isArray(names)) throw invalid10();
2290
3176
  let distinct = [], seen = /* @__PURE__ */ new Set();
2291
3177
  for (let name2 of names) {
2292
- if (typeof name2 != "string" || !safeEnrichmentName(name2)) throw invalid7();
3178
+ if (typeof name2 != "string" || !safeEnrichmentName(name2)) throw invalid10();
2293
3179
  if (!seen.has(name2)) {
2294
- if (seen.size === 16) throw invalid7();
3180
+ if (seen.size === 16) throw invalid10();
2295
3181
  seen.add(name2), distinct.push(name2);
2296
3182
  }
2297
3183
  }
@@ -2316,16 +3202,16 @@ var files = {
2316
3202
  async upload(id3) {
2317
3203
  return operation(async (context, signal) => {
2318
3204
  let file2 = await send(`${idPath(id3)}/upload`, { method: "POST" }, !0, context, signal);
2319
- if (file2.id !== id3) throw unavailable2();
3205
+ if (file2.id !== id3) throw unavailable3();
2320
3206
  return file2;
2321
3207
  });
2322
3208
  },
2323
3209
  async create(input, options) {
2324
3210
  let context = await resolveFilesContext();
2325
3211
  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")))
2326
- throw invalid7();
3212
+ throw invalid10();
2327
3213
  let blob = input.file instanceof Blob, array3 = input.file instanceof Uint8Array, stream = input.file instanceof ReadableStream;
2328
- if (!blob && !array3 && !stream) throw invalid7();
3214
+ if (!blob && !array3 && !stream) throw invalid10();
2329
3215
  let intrinsic = blob ? input.file.size : array3 ? input.file.byteLength : void 0;
2330
3216
  if (intrinsic !== void 0 && input.size !== void 0 && input.size !== intrinsic)
2331
3217
  throw !Number.isSafeInteger(input.size) || input.size < 0 ? new FileOperationError("invalid_input", 400, !1, { reason: "invalid_size" }) : new FileOperationError(
@@ -2346,7 +3232,7 @@ var files = {
2346
3232
  }, FILE_ORIGINAL_MAX_BYTES);
2347
3233
  if (!context.local && !context.localFiles && metadata.storage === "local") throw new FileOperationError("unsupported_context", 400);
2348
3234
  let header = encodeURIComponent(JSON.stringify(metadata));
2349
- if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid7();
3235
+ if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid10();
2350
3236
  let release = await acquireSlot(context.signal);
2351
3237
  if (context.localFiles && !routineTransport() && metadata.size > MAX_BYTES)
2352
3238
  try {
@@ -2380,7 +3266,7 @@ var files = {
2380
3266
  !1,
2381
3267
  { reason: "size_mismatch", expectedBytes: metadata.size, receivedBytes: bytes.byteLength }
2382
3268
  );
2383
- if (signal.aborted) throw unavailable2();
3269
+ if (signal.aborted) throw unavailable3();
2384
3270
  return await send("", {
2385
3271
  method: "POST",
2386
3272
  headers: { "content-type": "application/octet-stream", "x-os-file": header },
@@ -2390,12 +3276,12 @@ var files = {
2390
3276
  release();
2391
3277
  }
2392
3278
  }, context.signal).catch((error) => {
2393
- throw error instanceof FileOperationError ? error : unavailable2();
3279
+ throw error instanceof FileOperationError ? error : unavailable3();
2394
3280
  });
2395
3281
  },
2396
3282
  async enrich(input) {
2397
3283
  let context = await resolveFilesContext();
2398
- 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 invalid7();
3284
+ 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();
2399
3285
  let path = `${idPath(input.file)}/enrichments`;
2400
3286
  if (typeof input.content == "string" ? input.content.length > MAX_BYTES : input.content.byteLength > MAX_BYTES)
2401
3287
  throw new FileOperationError("request_too_large", 413);
@@ -2412,12 +3298,12 @@ var files = {
2412
3298
  ...input.mediaType === void 0 ? {} : { mediaType: input.mediaType },
2413
3299
  ...input.replace === void 0 ? {} : { replace: input.replace }
2414
3300
  }, MAX_BYTES), header = encodeURIComponent(JSON.stringify(metadata));
2415
- if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid7();
3301
+ if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid10();
2416
3302
  let result2 = await send(path, { method: "POST", headers: {
2417
3303
  "content-type": "application/octet-stream",
2418
3304
  "x-os-enrichment": header
2419
3305
  }, body: bytes.buffer }, "enrichment", context2, signal);
2420
- if (result2.name !== metadata.name) throw unavailable2();
3306
+ if (result2.name !== metadata.name) throw unavailable3();
2421
3307
  return result2;
2422
3308
  }, context);
2423
3309
  },
@@ -2519,30 +3405,30 @@ var AirtableOperationError = class extends Error {
2519
3405
  };
2520
3406
 
2521
3407
  var recordId = (v) => typeof v == "string" && /^rec[A-Za-z0-9]+$/.test(v), tableId = (v) => typeof v == "string" && /^tbl[A-Za-z0-9]+$/.test(v);
2522
- function fail2(message2) {
3408
+ function fail5(message2) {
2523
3409
  throw new AirtableOperationError(message2);
2524
3410
  }
2525
- function object3(v) {
2526
- return (!v || typeof v != "object" || Array.isArray(v) || ![null, Object.prototype].includes(Object.getPrototypeOf(v))) && fail2("Invalid Airtable data"), v;
3411
+ function object6(v) {
3412
+ return (!v || typeof v != "object" || Array.isArray(v) || ![null, Object.prototype].includes(Object.getPrototypeOf(v))) && fail5("Invalid Airtable data"), v;
2527
3413
  }
2528
- function keys2(v, allowed, required = allowed) {
2529
- (Object.keys(v).some((k) => !allowed.includes(k)) || required.some((k) => !Object.hasOwn(v, k))) && fail2("Invalid Airtable input");
3414
+ function keys4(v, allowed, required = allowed) {
3415
+ (Object.keys(v).some((k) => !allowed.includes(k)) || required.some((k) => !Object.hasOwn(v, k))) && fail5("Invalid Airtable input");
2530
3416
  }
2531
3417
  function text3(v) {
2532
3418
  return typeof v == "string" && v.length > 0 && v.length <= 1024;
2533
3419
  }
2534
- function fields2(v, nonempty = !1) {
2535
- let result2 = object3(v);
2536
- (nonempty && !Object.keys(result2).length || Object.keys(result2).some((k) => !text3(k))) && fail2("Invalid Airtable fields");
3420
+ function fields3(v, nonempty = !1) {
3421
+ let result2 = object6(v);
3422
+ (nonempty && !Object.keys(result2).length || Object.keys(result2).some((k) => !text3(k))) && fail5("Invalid Airtable fields");
2537
3423
  try {
2538
3424
  return serializable(result2);
2539
3425
  } catch {
2540
- return fail2("Invalid Airtable fields");
3426
+ return fail5("Invalid Airtable fields");
2541
3427
  }
2542
3428
  }
2543
3429
  function record2(v) {
2544
- let r = object3(v);
2545
- return (!recordId(r.id) || r.createdTime !== void 0 && (typeof r.createdTime != "string" || !Number.isFinite(Date.parse(r.createdTime)))) && fail2("Malformed Airtable record"), { id: r.id, ...r.createdTime === void 0 ? {} : { createdTime: r.createdTime }, fields: fields2(r.fields) };
3430
+ let r = object6(v);
3431
+ 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) };
2546
3432
  }
2547
3433
  function equal(a, b) {
2548
3434
  if (a === b) return !0;
@@ -2557,7 +3443,7 @@ function createConnections(transport) {
2557
3443
  return { async get() {
2558
3444
  throw new Error("Connection unavailable");
2559
3445
  }, airtable(name2) {
2560
- (typeof name2 != "string" || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(name2)) && fail2("Invalid Airtable connection name");
3446
+ (typeof name2 != "string" || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(name2)) && fail5("Invalid Airtable connection name");
2561
3447
  let call = (operation2, input) => transport(name2, operation2, input);
2562
3448
  return {
2563
3449
  tables: { list: async () => await call("tables.list", {}) },
@@ -2573,12 +3459,12 @@ function createConnections(transport) {
2573
3459
  }
2574
3460
  async function executeAirtableOperation(authority2, operation2, raw, options = {}) {
2575
3461
  let { name: name2, baseId, accessToken } = authority2;
2576
- (!/^[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)) && fail2("Airtable connection unavailable");
3462
+ (!/^[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");
2577
3463
  let input;
2578
3464
  try {
2579
- input = object3(serializable(raw));
3465
+ input = object6(serializable(raw));
2580
3466
  } catch {
2581
- return fail2("Invalid Airtable input");
3467
+ return fail5("Invalid Airtable input");
2582
3468
  }
2583
3469
  let mutation = ["records.create", "records.update", "records.delete"].includes(operation2), receipt = (ids2) => ({
2584
3470
  provider: "airtable",
@@ -2588,7 +3474,7 @@ async function executeAirtableOperation(authority2, operation2, raw, options = {
2588
3474
  operation: operation2.slice(8),
2589
3475
  records: ids2.map((id3) => ({ id: id3 }))
2590
3476
  });
2591
- async function request2(path2, init2 = {}, write = !1) {
3477
+ async function request3(path2, init2 = {}, write = !1) {
2592
3478
  let response2;
2593
3479
  try {
2594
3480
  response2 = await (options.fetch ?? fetch)(`https://api.airtable.com/v0/${path2}`, {
@@ -2605,7 +3491,7 @@ async function executeAirtableOperation(authority2, operation2, raw, options = {
2605
3491
  }), new AirtableOperationError("Airtable request rejected", write && (response2.status >= 500 || response2.status === 408 || response2.status < 400) ? "uncertain" : "unapplied");
2606
3492
  try {
2607
3493
  if (!response2.headers.get("content-type")?.toLowerCase().includes("application/json")) throw new Error();
2608
- let value = object3(await response2.json()), safe = serializable(value);
3494
+ let value = object6(await response2.json()), safe = serializable(value);
2609
3495
  if (Object.hasOwn(value, "error") || JSON.stringify(safe).includes(accessToken)) throw new Error();
2610
3496
  return value;
2611
3497
  } catch {
@@ -2613,74 +3499,74 @@ async function executeAirtableOperation(authority2, operation2, raw, options = {
2613
3499
  }
2614
3500
  }
2615
3501
  if (operation2 === "tables.list") {
2616
- keys2(input, []);
3502
+ keys4(input, []);
2617
3503
  let tables = [], seen = /* @__PURE__ */ new Set(), offset;
2618
3504
  do {
2619
- let query2 = new URLSearchParams(offset ? { offset } : {}), page = await request2(`meta/bases/${baseId}/tables?${query2}`);
2620
- Array.isArray(page.tables) || fail2("Malformed Airtable tables");
3505
+ let query2 = new URLSearchParams(offset ? { offset } : {}), page = await request3(`meta/bases/${baseId}/tables?${query2}`);
3506
+ Array.isArray(page.tables) || fail5("Malformed Airtable tables");
2621
3507
  for (let value of page.tables) {
2622
- let t = object3(value);
2623
- (!tableId(t.id) || !text3(t.name) || !text3(t.primaryFieldId) || !Array.isArray(t.fields) || tables.some((existing) => existing.id === t.id)) && fail2("Malformed Airtable table");
3508
+ let t = object6(value);
3509
+ (!tableId(t.id) || !text3(t.name) || !text3(t.primaryFieldId) || !Array.isArray(t.fields) || tables.some((existing) => existing.id === t.id)) && fail5("Malformed Airtable table");
2624
3510
  let metadata = t.fields.map((value2) => {
2625
- let f = object3(value2);
2626
- return (typeof f.id != "string" || !/^fld[A-Za-z0-9]+$/.test(f.id) || !text3(f.name) || !text3(f.type)) && fail2("Malformed Airtable field"), { id: f.id, name: f.name, type: f.type, ...f.options === void 0 ? {} : { options: serializable(f.options) } };
3511
+ let f = object6(value2);
3512
+ 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) } };
2627
3513
  });
2628
- (!metadata.some((f) => f.id === t.primaryFieldId) || new Set(metadata.map((f) => f.id)).size !== metadata.length) && fail2("Malformed Airtable fields"), tables.push({ id: t.id, name: t.name, primaryFieldId: t.primaryFieldId, fields: metadata });
3514
+ (!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 });
2629
3515
  }
2630
3516
  offset = nextOffset(page.offset, seen);
2631
3517
  } while (offset);
2632
3518
  return tables;
2633
3519
  }
2634
- (!text3(input.table) || input.table === "." || input.table === "..") && fail2("Invalid Airtable table"), mutation && !tableId(input.table) && fail2("Airtable writes require a stable table ID");
3520
+ (!text3(input.table) || input.table === "." || input.table === "..") && fail5("Invalid Airtable table"), mutation && !tableId(input.table) && fail5("Airtable writes require a stable table ID");
2635
3521
  let path = `${baseId}/${encodeURIComponent(input.table)}`;
2636
3522
  if (operation2 === "records.get") {
2637
- keys2(input, ["table", "id"]), recordId(input.id) || fail2("Invalid Airtable record ID");
2638
- let result3 = record2(await request2(`${path}/${input.id}`));
2639
- return result3.id !== input.id && fail2("Malformed Airtable record"), result3;
3523
+ keys4(input, ["table", "id"]), recordId(input.id) || fail5("Invalid Airtable record ID");
3524
+ let result3 = record2(await request3(`${path}/${input.id}`));
3525
+ return result3.id !== input.id && fail5("Malformed Airtable record"), result3;
2640
3526
  }
2641
3527
  if (operation2 === "records.list") {
2642
- keys2(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) && fail2("Invalid Airtable field selection");
3528
+ 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");
2643
3529
  let records2 = [], ids2 = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set(), offset;
2644
3530
  do {
2645
3531
  let query2 = new URLSearchParams();
2646
3532
  for (let field of input.fields ?? []) query2.append("fields[]", field);
2647
3533
  offset && query2.set("offset", offset);
2648
- let page = await request2(`${path}?${query2}`);
2649
- Array.isArray(page.records) || fail2("Malformed Airtable records");
3534
+ let page = await request3(`${path}?${query2}`);
3535
+ Array.isArray(page.records) || fail5("Malformed Airtable records");
2650
3536
  for (let value of page.records) {
2651
3537
  let r = record2(value);
2652
- ids2.has(r.id) && fail2("Malformed Airtable pagination"), ids2.add(r.id), records2.push(r);
3538
+ ids2.has(r.id) && fail5("Malformed Airtable pagination"), ids2.add(r.id), records2.push(r);
2653
3539
  }
2654
3540
  offset = nextOffset(page.offset, seen);
2655
3541
  } while (offset);
2656
3542
  return records2;
2657
3543
  }
2658
- mutation || fail2("Unsupported Airtable operation"), keys2(input, ["table", "records"]), (!Array.isArray(input.records) || !input.records.length || input.records.length > 10) && fail2("Invalid Airtable batch");
3544
+ mutation || fail5("Unsupported Airtable operation"), keys4(input, ["table", "records"]), (!Array.isArray(input.records) || !input.records.length || input.records.length > 10) && fail5("Invalid Airtable batch");
2659
3545
  let kind = operation2.slice(8), ids = /* @__PURE__ */ new Set(), records = input.records.map((value) => {
2660
- let r = object3(value);
2661
- if (keys2(r, kind === "create" ? ["fields"] : kind === "update" ? ["id", "expected", "set"] : ["id", "expected"]), kind === "create") return { fields: fields2(r.fields, !0) };
2662
- (!recordId(r.id) || ids.has(r.id)) && fail2("Invalid Airtable batch record ID"), ids.add(r.id);
2663
- let set = kind === "update" ? fields2(r.set, !0) : void 0;
2664
- return set && Object.values(set).some((value2) => value2 === null) && fail2("Airtable guard null cannot be an update value"), { id: r.id, expected: fields2(r.expected), ...set ? { set } : {} };
3546
+ let r = object6(value);
3547
+ if (keys4(r, kind === "create" ? ["fields"] : kind === "update" ? ["id", "expected", "set"] : ["id", "expected"]), kind === "create") return { fields: fields3(r.fields, !0) };
3548
+ (!recordId(r.id) || ids.has(r.id)) && fail5("Invalid Airtable batch record ID"), ids.add(r.id);
3549
+ let set = kind === "update" ? fields3(r.set, !0) : void 0;
3550
+ 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 } : {} };
2665
3551
  });
2666
3552
  for (let r of records) {
2667
3553
  if (!("id" in r)) continue;
2668
- let current2 = record2(await request2(`${path}/${r.id}`));
2669
- current2.id !== r.id && fail2("Malformed Airtable record");
3554
+ let current2 = record2(await request3(`${path}/${r.id}`));
3555
+ current2.id !== r.id && fail5("Malformed Airtable record");
2670
3556
  for (let [key, value] of Object.entries(r.expected))
2671
- (value === null ? Object.hasOwn(current2.fields, key) : !Object.hasOwn(current2.fields, key) || !equal(current2.fields[key], value)) && fail2("Airtable reviewed values are stale");
3557
+ (value === null ? Object.hasOwn(current2.fields, key) : !Object.hasOwn(current2.fields, key) || !equal(current2.fields[key], value)) && fail5("Airtable reviewed values are stale");
2672
3558
  }
2673
3559
  await options.beforeMutation?.();
2674
3560
  let query = new URLSearchParams();
2675
3561
  if (kind === "delete") for (let id3 of ids) query.append("records[]", id3);
2676
- let result2 = await request2(`${path}${kind === "delete" ? `?${query}` : ""}`, {
3562
+ let result2 = await request3(`${path}${kind === "delete" ? `?${query}` : ""}`, {
2677
3563
  method: kind === "create" ? "POST" : kind === "update" ? "PATCH" : "DELETE",
2678
3564
  ...kind === "delete" ? {} : { body: JSON.stringify({ records: records.map((r) => "id" in r ? { id: r.id, fields: r.set } : r) }) }
2679
3565
  }, !0), acknowledged = [], returned = [];
2680
3566
  try {
2681
3567
  if (!Array.isArray(result2.records)) throw new Error();
2682
3568
  for (let value of result2.records) {
2683
- let r = object3(value);
3569
+ let r = object6(value);
2684
3570
  if (!recordId(r.id) || acknowledged.includes(r.id) || kind !== "create" && !ids.has(r.id) || kind === "delete" && r.deleted !== !0) throw new Error();
2685
3571
  acknowledged.push(r.id), kind !== "delete" && returned.push(record2(r));
2686
3572
  }
@@ -2696,7 +3582,7 @@ async function executeAirtableOperation(authority2, operation2, raw, options = {
2696
3582
  }
2697
3583
  function nextOffset(value, seen) {
2698
3584
  if (value !== void 0)
2699
- return (!text3(value) || seen.has(value)) && fail2("Malformed Airtable pagination"), seen.add(value), value;
3585
+ return (!text3(value) || seen.has(value)) && fail5("Malformed Airtable pagination"), seen.add(value), value;
2700
3586
  }
2701
3587
 
2702
3588
  var MANAGED_CONNECTION_CAPABILITY_ENV = "OS_MANAGED_CONNECTION_CAPABILITY";
@@ -2941,8 +3827,8 @@ var InboxOperationError = class extends Error {
2941
3827
  reason;
2942
3828
  };
2943
3829
  function parseQuestionAvailability(value, available = !1) {
2944
- let state = object4(value);
2945
- return keys3(state, ["unavailableReason"], []), "unavailableReason" in state ? (assert(!available && state.unavailableReason === "handler_unavailable"), { unavailableReason: state.unavailableReason }) : {};
3830
+ let state = object7(value);
3831
+ return keys5(state, ["unavailableReason"], []), "unavailableReason" in state ? (assert(!available && state.unavailableReason === "handler_unavailable"), { unavailableReason: state.unavailableReason }) : {};
2946
3832
  }
2947
3833
  function questionAvailability(value, available = !1) {
2948
3834
  return parseQuestionAvailability({
@@ -2951,9 +3837,9 @@ function questionAvailability(value, available = !1) {
2951
3837
  }
2952
3838
  function parseInboxUnavailableFailure(value, status) {
2953
3839
  try {
2954
- let envelope = object4(value);
3840
+ let envelope = object7(value);
2955
3841
  if (status === 409) {
2956
- keys3(envelope, ["error"]);
3842
+ keys5(envelope, ["error"]);
2957
3843
  for (let reason of ["action_processing", "action_failed"]) {
2958
3844
  let error = new InboxOperationError(409, reason);
2959
3845
  if (envelope.error === error.message) return error;
@@ -2961,7 +3847,7 @@ function parseInboxUnavailableFailure(value, status) {
2961
3847
  return;
2962
3848
  }
2963
3849
  if (status !== 503) return;
2964
- keys3(envelope, ["error", "unavailableReason"], ["error", "unavailableReason"]), assert(text4(envelope.error));
3850
+ keys5(envelope, ["error", "unavailableReason"], ["error", "unavailableReason"]), assert(text4(envelope.error));
2965
3851
  let state = questionAvailability(envelope);
2966
3852
  return new InboxOperationError(503, state.unavailableReason);
2967
3853
  } catch {
@@ -2990,13 +3876,13 @@ var operations = {
2990
3876
  function assert(value) {
2991
3877
  if (!value) throw new Error("Invalid Inbox result");
2992
3878
  }
2993
- function object4(value) {
3879
+ function object7(value) {
2994
3880
  return assert(value && typeof value == "object" && !Array.isArray(value) && [Object.prototype, null].includes(Object.getPrototypeOf(value)) && Reflect.ownKeys(value).every((key) => {
2995
3881
  let descriptor = typeof key == "string" ? Object.getOwnPropertyDescriptor(value, key) : void 0;
2996
3882
  return !!descriptor?.enumerable && "value" in descriptor;
2997
3883
  })), value;
2998
3884
  }
2999
- function keys3(value, allowed, required = allowed) {
3885
+ function keys5(value, allowed, required = allowed) {
3000
3886
  assert(Object.keys(value).every((key) => allowed.includes(key)) && required.every((key) => Object.hasOwn(value, key)));
3001
3887
  }
3002
3888
  function text4(value, empty2 = !1) {
@@ -3024,65 +3910,65 @@ function json(value, ancestors = /* @__PURE__ */ new Set()) {
3024
3910
  if (value === null || typeof value == "boolean" || typeof value == "string" || typeof value == "number" && Number.isFinite(value)) return value;
3025
3911
  assert(value && typeof value == "object" && !ancestors.has(value)), ancestors.add(value);
3026
3912
  try {
3027
- return Array.isArray(value) ? array2(value).map((entry) => json(entry, ancestors)) : Object.fromEntries(Object.entries(object4(value)).map(([key, entry]) => [key, json(entry, ancestors)]));
3913
+ return Array.isArray(value) ? array2(value).map((entry) => json(entry, ancestors)) : Object.fromEntries(Object.entries(object7(value)).map(([key, entry]) => [key, json(entry, ancestors)]));
3028
3914
  } finally {
3029
3915
  ancestors.delete(value);
3030
3916
  }
3031
3917
  }
3032
3918
  function recordReference(value) {
3033
- let record4 = object4(value);
3034
- return keys3(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;
3919
+ let record4 = object7(value);
3920
+ 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;
3035
3921
  }
3036
3922
  function responseDefinition(value) {
3037
- let definition = object4(value);
3038
- keys3(definition, ["type", "source"]), assert(definition.type === "selection");
3039
- let source2 = object4(definition.source);
3923
+ let definition = object7(value);
3924
+ keys5(definition, ["type", "source"]), assert(definition.type === "selection");
3925
+ let source2 = object7(definition.source);
3040
3926
  if (source2.type === "authored") {
3041
- keys3(source2, ["type", "options", "suggestions", "search"], ["type", "options"]);
3927
+ keys5(source2, ["type", "options", "suggestions", "search"], ["type", "options"]);
3042
3928
  let options = array2(source2.options);
3043
3929
  assert(options.length > 0);
3044
3930
  let values = options.map((value2) => {
3045
- let option = object4(value2);
3046
- if (keys3(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) {
3047
- let note = object4(option.note);
3048
- keys3(note, ["placeholder"]), assert(text4(note.placeholder));
3931
+ let option = object7(value2);
3932
+ 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) {
3933
+ let note = object7(option.note);
3934
+ keys5(note, ["placeholder"]), assert(text4(note.placeholder));
3049
3935
  }
3050
3936
  return option.value;
3051
3937
  });
3052
3938
  if (assert(new Set(values).size === values.length), "search" in source2 || "suggestions" in source2) {
3053
- let search = object4(source2.search);
3054
- keys3(search, ["triggerLabel", "placeholder", "emptyLabel"]), assert(text4(search.triggerLabel) && text4(search.placeholder) && text4(search.emptyLabel));
3939
+ let search = object7(source2.search);
3940
+ keys5(search, ["triggerLabel", "placeholder", "emptyLabel"]), assert(text4(search.triggerLabel) && text4(search.placeholder) && text4(search.emptyLabel));
3055
3941
  let suggestions2 = array2(source2.suggestions);
3056
3942
  assert(suggestions2.length <= 8 && suggestions2.every((value2) => text4(value2) && values.includes(value2)) && new Set(suggestions2).size === suggestions2.length);
3057
3943
  } else assert(options.length <= 9);
3058
3944
  return;
3059
3945
  }
3060
- assert(source2.type === "records"), keys3(source2, ["type", "collection", "refPrefix", "where", "display", "suggestions"], ["type", "collection", "display"]);
3061
- let collection = object4(source2.collection);
3062
- keys3(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));
3063
- let where = object4(source2.where ?? {});
3946
+ assert(source2.type === "records"), keys5(source2, ["type", "collection", "refPrefix", "where", "display", "suggestions"], ["type", "collection", "display"]);
3947
+ let collection = object7(source2.collection);
3948
+ 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));
3949
+ let where = object7(source2.where ?? {});
3064
3950
  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))));
3065
- let display = object4(source2.display);
3066
- keys3(display, ["labelFields"]);
3951
+ let display = object7(source2.display);
3952
+ keys5(display, ["labelFields"]);
3067
3953
  let labels = array2(display.labelFields);
3068
3954
  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)));
3069
3955
  let suggestions = array2(source2.suggestions ?? []), refs = suggestions.map((value2) => {
3070
- let suggestion = object4(value2);
3071
- keys3(suggestion, ["record", "reason"], ["record"]);
3956
+ let suggestion = object7(value2);
3957
+ keys5(suggestion, ["record", "reason"], ["record"]);
3072
3958
  let record4 = recordReference(suggestion.record);
3073
3959
  return assert(record4.repository === collection.repository), "reason" in suggestion && assert(text4(suggestion.reason)), record4.ref;
3074
3960
  });
3075
3961
  assert(suggestions.length <= 8 && new Set(refs).size === refs.length);
3076
3962
  }
3077
3963
  function response(value) {
3078
- let answer = object4(value);
3964
+ let answer = object7(value);
3079
3965
  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;
3080
3966
  }
3081
3967
  function parseInboxRequest(value) {
3082
3968
  try {
3083
- let envelope = object4(value);
3969
+ let envelope = object7(value);
3084
3970
  assert(Object.keys(envelope).sort().join(",") === "input,operation"), assert(typeof envelope.operation == "string" && Object.hasOwn(operations, envelope.operation));
3085
- let operation2 = envelope.operation, input = { ...object4(envelope.input) }, required = operations[operation2];
3971
+ let operation2 = envelope.operation, input = { ...object7(envelope.input) }, required = operations[operation2];
3086
3972
  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)));
3087
3973
  for (let key of ["itemId", "personId", "fileId"]) key in input && assert(id2(input[key]));
3088
3974
  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 };
@@ -3091,54 +3977,54 @@ function parseInboxRequest(value) {
3091
3977
  }
3092
3978
  }
3093
3979
  function parseInboxCurrent(value) {
3094
- let current2 = object4(value), workspace = object4(current2.workspace), viewer = object4(current2.viewer);
3980
+ let current2 = object7(value), workspace = object7(current2.workspace), viewer = object7(current2.viewer);
3095
3981
  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)), {
3096
3982
  workspace: { id: workspace.id, slug: workspace.slug, name: workspace.name, locale: workspace.locale, timezone: workspace.timezone },
3097
3983
  viewer: { id: viewer.id, name: viewer.name, email: viewer.email }
3098
3984
  };
3099
3985
  }
3100
3986
  function parseInboxItem(value) {
3101
- let item = object4(json(value));
3102
- 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(object4(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) => {
3103
- let view = object4(value2);
3987
+ let item = object7(json(value));
3988
+ 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) => {
3989
+ let view = object7(value2);
3104
3990
  assert(text4(view.id) && text4(view.view) && text4(view.implementation)), json(view.input);
3105
3991
  }), array2(item.people).forEach((value2) => {
3106
- let person = object4(value2);
3992
+ let person = object7(value2);
3107
3993
  assert(id2(person.id) && text4(person.name));
3108
3994
  }), array2(item.questions).forEach((value2) => {
3109
- let question2 = object4(value2);
3995
+ let question2 = object7(value2);
3110
3996
  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) {
3111
- let accepted = object4(question2.acceptedResponse);
3997
+ let accepted = object7(question2.acceptedResponse);
3112
3998
  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));
3113
3999
  }
3114
4000
  if (question2.execution !== null) {
3115
- let execution = object4(question2.execution);
4001
+ let execution = object7(question2.execution);
3116
4002
  if (assert(id2(execution.id) && ["pending", "running", "completed", "failed"].includes(String(execution.state)) && integer(execution.attempt, 0)), "consequence" in execution) {
3117
- let consequence = object4(execution.consequence);
4003
+ let consequence = object7(execution.consequence);
3118
4004
  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) => {
3119
- let receipt = object4(value3);
4005
+ let receipt = object7(value3);
3120
4006
  assert(text4(receipt.repository) && text4(receipt.commit) && text4(receipt.diff, !0));
3121
4007
  });
3122
4008
  }
3123
4009
  }
3124
4010
  }), array2(item.linkedAsks).forEach((value2) => {
3125
- let linked = object4(value2);
4011
+ let linked = object7(value2);
3126
4012
  if (assert(id2(linked.id)), linked.state === "unavailable") assert(typeof linked.done == "boolean");
3127
4013
  else if (assert(["yours", "done", "open", "theirs"].includes(String(linked.state)) && text4(linked.title)), linked.state === "theirs") {
3128
- let assignee = object4(linked.assignee);
4014
+ let assignee = object7(linked.assignee);
3129
4015
  assert(id2(assignee.id) && text4(assignee.name));
3130
4016
  }
3131
4017
  }), array2(item.activity).forEach((value2) => {
3132
- let event = object4(value2);
3133
- 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)), object4(event.data);
4018
+ let event = object7(value2);
4019
+ 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);
3134
4020
  }), array2(item.work).forEach((value2) => {
3135
- let work = object4(value2);
4021
+ let work = object7(value2);
3136
4022
  assert(id2(work.id) && text4(work.questionId) && text4(work.reason) && optionalDate(work.settledAt));
3137
4023
  }), item;
3138
4024
  }
3139
4025
  function parseAnswerableQuestion(value) {
3140
- let entry = object4(json(value));
3141
- keys3(
4026
+ let entry = object7(json(value));
4027
+ keys5(
3142
4028
  entry,
3143
4029
  ["itemId", "number", "revision", "title", "inboxUrl", "questionId", "routine", "prompt", "response", "answerable", "tags", "recordRefs", "instructions", "unavailableReason"],
3144
4030
  ["itemId", "number", "revision", "title", "inboxUrl", "questionId", "routine", "prompt", "response", "answerable"]
@@ -3151,29 +4037,29 @@ function askMetadata(entry) {
3151
4037
  assert(tags.length <= 32 && tags.every((tag) => text4(tag) && new TextEncoder().encode(tag).byteLength <= 64)), assert(new Set(tags).size === tags.length);
3152
4038
  let refs = array2(entry.recordRefs === void 0 ? [] : entry.recordRefs);
3153
4039
  refs.forEach((value) => {
3154
- let ref = object4(value);
3155
- keys3(ref, ["repository", "id"]), recordReference({ repository: ref.repository, ref: ref.id });
4040
+ let ref = object7(value);
4041
+ keys5(ref, ["repository", "id"]), recordReference({ repository: ref.repository, ref: ref.id });
3156
4042
  }), assert(new Set(refs.map((value) => {
3157
- let ref = object4(value);
4043
+ let ref = object7(value);
3158
4044
  return JSON.stringify([ref.repository, ref.id]);
3159
4045
  })).size === refs.length), entry.tags = tags, entry.recordRefs = refs;
3160
4046
  }
3161
4047
  function parseInboxAcceptance(value) {
3162
- let accepted = object4(value);
4048
+ let accepted = object7(value);
3163
4049
  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;
3164
4050
  }
3165
4051
  function parseInboxResult(operation2, value) {
3166
4052
  if (operation2 === "current") return parseInboxCurrent(value);
3167
4053
  if (operation2 === "questions.list") {
3168
- let page = object4(value);
3169
- keys3(page, ["questions", "nextBeforeNumber"]);
4054
+ let page = object7(value);
4055
+ keys5(page, ["questions", "nextBeforeNumber"]);
3170
4056
  let questions = array2(page.questions).map(parseAnswerableQuestion);
3171
4057
  return assert(page.nextBeforeNumber === null || integer(page.nextBeforeNumber)), { questions, nextBeforeNumber: page.nextBeforeNumber };
3172
4058
  }
3173
4059
  if (operation2 === "items.readRecords") return parseInboxRecords(value);
3174
4060
  if (operation2 === "items.read") return parseInboxItem(value);
3175
4061
  if (operation2 === "items.list") {
3176
- let page = object4(value), items = array2(page.items).map(parseInboxItem);
4062
+ let page = object7(value), items = array2(page.items).map(parseInboxItem);
3177
4063
  return assert(items.length <= 100 && (page.nextBeforeNumber === null || integer(page.nextBeforeNumber))), { items, nextBeforeNumber: page.nextBeforeNumber };
3178
4064
  }
3179
4065
  if (operation2 === "items.see") {
@@ -3181,30 +4067,30 @@ function parseInboxResult(operation2, value) {
3181
4067
  return;
3182
4068
  }
3183
4069
  if (operation2 === "items.markDigestRead") {
3184
- let read2 = object4(value);
4070
+ let read2 = object7(value);
3185
4071
  return assert(integer(read2.activityId) && date(read2.readAt)), read2;
3186
4072
  }
3187
4073
  if (operation2 === "items.rename" || operation2 === "items.setLifecycle") {
3188
- let update = object4(value), item = parseInboxItem(update.item);
4074
+ let update = object7(value), item = parseInboxItem(update.item);
3189
4075
  return assert((update.activityId === null || integer(update.activityId)) && optionalDate(update.changedAt)), { ...update, item };
3190
4076
  }
3191
4077
  if (operation2 === "items.listRecipientCandidates") {
3192
4078
  let candidates = array2(value);
3193
4079
  return candidates.forEach((value2) => {
3194
- let person = object4(value2);
4080
+ let person = object7(value2);
3195
4081
  assert(id2(person.id) && text4(person.name) && text4(person.email));
3196
- }), assert(new Set(candidates.map((value2) => object4(value2).id)).size === candidates.length), candidates;
4082
+ }), assert(new Set(candidates.map((value2) => object7(value2).id)).size === candidates.length), candidates;
3197
4083
  }
3198
4084
  if (operation2 === "items.addRecipient") {
3199
- let addition = object4(value), item = parseInboxItem(addition.item);
4085
+ let addition = object7(value), item = parseInboxItem(addition.item);
3200
4086
  return assert(id2(addition.addedPersonId) && item.people.some((person) => person.id === addition.addedPersonId)), { ...addition, item };
3201
4087
  }
3202
4088
  if (operation2 === "questions.answer") return parseInboxAcceptance(value);
3203
4089
  if (operation2 === "questions.searchRecords") {
3204
- let result2 = object4(value);
4090
+ let result2 = object7(value);
3205
4091
  assert(text4(result2.recordType) && integer(result2.eligibleCount, 0) && integer(result2.matchCount, 0) && Number(result2.matchCount) <= Number(result2.eligibleCount));
3206
4092
  let labeled = (value2) => {
3207
- let record4 = object4(value2);
4093
+ let record4 = object7(value2);
3208
4094
  recordReference({ repository: record4.repository, ref: record4.ref }), assert(text4(record4.label)), "reason" in record4 && assert(text4(record4.reason));
3209
4095
  };
3210
4096
  return array2(result2.matches).forEach(labeled), array2(result2.suggestions).forEach(labeled), "selected" in result2 && labeled(result2.selected), result2;
@@ -3212,9 +4098,9 @@ function parseInboxResult(operation2, value) {
3212
4098
  throw new Error("File content is not a JSON result");
3213
4099
  }
3214
4100
 
3215
- async function limitedBody(request2, limit, timeoutMs) {
3216
- if (!request2.body) return new Uint8Array();
3217
- let reader = request2.body.getReader(), expired = !1, timer = timeoutMs === void 0 ? void 0 : setTimeout(() => {
4101
+ async function limitedBody(request3, limit, timeoutMs) {
4102
+ if (!request3.body) return new Uint8Array();
4103
+ let reader = request3.body.getReader(), expired = !1, timer = timeoutMs === void 0 ? void 0 : setTimeout(() => {
3218
4104
  expired = !0, reader.cancel().catch(() => {
3219
4105
  });
3220
4106
  }, timeoutMs), chunks = [], length = 0;
@@ -3573,16 +4459,16 @@ function appContext(origin, active2, changed) {
3573
4459
  return requestChecked(`routines/${encodeURIComponent(key)}/${suffix}`, { signal }, !1, !0);
3574
4460
  }
3575
4461
  async function requestFiles(suffix, init2, parent) {
3576
- let unavailable5 = () => new FileOperationError("unsupported_context", 400);
4462
+ let unavailable6 = () => new FileOperationError("unsupported_context", 400);
3577
4463
  if (!current2() || !/^(?:|\/[0-9a-f-]{36}(?:\/(?:content|upload|enrichments(?:\/[^/?#]+\/content)?))?)$/i.test(suffix))
3578
- throw unavailable5();
3579
- let admitted = credential, signal = parent ? AbortSignal.any([access.signal, parent]) : access.signal, failure = () => current2() && !signal.aborted ? new FileOperationError("unavailable", 503, !0) : unavailable5();
4464
+ throw unavailable6();
4465
+ let admitted = credential, signal = parent ? AbortSignal.any([access.signal, parent]) : access.signal, failure = () => current2() && !signal.aborted ? new FileOperationError("unavailable", 503, !0) : unavailable6();
3580
4466
  try {
3581
- return await hostedContent("", init2, signal, (_url, request2) => untilAborted(
3582
- send3(`files${suffix}`, admitted, signal, request2).then((value) => {
4467
+ return await hostedContent("", init2, signal, (_url, request3) => untilAborted(
4468
+ send3(`files${suffix}`, admitted, signal, request3).then((value) => {
3583
4469
  if (signal.aborted)
3584
4470
  throw value.body?.cancel().catch(() => {
3585
- }), unavailable5();
4471
+ }), unavailable6();
3586
4472
  return value;
3587
4473
  }),
3588
4474
  signal
@@ -3741,9 +4627,9 @@ var WorkspaceAccessError = class extends Error {
3741
4627
  status;
3742
4628
  };
3743
4629
 
3744
- var unavailable3 = () => new InboxOperationError(503, "unavailable"), stale = () => new InboxOperationError(401, "authority_unavailable"), contextFailure = (error) => error instanceof WorkspaceAccessError ? new InboxOperationError(error.status, error.status === 401 ? "authority_unavailable" : error.status === 403 ? "access_denied" : "unavailable") : stale();
4630
+ var unavailable4 = () => new InboxOperationError(503, "unavailable"), stale = () => new InboxOperationError(401, "authority_unavailable"), contextFailure = (error) => error instanceof WorkspaceAccessError ? new InboxOperationError(error.status, error.status === 401 ? "authority_unavailable" : error.status === 403 ? "access_denied" : "unavailable") : stale();
3745
4631
  function hostFailure(error, context) {
3746
- return !context.isCurrent() || context.expiresAt <= Date.now() || error instanceof InboxContextError && error.status === 401 ? stale() : error instanceof InboxContextError && error.status === 403 ? new InboxOperationError(403, "access_denied") : unavailable3();
4632
+ return !context.isCurrent() || context.expiresAt <= Date.now() || error instanceof InboxContextError && error.status === 401 ? stale() : error instanceof InboxContextError && error.status === 403 ? new InboxOperationError(403, "access_denied") : unavailable4();
3747
4633
  }
3748
4634
  async function send2(operation2, input, resolved) {
3749
4635
  let envelope = parseInboxRequest({ operation: operation2, input }), context;
@@ -3763,11 +4649,11 @@ async function send2(operation2, input, resolved) {
3763
4649
  [400, 401, 403, 409].includes(response2.status) ? response2.status : 503,
3764
4650
  response2.status === 400 ? "invalid_input" : response2.status === 401 ? "authority_unavailable" : response2.status === 403 ? "access_denied" : response2.status === 409 ? "conflict" : "unavailable"
3765
4651
  );
3766
- if (response2.status !== 200) throw unavailable3();
4652
+ if (response2.status !== 200) throw unavailable4();
3767
4653
  let parsed = parseInboxResult(operation2, value);
3768
4654
  return check2(), parsed;
3769
4655
  } catch (error) {
3770
- throw check2(), error instanceof InboxOperationError ? error : unavailable3();
4656
+ throw check2(), error instanceof InboxOperationError ? error : unavailable4();
3771
4657
  }
3772
4658
  }
3773
4659
  if (context.endpoint !== `https://${context.workspace}.oddington.ai` || ["auth", "www", "api", "os"].includes(context.workspace)) throw stale();
@@ -3778,7 +4664,7 @@ async function send2(operation2, input, resolved) {
3778
4664
  } catch (error) {
3779
4665
  throw hostFailure(error, context);
3780
4666
  }
3781
- if (!host) throw unavailable3();
4667
+ if (!host) throw unavailable4();
3782
4668
  }
3783
4669
  let check = () => {
3784
4670
  if (!context.isCurrent() || host && !host.isCurrent() || !Number.isFinite(context.expiresAt) || context.expiresAt <= Date.now()) throw stale();
@@ -3816,18 +4702,18 @@ async function send2(operation2, input, resolved) {
3816
4702
  }
3817
4703
  if (response2.status !== 200)
3818
4704
  throw response2.body?.cancel().catch(() => {
3819
- }), unavailable3();
4705
+ }), unavailable4();
3820
4706
  let bytes = await limitedBody(response2, INBOX_RESULT_BYTES);
3821
- if (check(), !bytes) throw unavailable3();
4707
+ if (check(), !bytes) throw unavailable4();
3822
4708
  let value = JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes)), parsed = parseInboxResult(operation2, value);
3823
- if (check(), operation2 === "current" && parsed.workspace.slug !== context.workspace) throw unavailable3();
4709
+ if (check(), operation2 === "current" && parsed.workspace.slug !== context.workspace) throw unavailable4();
3824
4710
  if ("itemId" in envelope.input) {
3825
4711
  let item = operation2 === "items.read" ? parsed : operation2 === "items.rename" || operation2 === "items.setLifecycle" || operation2 === "items.addRecipient" ? parsed.item : void 0;
3826
- if (item && (item.id !== envelope.input.itemId || "revision" in envelope.input && item.revision !== envelope.input.revision) || operation2 === "items.addRecipient" && parsed.addedPersonId !== envelope.input.personId) throw unavailable3();
4712
+ if (item && (item.id !== envelope.input.itemId || "revision" in envelope.input && item.revision !== envelope.input.revision) || operation2 === "items.addRecipient" && parsed.addedPersonId !== envelope.input.personId) throw unavailable4();
3827
4713
  }
3828
4714
  return parsed;
3829
4715
  } catch (error) {
3830
- throw check(), error instanceof InboxOperationError ? error : unavailable3();
4716
+ throw check(), error instanceof InboxOperationError ? error : unavailable4();
3831
4717
  }
3832
4718
  }
3833
4719
  var inbox = {
@@ -3847,14 +4733,14 @@ var inbox = {
3847
4733
  throw hostFailure(error, initial);
3848
4734
  }
3849
4735
  if (initial.kind === "local") throw new InboxOperationError(403, "access_denied");
3850
- if (!host) throw unavailable3();
4736
+ if (!host) throw unavailable4();
3851
4737
  let check = () => {
3852
4738
  if (!initial.isCurrent() || !host.isCurrent() || initial.expiresAt <= Date.now()) throw stale();
3853
4739
  };
3854
4740
  do {
3855
4741
  check();
3856
4742
  let page = await send2("items.list", beforeNumber === void 0 ? {} : { beforeNumber });
3857
- if (check(), beforeNumber !== void 0 && (page.items.some((item) => item.number >= beforeNumber) || page.nextBeforeNumber !== null && page.nextBeforeNumber >= beforeNumber)) throw unavailable3();
4743
+ if (check(), beforeNumber !== void 0 && (page.items.some((item) => item.number >= beforeNumber) || page.nextBeforeNumber !== null && page.nextBeforeNumber >= beforeNumber)) throw unavailable4();
3858
4744
  if (items.push(...page.items), page.nextBeforeNumber === null) return items;
3859
4745
  beforeNumber = page.nextBeforeNumber;
3860
4746
  } while (!0);
@@ -3889,7 +4775,7 @@ var inbox = {
3889
4775
  routines,
3890
4776
  ...beforeNumber === void 0 ? {} : { beforeNumber }
3891
4777
  }, initial);
3892
- if (check(), page.questions.some((question2) => question2.inboxUrl !== `https://${initial.workspace}.oddington.ai/inbox/${question2.itemId}` || !routines.includes(question2.routine)) || beforeNumber !== void 0 && page.nextBeforeNumber !== null && page.nextBeforeNumber >= beforeNumber) throw unavailable3();
4778
+ if (check(), page.questions.some((question2) => question2.inboxUrl !== `https://${initial.workspace}.oddington.ai/inbox/${question2.itemId}` || !routines.includes(question2.routine)) || beforeNumber !== void 0 && page.nextBeforeNumber !== null && page.nextBeforeNumber >= beforeNumber) throw unavailable4();
3893
4779
  if (questions.push(...page.questions), page.nextBeforeNumber === null) return questions;
3894
4780
  beforeNumber = page.nextBeforeNumber;
3895
4781
  } while (!0);
@@ -4095,10 +4981,10 @@ function createLocalBrowserAuth(origin, failure) {
4095
4981
  coordinator.listeners.add(observe);
4096
4982
  let assertActive = () => {
4097
4983
  if (!active2) throw failure("disposed");
4098
- }, unavailable5 = async () => Object.freeze({
4984
+ }, unavailable6 = async () => Object.freeze({
4099
4985
  status: active2 ? "unavailable" : "disposed"
4100
4986
  }), handle2 = Object.freeze({
4101
- authorization: Object.freeze({ get: unavailable5, approve: unavailable5, deny: unavailable5 }),
4987
+ authorization: Object.freeze({ get: unavailable6, approve: unavailable6, deny: unavailable6 }),
4102
4988
  getState() {
4103
4989
  return active2 && !coordinator.state.pending && coordinator.state.status === "signed_in" && !coordinator.context.isCurrent() && coordinator.state.status === "signed_in" && publish(coordinator, { status: "unavailable", error: "unavailable" }), lastState;
4104
4990
  },
@@ -4215,14 +5101,14 @@ function createBrowserAuth(runtime) {
4215
5101
  let revision = c.revision, person = c.session.user.id, controller = new AbortController(), deadline = Date.now() + 15e3, finish, promise = new Promise((resolve) => {
4216
5102
  finish = resolve;
4217
5103
  }), resolution2 = { promise, checkBound() {
4218
- Date.now() >= deadline && fail4();
5104
+ Date.now() >= deadline && fail7();
4219
5105
  }, complete() {
4220
5106
  c.resolution === resolution2 && (clearTimeout(timer), c.resolution = void 0, finish());
4221
5107
  }, cancel() {
4222
5108
  c.resolution === resolution2 && (resolution2.complete(), controller.abort());
4223
5109
  } };
4224
5110
  c.resolution = resolution2;
4225
- let fail4 = (error) => {
5111
+ let fail7 = (error) => {
4226
5112
  if (c.resolution === resolution2) {
4227
5113
  if (terminalSessionFailure(error)) {
4228
5114
  expire(c);
@@ -4234,7 +5120,7 @@ function createBrowserAuth(runtime) {
4234
5120
  }
4235
5121
  c.revision++, resolution2.cancel(), c.timer && clearTimeout(c.timer), publish2(c, { status: "unavailable", account: c.state.account, error: "unavailable" });
4236
5122
  }
4237
- }, timer = setTimeout(() => fail4(), 15e3);
5123
+ }, timer = setTimeout(() => fail7(), 15e3);
4238
5124
  return validSession(c.session) || publish2(c, { status: "reconnecting", account: c.state.account, pending: c.state.pending }), Promise.resolve().then(async () => {
4239
5125
  if (c.resolution === resolution2)
4240
5126
  try {
@@ -4245,16 +5131,16 @@ function createBrowserAuth(runtime) {
4245
5131
  return;
4246
5132
  }
4247
5133
  if (result2.error) {
4248
- fail4(result2.error);
5134
+ fail7(result2.error);
4249
5135
  return;
4250
5136
  }
4251
5137
  if (!result2.data.session || !validSession(result2.data.session)) {
4252
- fail4();
5138
+ fail7();
4253
5139
  return;
4254
5140
  }
4255
5141
  accept(c, result2.data.session.user.id === person ? "TOKEN_REFRESHED" : "SIGNED_IN", result2.data.session), resolution2.complete();
4256
5142
  } catch (error) {
4257
- fail4(error);
5143
+ fail7(error);
4258
5144
  }
4259
5145
  }), promise;
4260
5146
  }
@@ -4578,10 +5464,10 @@ async function provider(configuration, guard) {
4578
5464
  }
4579
5465
  },
4580
5466
  fetch: Object.assign(async (input, init2) => {
4581
- let revision = guard.revision(), refresh2 = String(input) === `${configuration.providerUrl}/auth/v1/token?grant_type=refresh_token`, cancelled = () => Response.json({ error_code: "os_refresh_cancelled" }, { status: 400 }), request2 = String(input).startsWith(`${configuration.providerUrl}/auth/v1/oauth/authorizations/`) ? authorizationRequest : void 0, rejectStale = () => {
4582
- throw request2 && (request2.rejected = !0), new BrowserAuthError("stale");
5467
+ let revision = guard.revision(), refresh2 = String(input) === `${configuration.providerUrl}/auth/v1/token?grant_type=refresh_token`, cancelled = () => Response.json({ error_code: "os_refresh_cancelled" }, { status: 400 }), request3 = String(input).startsWith(`${configuration.providerUrl}/auth/v1/oauth/authorizations/`) ? authorizationRequest : void 0, rejectStale = () => {
5468
+ throw request3 && (request3.rejected = !0), new BrowserAuthError("stale");
4583
5469
  };
4584
- if (request2 && (!request2.current() || !guard.canAuthorize(new Headers(init2?.headers).get("authorization")?.replace(/^Bearer /, "") ?? "")) && rejectStale(), !alive() && refresh2) return cancelled();
5470
+ if (request3 && (!request3.current() || !guard.canAuthorize(new Headers(init2?.headers).get("authorization")?.replace(/^Bearer /, "") ?? "")) && rejectStale(), !alive() && refresh2) return cancelled();
4585
5471
  (!guard.current(revision) || !alive()) && rejectStale();
4586
5472
  let response2, body;
4587
5473
  try {
@@ -4595,7 +5481,7 @@ async function provider(configuration, guard) {
4595
5481
  throw error;
4596
5482
  }
4597
5483
  if (!alive() && refresh2) return cancelled();
4598
- if ((!guard.current(revision) || !alive() || request2 && !request2.current()) && rejectStale(), refresh2) {
5484
+ if ((!guard.current(revision) || !alive() || request3 && !request3.current()) && rejectStale(), refresh2) {
4599
5485
  let value;
4600
5486
  try {
4601
5487
  value = JSON.parse(new TextDecoder().decode(body));
@@ -4616,7 +5502,7 @@ async function provider(configuration, guard) {
4616
5502
  ), json2 = result2.json.bind(result2);
4617
5503
  return result2.json = async () => {
4618
5504
  let value = await json2();
4619
- return (!guard.current(revision) || !alive() || request2 && !request2.current()) && rejectStale(), value && typeof value.access_token == "string" && provenance.set(value.access_token, revision), value;
5505
+ return (!guard.current(revision) || !alive() || request3 && !request3.current()) && rejectStale(), value && typeof value.access_token == "string" && provenance.set(value.access_token, revision), value;
4620
5506
  }, result2;
4621
5507
  }, { preconnect: fetch.preconnect })
4622
5508
  });
@@ -4646,15 +5532,15 @@ async function provider(configuration, guard) {
4646
5532
  authorizationQueue = new Promise((resolve) => {
4647
5533
  release = resolve;
4648
5534
  }), await previous;
4649
- let request2 = { current: current2, rejected: !1 };
4650
- authorizationRequest = request2;
5535
+ let request3 = { current: current2, rejected: !1 };
5536
+ authorizationRequest = request3;
4651
5537
  try {
4652
5538
  if (!current2()) throw new BrowserAuthError("stale");
4653
5539
  let client = activeClient(), result2 = await (kind === "get" ? client.oauth.getAuthorizationDetails(id3) : kind === "approve" ? client.oauth.approveAuthorization(id3, { skipBrowserRedirect: !0 }) : client.oauth.denyAuthorization(id3, { skipBrowserRedirect: !0 }));
4654
- if (request2.rejected || !current2()) throw new BrowserAuthError("stale");
5540
+ if (request3.rejected || !current2()) throw new BrowserAuthError("stale");
4655
5541
  return result2;
4656
5542
  } catch (error) {
4657
- throw request2.rejected || !current2() ? new BrowserAuthError("stale") : error;
5543
+ throw request3.rejected || !current2() ? new BrowserAuthError("stale") : error;
4658
5544
  } finally {
4659
5545
  authorizationRequest = void 0, release();
4660
5546
  }
@@ -4734,29 +5620,29 @@ function routineRunHandle(operations2) {
4734
5620
  });
4735
5621
  }
4736
5622
 
4737
- var name = /^[a-z0-9][a-z0-9-]{0,62}$/, uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, invalid8 = () => {
5623
+ 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 = () => {
4738
5624
  throw new Error("Run state unavailable");
4739
- }, record3 = (value) => value && typeof value == "object" && !Array.isArray(value) ? value : invalid8();
4740
- function time(value) {
4741
- return typeof value != "string" || value.length > 40 || !Number.isFinite(Date.parse(value)) ? invalid8() : value;
5625
+ }, record3 = (value) => value && typeof value == "object" && !Array.isArray(value) ? value : invalid11();
5626
+ function time2(value) {
5627
+ return typeof value != "string" || value.length > 40 || !Number.isFinite(Date.parse(value)) ? invalid11() : value;
4742
5628
  }
4743
5629
  function times(value) {
4744
5630
  return {
4745
- ...value.startedAt === void 0 ? {} : { startedAt: time(value.startedAt) },
4746
- ...value.finishedAt === void 0 ? {} : { finishedAt: time(value.finishedAt) }
5631
+ ...value.startedAt === void 0 ? {} : { startedAt: time2(value.startedAt) },
5632
+ ...value.finishedAt === void 0 ? {} : { finishedAt: time2(value.finishedAt) }
4747
5633
  };
4748
5634
  }
4749
5635
  function bounded(value) {
4750
- return assertRoutineJson(value), new TextEncoder().encode(JSON.stringify(value)).byteLength > 256 * 1024 ? invalid8() : value;
5636
+ return assertRoutineJson(value), new TextEncoder().encode(JSON.stringify(value)).byteLength > 256 * 1024 ? invalid11() : value;
4751
5637
  }
4752
5638
  function progress(value) {
4753
5639
  if (value === void 0) return {};
4754
5640
  let v = record3(value);
4755
- return Object.keys(v).sort().join(",") !== "completed,total" || !Number.isSafeInteger(v.completed) || !Number.isSafeInteger(v.total) || v.completed < 1 || v.completed > v.total ? invalid8() : { progress: { completed: v.completed, total: v.total } };
5641
+ 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 } };
4756
5642
  }
4757
5643
  function parseRunStep(value, expected) {
4758
5644
  let v = record3(value);
4759
- 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 invalid8();
5645
+ 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();
4760
5646
  let output = captureRetainedStepOutput(v.id, {
4761
5647
  ...Object.hasOwn(v, "summary") ? { summary: v.summary } : {},
4762
5648
  ...Object.hasOwn(v, "data") ? { data: v.data } : {}
@@ -4773,28 +5659,28 @@ function parseRunStep(value, expected) {
4773
5659
  }
4774
5660
  function parseRemoteRun(value, expected = {}) {
4775
5661
  let v = record3(value);
4776
- if (typeof v.id != "string" || !uuid.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 invalid8();
5662
+ 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();
4777
5663
  let steps = v.steps.map((value2) => {
4778
5664
  let step = record3(value2);
4779
- return typeof step.detailAvailable != "boolean" || Object.hasOwn(step, "data") ? invalid8() : { ...parseRunStep(step), detailAvailable: step.detailAvailable };
5665
+ return typeof step.detailAvailable != "boolean" || Object.hasOwn(step, "data") ? invalid11() : { ...parseRunStep(step), detailAvailable: step.detailAvailable };
4780
5666
  });
4781
- if (new Set(steps.map((step) => step.id)).size !== steps.length) return invalid8();
5667
+ if (new Set(steps.map((step) => step.id)).size !== steps.length) return invalid11();
4782
5668
  let failure;
4783
5669
  if (v.failure !== void 0) {
4784
5670
  let f = record3(v.failure);
4785
- if (v.status !== "failed" || typeof f.message != "string" || !f.message || f.message.length > 512) return invalid8();
5671
+ if (v.status !== "failed" || typeof f.message != "string" || !f.message || f.message.length > 512) return invalid11();
4786
5672
  if (f.code === "step_output_too_large") {
4787
5673
  let { code, message: message2, ...facts } = f, detail = parseRoutineStepOutputDetail(facts);
4788
- if (!steps.some((step) => step.id === detail.step && step.status === "failed") || message2 !== routineStepOutputMessage(detail)) return invalid8();
5674
+ if (!steps.some((step) => step.id === detail.step && step.status === "failed") || message2 !== routineStepOutputMessage(detail)) return invalid11();
4789
5675
  failure = { code, message: message2, ...detail };
4790
5676
  } else failure = { message: f.message };
4791
5677
  }
4792
- return Object.hasOwn(v, "result") && v.status !== "succeeded" ? invalid8() : {
5678
+ return Object.hasOwn(v, "result") && v.status !== "succeeded" ? invalid11() : {
4793
5679
  id: v.id,
4794
5680
  routine: v.routine,
4795
5681
  placement: "remote",
4796
5682
  status: v.status,
4797
- createdAt: time(v.createdAt),
5683
+ createdAt: time2(v.createdAt),
4798
5684
  ...times(v),
4799
5685
  steps,
4800
5686
  ...Object.hasOwn(v, "result") ? { result: bounded(v.result) } : {},
@@ -4802,7 +5688,7 @@ function parseRemoteRun(value, expected = {}) {
4802
5688
  };
4803
5689
  }
4804
5690
 
4805
- var identifier = /^[a-z0-9]+(?:-[a-z0-9]+)*(?![\s\S])/, uuid2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}(?![\s\S])/i, dataErrorCodes = /* @__PURE__ */ new Set([
5691
+ var identifier = /^[a-z0-9]+(?:-[a-z0-9]+)*(?![\s\S])/, uuid3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}(?![\s\S])/i, dataErrorCodes = /* @__PURE__ */ new Set([
4806
5692
  "context_unavailable",
4807
5693
  "unauthenticated",
4808
5694
  "access_denied",
@@ -4820,26 +5706,26 @@ var identifier = /^[a-z0-9]+(?:-[a-z0-9]+)*(?![\s\S])/, uuid2 = /^[0-9a-f]{8}-[0
4820
5706
  this.name = "AppRoutineError";
4821
5707
  }
4822
5708
  reason;
4823
- }, fail3 = (reason) => {
5709
+ }, fail6 = (reason) => {
4824
5710
  throw new AppRoutineError(reason);
4825
5711
  };
4826
5712
  function current(context) {
4827
- (!context.isCurrent() || context.kind === "local" && context.signal.aborted) && fail3("authority_unavailable");
5713
+ (!context.isCurrent() || context.kind === "local" && context.signal.aborted) && fail6("authority_unavailable");
4828
5714
  }
4829
5715
  function appDescriptors() {
4830
5716
  return globalThis[/* @__PURE__ */ Symbol.for("oddington.app.descriptor")]?.routines ?? [];
4831
5717
  }
4832
5718
  async function authority(retained = !1) {
4833
- let context = await resolveAppContext(retained).catch(() => fail3("authority_unavailable"));
4834
- return current(context), context.kind !== "local" && (!context.binding || !context.memberId || !identifier.test(context.workspace) || context.workspace.length > 63 || ["auth", "api", "os", "www"].includes(context.workspace) || context.endpoint !== `https://${context.workspace}.oddington.ai`) && fail3("authority_unavailable"), context;
5719
+ let context = await resolveAppContext(retained).catch(() => fail6("authority_unavailable"));
5720
+ return current(context), context.kind !== "local" && (!context.binding || !context.memberId || !identifier.test(context.workspace) || context.workspace.length > 63 || ["auth", "api", "os", "www"].includes(context.workspace) || context.endpoint !== `https://${context.workspace}.oddington.ai`) && fail6("authority_unavailable"), context;
4835
5721
  }
4836
5722
  async function live(context, read2) {
4837
5723
  if (current(context), context.kind === "local") return context;
4838
5724
  let resolved = await authority(read2);
4839
- return current(context), (resolved.kind === "local" || resolved.binding !== context.binding || resolved.memberId !== context.memberId || resolved.workspace !== context.workspace || resolved.endpoint !== context.endpoint) && fail3("authority_unavailable"), resolved;
5725
+ return current(context), (resolved.kind === "local" || resolved.binding !== context.binding || resolved.memberId !== context.memberId || resolved.workspace !== context.workspace || resolved.endpoint !== context.endpoint) && fail6("authority_unavailable"), resolved;
4840
5726
  }
4841
- async function request(key, suffix, init2, maximum = SUMMARY_BYTES, retained, read2 = !1) {
4842
- (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail3("authority_unavailable");
5727
+ async function request2(key, suffix, init2, maximum = SUMMARY_BYTES, retained, read2 = !1) {
5728
+ (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail6("authority_unavailable");
4843
5729
  let context = retained ? await live(retained, read2) : await authority(read2);
4844
5730
  current(context);
4845
5731
  let deadline = new AbortController(), timeout = context.kind === "local" ? void 0 : setTimeout(() => deadline.abort(), 2e4);
@@ -4851,22 +5737,22 @@ async function request(key, suffix, init2, maximum = SUMMARY_BYTES, retained, re
4851
5737
  signal: deadline.signal,
4852
5738
  headers: { authorization: `Bearer ${context.accessToken}`, ...init2?.body ? { "content-type": "application/json" } : {} }
4853
5739
  }));
4854
- response2.redirected && fail3("execution_unavailable");
5740
+ response2.redirected && fail6("execution_unavailable");
4855
5741
  let value = await appResponse(response2, maximum, context.kind === "local" ? context.signal : deadline.signal);
4856
5742
  if (current(context), context.kind !== "local" && await live(context, read2), !response2.ok) {
4857
5743
  if (context.kind !== "local") {
4858
5744
  let code = value?.code;
4859
- if ((code === "authentication_required" || code === "access_denied") && fail3("authority_unavailable"), (code === "input_invalid" || code === "file_not_remote") && fail3("invalid_input"), suffix === "describe" && (code === "current_deployment_unavailable" || code === "capability_unavailable"))
4860
- return unavailable4(key, code === "current_deployment_unavailable" ? "not_deployed" : "capability_unavailable");
4861
- fail3("execution_unavailable");
5745
+ if ((code === "authentication_required" || code === "access_denied") && fail6("authority_unavailable"), (code === "input_invalid" || code === "file_not_remote") && fail6("invalid_input"), suffix === "describe" && (code === "current_deployment_unavailable" || code === "capability_unavailable"))
5746
+ return unavailable5(key, code === "current_deployment_unavailable" ? "not_deployed" : "capability_unavailable");
5747
+ fail6("execution_unavailable");
4862
5748
  }
4863
5749
  let reason = value?.error;
4864
- reason === "authority_unavailable" && (context.kind === "local" && context.invalidate(), fail3(reason)), (reason === "invalid_input" || reason === "execution_unavailable") && fail3(reason), fail3("execution_unavailable");
5750
+ reason === "authority_unavailable" && (context.kind === "local" && context.invalidate(), fail6(reason)), (reason === "invalid_input" || reason === "execution_unavailable") && fail6(reason), fail6("execution_unavailable");
4865
5751
  }
4866
5752
  return value;
4867
5753
  } catch (error) {
4868
5754
  if (current(context), error instanceof AppRoutineError) throw error;
4869
- fail3("execution_unavailable");
5755
+ fail6("execution_unavailable");
4870
5756
  } finally {
4871
5757
  clearTimeout(timeout);
4872
5758
  }
@@ -4874,12 +5760,12 @@ async function request(key, suffix, init2, maximum = SUMMARY_BYTES, retained, re
4874
5760
  function summary(value, key, context, id3) {
4875
5761
  if (context.kind !== "local")
4876
5762
  try {
4877
- return (!only(value, "id,routine,placement,status,createdAt,startedAt,finishedAt,steps,result,failure") || !Array.isArray(value.steps) || value.steps.some((step) => !only(step, "id,title,status,startedAt,finishedAt,progress,summary,detailAvailable")) || value.failure !== void 0 && !validFailure(value.failure, value.steps)) && fail3("execution_unavailable"), parseRemoteRun(value, { routine: key, id: id3 });
5763
+ return (!only(value, "id,routine,placement,status,createdAt,startedAt,finishedAt,steps,result,failure") || !Array.isArray(value.steps) || value.steps.some((step) => !only(step, "id,title,status,startedAt,finishedAt,progress,summary,detailAvailable")) || value.failure !== void 0 && !validFailure(value.failure, value.steps)) && fail6("execution_unavailable"), parseRemoteRun(value, { routine: key, id: id3 });
4878
5764
  } catch {
4879
- return fail3("execution_unavailable");
5765
+ return fail6("execution_unavailable");
4880
5766
  }
4881
5767
  let run = value;
4882
- return (!only(run, "id,routine,placement,status,createdAt,startedAt,finishedAt,steps,result,failure,local") || typeof run.id != "string" || !uuid2.test(run.id) || id3 !== void 0 && run.id !== id3 || run.routine !== key || run.placement !== "local" || !["queued", "running", "succeeded", "failed"].includes(run.status) || !timestamp(run.createdAt) || !optionalTimes(run) || !Array.isArray(run.steps) || run.steps.length > 64 || run.steps.some((step) => !only(step, "id,title,status,startedAt,finishedAt,progress,summary,detailAvailable") || typeof step.detailAvailable != "boolean" || !validStep(step)) || new Set(run.steps.map((step) => step.id)).size !== run.steps.length || Object.hasOwn(run, "result") && (run.status !== "succeeded" || !bounded2(run.result)) || run.failure !== void 0 && (run.status !== "failed" || !validFailure(run.failure, run.steps)) || run.local !== void 0 && !validLocalActivity(run.local)) && fail3("execution_unavailable"), run;
5768
+ return (!only(run, "id,routine,placement,status,createdAt,startedAt,finishedAt,steps,result,failure,local") || typeof run.id != "string" || !uuid3.test(run.id) || id3 !== void 0 && run.id !== id3 || run.routine !== key || run.placement !== "local" || !["queued", "running", "succeeded", "failed"].includes(run.status) || !timestamp(run.createdAt) || !optionalTimes(run) || !Array.isArray(run.steps) || run.steps.length > 64 || run.steps.some((step) => !only(step, "id,title,status,startedAt,finishedAt,progress,summary,detailAvailable") || typeof step.detailAvailable != "boolean" || !validStep(step)) || new Set(run.steps.map((step) => step.id)).size !== run.steps.length || Object.hasOwn(run, "result") && (run.status !== "succeeded" || !bounded2(run.result)) || run.failure !== void 0 && (run.status !== "failed" || !validFailure(run.failure, run.steps)) || run.local !== void 0 && !validLocalActivity(run.local)) && fail6("execution_unavailable"), run;
4883
5769
  }
4884
5770
  function validFailure(value, steps) {
4885
5771
  if (!only(value, "message,code,step,sizeBytes,limitBytes,summaryBytes,dataBytes") || !message(value.message)) return !1;
@@ -4919,18 +5805,18 @@ function validLocalActivity(value) {
4919
5805
  } catch {
4920
5806
  return !1;
4921
5807
  }
4922
- })())) && value.effects.every((item) => only(item, "capability,operation,status,durationMs,reference,summary") && ["files", "inbox", "ai"].includes(item.capability) && typeof item.operation == "string" && /^[a-zA-Z][a-zA-Z0-9-]{0,62}$/.test(item.operation) && ["completed", "failed"].includes(item.status) && (item.durationMs === void 0 || typeof item.durationMs == "number" && Number.isFinite(item.durationMs) && item.durationMs >= 0) && (item.reference === void 0 || typeof item.reference == "string" && uuid2.test(item.reference)) && (!Object.hasOwn(item, "summary") || bounded2(item.summary))) && (value.git === void 0 || only(value.git, "branch,commit,dirty") && typeof value.git.dirty == "boolean" && (value.git.branch === void 0 || typeof value.git.branch == "string" && value.git.branch.length <= 256 && !/[\x00-\x1f\x7f]/.test(value.git.branch)) && (value.git.commit === void 0 || typeof value.git.commit == "string" && /^[0-9a-f]{40}$/.test(value.git.commit)));
5808
+ })())) && value.effects.every((item) => only(item, "capability,operation,status,durationMs,reference,summary") && ["files", "inbox", "ai"].includes(item.capability) && typeof item.operation == "string" && /^[a-zA-Z][a-zA-Z0-9-]{0,62}$/.test(item.operation) && ["completed", "failed"].includes(item.status) && (item.durationMs === void 0 || typeof item.durationMs == "number" && Number.isFinite(item.durationMs) && item.durationMs >= 0) && (item.reference === void 0 || typeof item.reference == "string" && uuid3.test(item.reference)) && (!Object.hasOwn(item, "summary") || bounded2(item.summary))) && (value.git === void 0 || only(value.git, "branch,commit,dirty") && typeof value.git.dirty == "boolean" && (value.git.branch === void 0 || typeof value.git.branch == "string" && value.git.branch.length <= 256 && !/[\x00-\x1f\x7f]/.test(value.git.branch)) && (value.git.commit === void 0 || typeof value.git.commit == "string" && /^[0-9a-f]{40}$/.test(value.git.commit)));
4923
5809
  }
4924
5810
  function jsonInput(value, ancestors = /* @__PURE__ */ new Set()) {
4925
5811
  if (value === null || typeof value == "string" || typeof value == "boolean" || typeof value == "number" && Number.isFinite(value)) return;
4926
- if (!value || typeof value != "object" || ancestors.has(value)) return fail3("invalid_input");
4927
- let array3 = Array.isArray(value), keys4 = Reflect.ownKeys(value);
4928
- if (!array3 && ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || array3 && (keys4.length !== value.length + 1 || !Array.from({ length: value.length }, (_, index) => Object.hasOwn(value, index)).every(Boolean))) return fail3("invalid_input");
5812
+ if (!value || typeof value != "object" || ancestors.has(value)) return fail6("invalid_input");
5813
+ let array3 = Array.isArray(value), keys6 = Reflect.ownKeys(value);
5814
+ 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");
4929
5815
  ancestors.add(value);
4930
- for (let key of keys4) {
5816
+ for (let key of keys6) {
4931
5817
  if (array3 && key === "length") continue;
4932
5818
  let descriptor = Object.getOwnPropertyDescriptor(value, key);
4933
- if (typeof key != "string" || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) return fail3("invalid_input");
5819
+ if (typeof key != "string" || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) return fail6("invalid_input");
4934
5820
  jsonInput(descriptor.value, ancestors);
4935
5821
  }
4936
5822
  ancestors.delete(value);
@@ -4939,26 +5825,26 @@ function structure(value) {
4939
5825
  return JSON.stringify(value, (_key, item) => item && typeof item == "object" && !Array.isArray(item) ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, item[key]])) : item);
4940
5826
  }
4941
5827
  function handle(key, id3, context) {
4942
- (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail3("authority_unavailable"), (typeof id3 != "string" || !uuid2.test(id3)) && fail3("invalid_input");
4943
- let read2 = async () => summary(await request(key, `runs/${id3}`, void 0, SUMMARY_BYTES, context, !0), key, context, id3);
5828
+ (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail6("authority_unavailable"), (typeof id3 != "string" || !uuid3.test(id3)) && fail6("invalid_input");
5829
+ let read2 = async () => summary(await request2(key, `runs/${id3}`, void 0, SUMMARY_BYTES, context, !0), key, context, id3);
4944
5830
  return routineRunHandle({
4945
5831
  async current() {
4946
5832
  return current(context), read2();
4947
5833
  },
4948
5834
  async step(step) {
4949
- (typeof step != "string" || !identifier.test(step)) && fail3("invalid_input");
4950
- let value = await request(key, `runs/${id3}/steps/${step}`, void 0, ROUTINE_STEP_OUTPUT_BYTES + 4096, context, !0);
5835
+ (typeof step != "string" || !identifier.test(step)) && fail6("invalid_input");
5836
+ let value = await request2(key, `runs/${id3}/steps/${step}`, void 0, ROUTINE_STEP_OUTPUT_BYTES + 4096, context, !0);
4951
5837
  if (context.kind !== "local")
4952
5838
  try {
4953
- return only(value, "id,title,status,startedAt,finishedAt,progress,summary,data") || fail3("execution_unavailable"), parseRunStep(value, step);
5839
+ return only(value, "id,title,status,startedAt,finishedAt,progress,summary,data") || fail6("execution_unavailable"), parseRunStep(value, step);
4954
5840
  } catch {
4955
- return fail3("execution_unavailable");
5841
+ return fail6("execution_unavailable");
4956
5842
  }
4957
- return (!only(value, "id,title,status,startedAt,finishedAt,progress,summary,data") || value.id !== step || !validStep(value)) && fail3("execution_unavailable"), value;
5843
+ return (!only(value, "id,title,status,startedAt,finishedAt,progress,summary,data") || value.id !== step || !validStep(value)) && fail6("execution_unavailable"), value;
4958
5844
  }
4959
5845
  });
4960
5846
  }
4961
- function unavailable4(key, reason) {
5847
+ function unavailable5(key, reason) {
4962
5848
  let descriptor = appDescriptors().find((item) => item.id === key);
4963
5849
  return {
4964
5850
  ...structuredClone(descriptor),
@@ -4967,7 +5853,7 @@ function unavailable4(key, reason) {
4967
5853
  };
4968
5854
  }
4969
5855
  function deployedDescription(value, key) {
4970
- (!only(value, "id,title,input,connections,steps,readiness") || value.id !== key || value.title !== void 0 && (typeof value.title != "string" || !value.title.trim() || value.title.length > 256) || !only(value.input, "type,properties,required,additionalProperties,items,maxItems,maxLength,minimum,maximum,storage,path,default") || !Array.isArray(value.steps) || value.steps.length > 64 || value.steps.some((step) => !only(step, "id,title") || typeof step.title != "string" || !step.title.trim() || step.title.length > 256) || !Array.isArray(value.connections) || value.connections.length > 64 || value.connections.some((item) => !only(item, "id,provider,name,available") || typeof item.available != "boolean" || typeof item.provider != "string" || !identifier.test(item.provider) || typeof item.name != "string" || !identifier.test(item.name) || item.id !== `${item.provider}/${item.name}`) || new Set(value.connections.map((item) => item.id)).size !== value.connections.length) && fail3("execution_unavailable");
5856
+ (!only(value, "id,title,input,connections,steps,readiness") || value.id !== key || value.title !== void 0 && (typeof value.title != "string" || !value.title.trim() || value.title.length > 256) || !only(value.input, "type,properties,required,additionalProperties,items,maxItems,maxLength,minimum,maximum,storage,path,default") || !Array.isArray(value.steps) || value.steps.length > 64 || value.steps.some((step) => !only(step, "id,title") || typeof step.title != "string" || !step.title.trim() || step.title.length > 256) || !Array.isArray(value.connections) || value.connections.length > 64 || value.connections.some((item) => !only(item, "id,provider,name,available") || typeof item.available != "boolean" || typeof item.provider != "string" || !identifier.test(item.provider) || typeof item.name != "string" || !identifier.test(item.name) || item.id !== `${item.provider}/${item.name}`) || new Set(value.connections.map((item) => item.id)).size !== value.connections.length) && fail6("execution_unavailable");
4971
5857
  let { default: inputDefault, ...input } = value.input, contract = parseAppRoutineContract({
4972
5858
  routine: key,
4973
5859
  input,
@@ -4977,44 +5863,44 @@ function deployedDescription(value, key) {
4977
5863
  }
4978
5864
  async function describeAppRoutine(key) {
4979
5865
  let descriptor = appDescriptors().find((item) => item.id === key);
4980
- if (!descriptor) return fail3("authority_unavailable");
5866
+ if (!descriptor) return fail6("authority_unavailable");
4981
5867
  try {
4982
- let context = await authority(), value = await request(key, "describe", void 0, 1024 * 1024, context);
4983
- return context.kind !== "local" && deployedDescription(value, key), (!only(value, "id,title,input,connections,steps,readiness") || !value.readiness || !Array.isArray(value.connections) || context.kind === "local" && structure({ ...value, readiness: void 0, connections: value.connections.map(({ available, ...item }) => item) }) !== structure(descriptor) || value.connections.some((item) => typeof item.available != "boolean") || !(value.readiness.state === "ready" && only(value.readiness, "state,placement") && value.readiness.placement === (context.kind === "local" ? "local" : "remote") || value.readiness.state === "unavailable" && only(value.readiness, "state,reason,message") && ["not_deployed", "definition_invalid", "capability_unavailable"].includes(value.readiness.reason) && message(value.readiness.message))) && fail3("execution_unavailable"), value;
5868
+ let context = await authority(), value = await request2(key, "describe", void 0, 1024 * 1024, context);
5869
+ return context.kind !== "local" && deployedDescription(value, key), (!only(value, "id,title,input,connections,steps,readiness") || !value.readiness || !Array.isArray(value.connections) || context.kind === "local" && structure({ ...value, readiness: void 0, connections: value.connections.map(({ available, ...item }) => item) }) !== structure(descriptor) || value.connections.some((item) => typeof item.available != "boolean") || !(value.readiness.state === "ready" && only(value.readiness, "state,placement") && value.readiness.placement === (context.kind === "local" ? "local" : "remote") || value.readiness.state === "unavailable" && only(value.readiness, "state,reason,message") && ["not_deployed", "definition_invalid", "capability_unavailable"].includes(value.readiness.reason) && message(value.readiness.message))) && fail6("execution_unavailable"), value;
4984
5870
  } catch {
4985
- return unavailable4(key, "capability_unavailable");
5871
+ return unavailable5(key, "capability_unavailable");
4986
5872
  }
4987
5873
  }
4988
5874
  function appRoutineBinding(key) {
4989
- return (typeof key != "string" || !identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail3("authority_unavailable"), Object.freeze({
5875
+ return (typeof key != "string" || !identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail6("authority_unavailable"), Object.freeze({
4990
5876
  describe: () => describeAppRoutine(key),
4991
5877
  async run(...args) {
4992
- args.length > 1 && fail3("invalid_input");
5878
+ args.length > 1 && fail6("invalid_input");
4993
5879
  let encoded;
4994
5880
  try {
4995
5881
  if (args[0] === void 0) encoded = "{}";
4996
5882
  else {
4997
5883
  jsonInput(args[0]);
4998
5884
  let input = JSON.stringify(args[0]);
4999
- new TextEncoder().encode(input).byteLength > 256 * 1024 && fail3("invalid_input"), encoded = `{"input":${input}}`;
5885
+ new TextEncoder().encode(input).byteLength > 256 * 1024 && fail6("invalid_input"), encoded = `{"input":${input}}`;
5000
5886
  }
5001
5887
  } catch {
5002
- return fail3("invalid_input");
5888
+ return fail6("invalid_input");
5003
5889
  }
5004
5890
  let context = await authority();
5005
5891
  context.kind !== "local" && (encoded = JSON.stringify({ ...JSON.parse(encoded), startKey: crypto.randomUUID() }));
5006
- let run = summary(await request(key, "runs", { method: "POST", body: encoded }, SUMMARY_BYTES, context), key, context);
5892
+ let run = summary(await request2(key, "runs", { method: "POST", body: encoded }, SUMMARY_BYTES, context), key, context);
5007
5893
  return handle(key, run.id, context);
5008
5894
  },
5009
5895
  runs: Object.freeze({
5010
5896
  async list() {
5011
- let context = await authority(!0), value = await request(key, "runs", void 0, 20 * SUMMARY_BYTES, context, !0);
5012
- if (!Array.isArray(value) || value.length > 20) return fail3("execution_unavailable");
5897
+ let context = await authority(!0), value = await request2(key, "runs", void 0, 20 * SUMMARY_BYTES, context, !0);
5898
+ if (!Array.isArray(value) || value.length > 20) return fail6("execution_unavailable");
5013
5899
  let runs = value.map((run) => summary(run, key, context));
5014
- return new Set(runs.map((run) => run.id)).size !== runs.length && fail3("execution_unavailable"), runs;
5900
+ return new Set(runs.map((run) => run.id)).size !== runs.length && fail6("execution_unavailable"), runs;
5015
5901
  },
5016
5902
  async get(id3) {
5017
- return (typeof id3 != "string" || !uuid2.test(id3)) && fail3("invalid_input"), (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail3("authority_unavailable"), handle(key, id3, await authority(!0));
5903
+ return (typeof id3 != "string" || !uuid3.test(id3)) && fail6("invalid_input"), (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail6("authority_unavailable"), handle(key, id3, await authority(!0));
5018
5904
  }
5019
5905
  })
5020
5906
  });
@@ -5034,11 +5920,11 @@ var app = /* @__PURE__ */ Object.freeze({
5034
5920
  })
5035
5921
  });
5036
5922
 
5037
- async function requestInboxPublication(operation2, request2, caller) {
5923
+ async function requestInboxPublication(operation2, request3, caller) {
5038
5924
  let attempt = () => {
5039
5925
  if (caller?.aborted) throw caller.reason;
5040
5926
  let timeout = AbortSignal.timeout(3e4);
5041
- return request2(caller ? AbortSignal.any([caller, timeout]) : timeout);
5927
+ return request3(caller ? AbortSignal.any([caller, timeout]) : timeout);
5042
5928
  };
5043
5929
  if (operation2 !== "publish") return attempt();
5044
5930
  try {
@@ -5056,7 +5942,7 @@ function routinePublicationClient2(options = {}) {
5056
5942
  let environment = {}, installed2 = options.request ? void 0 : routineTransport(), local2 = options.request ? void 0 : installed2?.request ?? void 0, workspace = installed2 ? "installed" : options.workspace ?? environment.OS_ROUTINE_WORKSPACE, capability = options.capability ?? (options.request ? void 0 : environment.OS_ROUTINE_RUN);
5057
5943
  if (!workspace || !/^[a-z0-9][a-z0-9-]*$/.test(workspace) || capability !== void 0 && !/^[0-9a-f]{64}$/.test(capability))
5058
5944
  throw new Error("A workspace and valid optional routine capability are required");
5059
- let headers = capability ? { "x-os-run": capability } : {}, request2 = options.request ?? (capability ? async (path, init2) => {
5945
+ let headers = capability ? { "x-os-run": capability } : {}, request3 = options.request ?? (capability ? async (path, init2) => {
5060
5946
  let origin = `https://${workspace}.oddington.ai`, target = new URL(path, `${origin}/`);
5061
5947
  if (workspace.length > 63 || ["auth", "www", "api", "os"].includes(workspace) || target.origin !== origin || target.search || target.hash || target.username || target.password || !/^\/api\/inbox\/(check|publish|resolve)$/.test(path) || init2?.method !== "POST")
5062
5948
  throw new Error("Invalid routine endpoint");
@@ -5066,7 +5952,7 @@ function routinePublicationClient2(options = {}) {
5066
5952
  });
5067
5953
  async function send3(operation2, body) {
5068
5954
  if (local2) return await local2(operation2, body);
5069
- let response2 = await requestInboxPublication(operation2, (signal) => request2(`/api/inbox/${operation2}`, {
5955
+ let response2 = await requestInboxPublication(operation2, (signal) => request3(`/api/inbox/${operation2}`, {
5070
5956
  method: "POST",
5071
5957
  headers: { "content-type": "application/json", ...headers },
5072
5958
  body: JSON.stringify(body),