@oddington/sdk 0.1.53 → 0.1.55

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,861 @@ 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 unavailable2 = () => {
2408
+ throw new DataOperationError("unavailable", !0);
2409
+ };
2410
+ function request(value) {
2411
+ return new Promise((resolve, reject) => {
2412
+ value.onsuccess = () => resolve(value.result), value.onerror = () => reject(new DataOperationError("unavailable", !0));
2413
+ });
2414
+ }
2415
+ function completed(transaction) {
2416
+ let done = new Promise((resolve, reject) => {
2417
+ transaction.oncomplete = () => resolve(), transaction.onabort = transaction.onerror = () => reject(new DataOperationError("unavailable", !0));
2418
+ });
2419
+ return done.catch(() => {
2420
+ }), done;
2421
+ }
2422
+ function encode(bytes) {
2423
+ return btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""));
2424
+ }
2425
+ async function openSnapshotStore() {
2426
+ let opening = indexedDB.open("oddington.data.snapshots.v2", 1);
2427
+ opening.onupgradeneeded = () => {
2428
+ opening.result.createObjectStore("current"), opening.result.createObjectStore("changes"), opening.result.createObjectStore("records", { keyPath: ["installation", "ref"] }).createIndex("collection", ["installation", "collection"]);
2429
+ };
2430
+ let database = await request(opening);
2431
+ return database.onversionchange = () => database.close(), {
2432
+ close() {
2433
+ database.close();
2434
+ },
2435
+ async current(partition) {
2436
+ let transaction = database.transaction(["current", "records", "changes"], "readonly"), done = completed(transaction), value = await request(transaction.objectStore("current").get(partition));
2437
+ if (!value) {
2438
+ await done;
2439
+ return;
2440
+ }
2441
+ if (value.partition !== partition || !value.id || !value.validator || !value.version || !Array.isArray(value.catalogue) || !value.counts || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
2442
+ await done;
2443
+ return;
2444
+ }
2445
+ let changes = await request(transaction.objectStore("changes").get(value.id)), complete = Array.isArray(changes) && changes.length === value.changeCount;
2446
+ for (let collection of value.catalogue)
2447
+ await request(transaction.objectStore("records").index("collection").count([value.id, collection.name])) !== value.counts[collection.name] && (complete = !1);
2448
+ return await done, complete ? value : void 0;
2449
+ },
2450
+ async install(partition, validator, envelope, changes, assertCurrent) {
2451
+ let installation = {
2452
+ id: crypto.randomUUID(),
2453
+ partition,
2454
+ validator,
2455
+ version: envelope.version,
2456
+ catalogue: envelope.catalogue,
2457
+ changeCount: changes.length,
2458
+ cursorKey: crypto.getRandomValues(new Uint8Array(32)),
2459
+ counts: Object.fromEntries(Object.entries(envelope.collections).map(([name2, rows]) => [name2, rows.length]))
2460
+ }, transaction = database.transaction(["current", "records", "changes"], "readwrite"), done = completed(transaction);
2461
+ try {
2462
+ assertCurrent();
2463
+ let records = transaction.objectStore("records");
2464
+ for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
2465
+ records.put({ installation: installation.id, collection, ref: record4.$ref, record: record4 });
2466
+ return await request(transaction.objectStore("changes").put(changes, installation.id)), await request(transaction.objectStore("current").put(installation, partition)), assertCurrent(), await done, assertCurrent(), installation;
2467
+ } catch (error) {
2468
+ try {
2469
+ transaction.abort();
2470
+ } catch {
2471
+ }
2472
+ throw await done.catch(() => {
2473
+ }), error;
2474
+ }
2475
+ },
2476
+ async read(installation, ref) {
2477
+ 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]));
2478
+ return await done, count !== installation.counts[collection] ? unavailable2() : row?.record ?? null;
2479
+ },
2480
+ async changes(installation) {
2481
+ let transaction = database.transaction("changes", "readonly"), done = completed(transaction), rows = await request(transaction.objectStore("changes").get(installation.id));
2482
+ return await done, !rows || rows.length !== installation.changeCount ? unavailable2() : rows;
2483
+ },
2484
+ async query(installation, query, maxRecords) {
2485
+ 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 () => {
2486
+ await done, transaction = void 0, done = void 0;
2487
+ }, evaluation = evaluateRecordsQuery(query, installation.catalogue, {
2488
+ workspaceId: installation.partition,
2489
+ repository: installation.partition,
2490
+ identity: installation.id,
2491
+ version: installation.version
2492
+ }, maxRecords);
2493
+ try {
2494
+ let step = evaluation.next();
2495
+ for (; !step.done; ) {
2496
+ let work = step.value, value;
2497
+ if (work.operation === "scan") {
2498
+ let rows = await request(records().index("collection").getAll([installation.id, work.collection]));
2499
+ if (rows.length !== installation.counts[work.collection]) return unavailable2();
2500
+ value = rows.map((row) => row.record);
2501
+ } else if (work.operation === "lookup") {
2502
+ let row = await request(records().get([installation.id, work.ref]));
2503
+ value = row && { record: row.record, collection: row.collection };
2504
+ } else if (await finish(), work.operation === "seal") {
2505
+ let iv = crypto.getRandomValues(new Uint8Array(12)), sealed = new Uint8Array(await crypto.subtle.encrypt(
2506
+ { name: "AES-GCM", iv },
2507
+ key,
2508
+ new TextEncoder().encode(JSON.stringify(work.payload))
2509
+ ));
2510
+ value = encode(new Uint8Array([...iv, ...sealed]));
2511
+ } else
2512
+ try {
2513
+ 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));
2514
+ value = JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(opened));
2515
+ } catch {
2516
+ throw new DataOperationError("invalid_query");
2517
+ }
2518
+ step = evaluation.next(value);
2519
+ }
2520
+ return await finish(), step.value;
2521
+ } catch (error) {
2522
+ try {
2523
+ transaction?.abort();
2524
+ } catch {
2525
+ }
2526
+ throw await done?.catch(() => {
2527
+ }), error;
2528
+ }
2529
+ }
2530
+ };
2531
+ }
2532
+
2533
+ var invalid8 = () => {
2534
+ throw new DataOperationError("unavailable", !0);
2535
+ }, 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)), snapshotAcquisitionType = "application/vnd.oddington.data-snapshot+json";
2536
+ function validateAcquisition(input, repository, name2) {
2537
+ let row = object5(input), snapshot = object5(row.snapshot);
2538
+ if (Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== "data-snapshot-acquisition.v1" || 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();
2539
+ let ids = /* @__PURE__ */ new Set(), unpublished = !1;
2540
+ for (let value of row.changes) {
2541
+ let c = object5(value), effect = object5(c.effect);
2542
+ 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();
2543
+ if (ids.add(c.id), c.source !== void 0) {
2544
+ let source2 = object5(c.source);
2545
+ if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid8();
2546
+ }
2547
+ if (c.publication !== void 0) {
2548
+ let publication = object5(c.publication);
2549
+ 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();
2550
+ } else unpublished = !0;
2551
+ if (effect.kind === "set") {
2552
+ 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();
2553
+ } else if (effect.kind === "create" || effect.kind === "delete") {
2554
+ if (Object.keys(effect).sort().join(",") !== "fields,kind") return invalid8();
2555
+ object5(effect.fields);
2556
+ } else return invalid8();
2557
+ }
2558
+ return {
2559
+ snapshot,
2560
+ changes: row.changes
2561
+ };
2562
+ }
2563
+ function materializeSnapshot(envelope, changes, version) {
2564
+ try {
2565
+ if (!changes.length) return envelope;
2566
+ let rows = new Map(Object.values(envelope.collections).flat().map((r) => [r.$ref, structuredClone(r)]));
2567
+ for (let c of changes) {
2568
+ let schema2 = envelope.catalogue.find((s) => c.ref.startsWith(`${s.name}/`));
2569
+ if (!schema2) return invalid8();
2570
+ let effect = c.effect, definitions2 = effect.kind === "set" ? schema2.schema.fields.filter((f) => f.name === effect.field) : schema2.schema.fields;
2571
+ if (effect.kind === "set" && !definitions2.length) return invalid8();
2572
+ if (validateRecordFields(
2573
+ effect.kind === "set" ? { [effect.field]: effect.value } : effect.fields,
2574
+ definitions2,
2575
+ (_ref, targets) => targets[0],
2576
+ !0
2577
+ ), !c.publication) continue;
2578
+ let prior = rows.get(c.ref);
2579
+ if (effect.kind === "set") {
2580
+ if (!prior) return invalid8();
2581
+ rows.set(c.ref, { ...prior, [effect.field]: effect.value, $version: c.recordVersion });
2582
+ } else if (effect.kind === "create") {
2583
+ if (prior) return invalid8();
2584
+ rows.set(c.ref, { ...effect.fields, $ref: c.ref, $version: c.recordVersion });
2585
+ } else {
2586
+ if (!prior) return invalid8();
2587
+ rows.delete(c.ref);
2588
+ }
2589
+ }
2590
+ return validateSnapshotEnvelope({
2591
+ format: envelope.format,
2592
+ repository: envelope.repository,
2593
+ name: envelope.name,
2594
+ version,
2595
+ schemas: Object.fromEntries(envelope.catalogue.map((c) => [c.name, {
2596
+ name: c.name,
2597
+ type: c.schema.type,
2598
+ ...c.schema.description === void 0 ? {} : { description: c.schema.description },
2599
+ fields: c.schema.fields.map(publicField)
2600
+ }])),
2601
+ 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)]))
2602
+ }, envelope.repository, envelope.name);
2603
+ } catch {
2604
+ return invalid8();
2605
+ }
2606
+ }
2607
+
2608
+ var invalid9 = () => {
2609
+ throw new DataOperationError("invalid_query");
2610
+ }, safeName = (value) => typeof value == "string" && /^[a-z0-9][a-z0-9._-]{0,127}$/.test(value) && !value.includes("..");
2611
+ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore) {
2612
+ let pending = /* @__PURE__ */ new WeakMap();
2613
+ return async function(input) {
2614
+ let properties = dataProperties(input), repository = properties.repository?.value, snapshot = properties.snapshot?.value;
2615
+ if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid9();
2616
+ let authority2 = await resolve(), invalidated = !1, assertCurrent = () => {
2617
+ if (invalidated || !authority2.isCurrent())
2618
+ throw invalidated = !0, new DataOperationError("context_unavailable");
2619
+ };
2620
+ assertCurrent();
2621
+ let partition = JSON.stringify([authority2.endpoint, authority2.memberId, authority2.workspace, repository, snapshot]), work = pending.get(authority2.binding);
2622
+ work || (work = /* @__PURE__ */ new Map(), pending.set(authority2.binding, work));
2623
+ let installing = work.get(partition);
2624
+ installing || (installing = (async () => {
2625
+ let store = await open();
2626
+ try {
2627
+ let cached = await store.current(partition);
2628
+ assertCurrent();
2629
+ let url = `${authority2.endpoint}/api/data/snapshots/${repository}/${snapshot}`;
2630
+ for (let attempt = 0; attempt < 3; attempt++) {
2631
+ let response2 = await fetch(url, {
2632
+ method: "GET",
2633
+ redirect: "error",
2634
+ cache: "no-store",
2635
+ headers: {
2636
+ ...authority2.headers,
2637
+ accept: snapshotAcquisitionType,
2638
+ ...cached ? { "if-none-match": cached.validator } : {}
2639
+ }
2640
+ });
2641
+ if (assertCurrent(), response2.status === 409) {
2642
+ await response2.body?.cancel();
2643
+ continue;
2644
+ }
2645
+ let validator = response2.headers.get("etag");
2646
+ if (response2.status === 304) {
2647
+ if (!cached || validator !== cached.validator) throw new DataOperationError("unavailable", !0);
2648
+ return cached;
2649
+ }
2650
+ if (!response2.ok) throw dataTransportError(response2.status, await response2.json().catch(() => {
2651
+ }));
2652
+ if (!validator || !/^"[^"\r\n]+"$/.test(validator) || response2.headers.get("content-type")?.split(";")[0] !== "application/json") throw new DataOperationError("unavailable", !0);
2653
+ let acquired = validateAcquisition(await response2.json(), repository, snapshot);
2654
+ assertCurrent();
2655
+ let artifact = await fetch(url, {
2656
+ method: "GET",
2657
+ redirect: "error",
2658
+ cache: "no-store",
2659
+ headers: { ...authority2.headers, "if-match": validator }
2660
+ });
2661
+ if (assertCurrent(), artifact.status === 409) {
2662
+ await artifact.body?.cancel();
2663
+ continue;
2664
+ }
2665
+ if (!artifact.ok) throw dataTransportError(artifact.status, await artifact.json().catch(() => {
2666
+ }));
2667
+ if (artifact.headers.get("etag") !== validator || !artifact.body || artifact.headers.get("content-type")?.split(";")[0] !== "application/gzip") throw new DataOperationError("unavailable", !0);
2668
+ 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);
2669
+ if (envelope.version !== acquired.snapshot.version || envelope.catalogue.map((c) => c.name).join("\0") !== acquired.snapshot.collections.join("\0")) throw new DataOperationError("unavailable", !0);
2670
+ let published = acquired.changes.filter((c) => c.publication), version = envelope.version;
2671
+ if (published.length) {
2672
+ let digest = new Uint8Array(await crypto.subtle.digest(
2673
+ "SHA-256",
2674
+ new TextEncoder().encode(JSON.stringify([envelope.version, published]))
2675
+ ));
2676
+ version = `snapshot-${Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
2677
+ }
2678
+ let materialized = materializeSnapshot(envelope, acquired.changes, version);
2679
+ return assertCurrent(), await store.install(partition, validator, materialized, acquired.changes, assertCurrent);
2680
+ }
2681
+ throw new DataOperationError("unavailable", !0);
2682
+ } finally {
2683
+ store.close();
2684
+ }
2685
+ })(), work.set(partition, installing), installing.finally(() => {
2686
+ work.get(partition) === installing && work.delete(partition);
2687
+ }).catch(() => {
2688
+ }));
2689
+ let installation;
2690
+ try {
2691
+ installation = await installing, assertCurrent();
2692
+ } catch (error) {
2693
+ throw assertCurrent(), error instanceof DataOperationError ? error : new DataOperationError("unavailable", !0);
2694
+ }
2695
+ let query = async (query2, maxRecords) => {
2696
+ assertCurrent();
2697
+ let captured = captureRecordsQuery(query2);
2698
+ checkDataRequestSize({
2699
+ repository,
2700
+ operation: maxRecords === void 0 ? "records.query" : "records.all",
2701
+ query: captured,
2702
+ ...maxRecords === void 0 ? {} : { maxRecords }
2703
+ });
2704
+ let store;
2705
+ try {
2706
+ store = await open(), assertCurrent();
2707
+ let result2 = await store.query(installation, captured, maxRecords);
2708
+ return assertCurrent(), result2;
2709
+ } catch (error) {
2710
+ throw assertCurrent(), error instanceof DataOperationError ? error : error instanceof RecordValidationError ? new DataOperationError("invalid_query") : new DataOperationError("unavailable", !0);
2711
+ } finally {
2712
+ store?.close();
2713
+ }
2714
+ }, localRead = async (operation2) => {
2715
+ assertCurrent();
2716
+ let store;
2717
+ try {
2718
+ store = await open(), assertCurrent();
2719
+ let value = await operation2(store);
2720
+ return assertCurrent(), value;
2721
+ } catch (error) {
2722
+ throw assertCurrent(), error instanceof DataOperationError ? error : new DataOperationError("unavailable", !0);
2723
+ } finally {
2724
+ store?.close();
2725
+ }
2726
+ }, queryRecords = query;
2727
+ return { changes: { list: () => localRead((store) => store.changes(installation)) }, records: {
2728
+ read: async (ref, ...extra) => {
2729
+ if (typeof ref != "string" || extra.length) return Promise.reject(new DataOperationError("invalid_query"));
2730
+ let [captured] = captureRecordsReadRefs([ref]);
2731
+ return installation.catalogue.some((c) => captured.startsWith(`${c.name}/`)) ? localRead((store) => store.read(installation, captured)) : Promise.reject(new DataOperationError("invalid_query"));
2732
+ },
2733
+ query: queryRecords,
2734
+ ...recordPagination(queryRecords),
2735
+ all: (input2, options) => {
2736
+ let captured = captureRecordsAll(input2, options);
2737
+ return query(captured.query, captured.maxRecords);
2738
+ }
2739
+ } };
2740
+ };
2741
+ }
2742
+ var initializeSnapshot = /* @__PURE__ */ createSnapshotInitializer();
2743
+
1861
2744
  var genericData = {
2745
+ init: initializeSnapshot,
1862
2746
  repository(repository) {
1863
2747
  async function send3(input) {
1864
2748
  let context = await resolveDataContext(), envelope = { repository, ...input }, changing = "operation" in input && ["changes.validate", "changes.apply", "changes.publish"].includes(String(input.operation));
@@ -2015,7 +2899,7 @@ async function hostedContent(url, init2, parent, upstream = fetch, check = async
2015
2899
  }
2016
2900
  }
2017
2901
 
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 = {
2902
+ 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
2903
  400: ["invalid_input", "unsupported_context"],
2020
2904
  401: ["unauthenticated"],
2021
2905
  403: ["access_denied"],
@@ -2044,7 +2928,7 @@ function heldSlot() {
2044
2928
  };
2045
2929
  }
2046
2930
  async function acquireSlot(signal) {
2047
- if (signal?.aborted) throw unavailable2();
2931
+ if (signal?.aborted) throw unavailable3();
2048
2932
  return active < MAX_ACTIVE ? (active++, heldSlot()) : new Promise((resolve, reject) => {
2049
2933
  let waiter = {
2050
2934
  signal,
@@ -2055,7 +2939,7 @@ async function acquireSlot(signal) {
2055
2939
  if (!waiter.waiting) return;
2056
2940
  waiter.waiting = !1;
2057
2941
  let index = waiters.indexOf(waiter);
2058
- index !== -1 && waiters.splice(index, 1), reject(unavailable2());
2942
+ index !== -1 && waiters.splice(index, 1), reject(unavailable3());
2059
2943
  }
2060
2944
  };
2061
2945
  waiters.push(waiter), signal?.addEventListener("abort", waiter.abort, { once: !0 }), signal?.aborted && waiter.abort();
@@ -2071,7 +2955,7 @@ async function boundedBytes(stream, limit, signal) {
2071
2955
  try {
2072
2956
  for (; ; ) {
2073
2957
  let { done, value } = await reader.read();
2074
- if (signal?.aborted) throw unavailable2();
2958
+ if (signal?.aborted) throw unavailable3();
2075
2959
  if (done) break;
2076
2960
  if (!(value instanceof Uint8Array)) throw new FileOperationError("invalid_input", 400, !1, { reason: "invalid_bytes" });
2077
2961
  if (size += value.byteLength, size > limit) throw new FileOperationError(
@@ -2092,7 +2976,7 @@ async function boundedBytes(stream, limit, signal) {
2092
2976
  async function timed(work, parent, timeout = TIMEOUT_MS) {
2093
2977
  let controller = new AbortController(), timer, abort, expiry = new Promise((_, reject) => {
2094
2978
  abort = () => {
2095
- controller.abort(), reject(unavailable2());
2979
+ controller.abort(), reject(unavailable3());
2096
2980
  }, timer = setTimeout(abort, timeout), parent?.addEventListener("abort", abort, { once: !0 }), parent?.aborted && abort();
2097
2981
  });
2098
2982
  try {
@@ -2106,12 +2990,12 @@ async function result(response2, maximum = RESULT_BYTES) {
2106
2990
  let bytes = await boundedBytes(response2.body, maximum);
2107
2991
  return JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes));
2108
2992
  } catch {
2109
- throw unavailable2();
2993
+ throw unavailable3();
2110
2994
  }
2111
2995
  }
2112
2996
  async function send(suffix, init2, descriptor, initial, parent) {
2113
2997
  let original = initial, checkCurrent = (context = original) => {
2114
- if (parent?.aborted) throw unavailable2();
2998
+ if (parent?.aborted) throw unavailable3();
2115
2999
  if (!original.isCurrent() || context.url !== original.url) throw new FileOperationError("unsupported_context", 400);
2116
3000
  };
2117
3001
  for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
@@ -2120,14 +3004,14 @@ async function send(suffix, init2, descriptor, initial, parent) {
2120
3004
  checkCurrent(context);
2121
3005
  try {
2122
3006
  let response2 = context.localFiles ? await context.localFiles(suffix, init2, parent) : await (async () => {
2123
- let url = `${context.url}${suffix}`, request2 = {
3007
+ let url = `${context.url}${suffix}`, request3 = {
2124
3008
  ...init2,
2125
3009
  signal: parent,
2126
3010
  headers: { ...context.headers, ...init2.headers },
2127
3011
  redirect: "error",
2128
3012
  cache: "no-store"
2129
3013
  };
2130
- return descriptor ? fetch(url, request2) : hostedContent(url, request2, parent);
3014
+ return descriptor ? fetch(url, request3) : hostedContent(url, request3, parent);
2131
3015
  })();
2132
3016
  if (!response2.ok) {
2133
3017
  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 +3020,11 @@ async function send(suffix, init2, descriptor, initial, parent) {
2136
3020
  response2.status,
2137
3021
  code === "capacity" || code === "unavailable",
2138
3022
  parseFileErrorDetail(error?.detail)
2139
- ) : unavailable2();
3023
+ ) : unavailable3();
2140
3024
  }
2141
3025
  if (response2.status !== 200)
2142
3026
  throw response2.body?.cancel().catch(() => {
2143
- }), unavailable2();
3027
+ }), unavailable3();
2144
3028
  try {
2145
3029
  checkCurrent();
2146
3030
  } catch (error) {
@@ -2153,25 +3037,25 @@ async function send(suffix, init2, descriptor, initial, parent) {
2153
3037
  return checkCurrent(), value;
2154
3038
  let parsed;
2155
3039
  if (descriptor === "enrichment") {
2156
- if (!value || typeof value != "object" || Array.isArray(value)) throw unavailable2();
3040
+ if (!value || typeof value != "object" || Array.isArray(value)) throw unavailable3();
2157
3041
  let { name: name2, ...metadata } = value;
2158
- if (!safeEnrichmentName(name2)) throw unavailable2();
3042
+ if (!safeEnrichmentName(name2)) throw unavailable3();
2159
3043
  parsed = { name: name2, ...parseEnrichmentDescriptor(metadata) };
2160
3044
  } else parsed = parseFileDescriptor(value);
2161
3045
  return checkCurrent(), parsed;
2162
3046
  } catch (error) {
2163
- let failure = error instanceof FileOperationError ? error : unavailable2();
3047
+ let failure = error instanceof FileOperationError ? error : unavailable3();
2164
3048
  if (init2.body instanceof ReadableStream || !failure.retryable || attempt + 1 === ATTEMPTS) throw failure;
2165
3049
  }
2166
3050
  }
2167
- throw unavailable2();
3051
+ throw unavailable3();
2168
3052
  }
2169
3053
  function idPath(id3) {
2170
- if (typeof id3 != "string" || !FILE_ID_PATTERN.test(id3)) throw invalid7();
3054
+ if (typeof id3 != "string" || !FILE_ID_PATTERN.test(id3)) throw invalid10();
2171
3055
  return `/${id3}`;
2172
3056
  }
2173
3057
  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) => {
3058
+ 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
3059
  let task = work(signal);
2176
3060
  return pending.add(task), task.then(() => pending.delete(task), () => pending.delete(task)), task;
2177
3061
  }, void 0, timeout), control = (body) => ({
@@ -2182,15 +3066,15 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
2182
3066
  try {
2183
3067
  let startRequest = control(upload?.file ?? metadata);
2184
3068
  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();
3069
+ let start = await request3((signal) => exchange(`${route}/start`, startRequest, "control", signal));
3070
+ if (!start || typeof start != "object" || Array.isArray(start)) throw unavailable3();
2187
3071
  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();
3072
+ 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
3073
  ticket = session.ticket, input.file instanceof ReadableStream && (reader = input.file.getReader());
2190
3074
  let lastProgress = Date.now(), next = async () => {
2191
3075
  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)));
3076
+ if (Date.now() - lastProgress >= TIMEOUT_MS) throw unavailable3();
3077
+ let value = await request3(() => reader.read(), Math.max(1, TIMEOUT_MS - (Date.now() - lastProgress)));
2194
3078
  return value.value?.byteLength && (lastProgress = Date.now()), value;
2195
3079
  } catch (error) {
2196
3080
  throw await reader.cancel(error).catch(() => {
@@ -2202,7 +3086,7 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
2202
3086
  if (input.file instanceof Uint8Array) part = new Uint8Array(input.file.subarray(sent, sent + length));
2203
3087
  else if (input.file instanceof Blob) {
2204
3088
  let slice = input.file.slice(sent, sent + length);
2205
- part = new Uint8Array(await request2(() => slice.arrayBuffer()));
3089
+ part = new Uint8Array(await request3(() => slice.arrayBuffer()));
2206
3090
  } else {
2207
3091
  part = new Uint8Array(length);
2208
3092
  let filled = 0;
@@ -2210,33 +3094,33 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
2210
3094
  if (!chunk || offset === chunk.byteLength) {
2211
3095
  chunk = void 0, offset = 0;
2212
3096
  let value2 = await next();
2213
- if (value2.done || !(value2.value instanceof Uint8Array) || (chunk = value2.value, chunk.byteLength > metadata.size - sent - filled)) throw invalid7();
3097
+ if (value2.done || !(value2.value instanceof Uint8Array) || (chunk = value2.value, chunk.byteLength > metadata.size - sent - filled)) throw invalid10();
2214
3098
  }
2215
3099
  let take = Math.min(length - filled, chunk.byteLength - offset);
2216
3100
  part.set(chunk.subarray(offset, offset + take), filled), filled += take, offset += take, offset === chunk.byteLength && (chunk = void 0, offset = 0);
2217
3101
  }
2218
3102
  }
2219
- if (part.byteLength !== length) throw invalid7();
3103
+ if (part.byteLength !== length) throw invalid10();
2220
3104
  if (reader && sent + length === metadata.size)
2221
3105
  for (lastProgress = Date.now(); ; ) {
2222
3106
  let value2 = await next();
2223
3107
  if (value2.done) break;
2224
- if (!(value2.value instanceof Uint8Array) || value2.value.byteLength) throw invalid7();
3108
+ if (!(value2.value instanceof Uint8Array) || value2.value.byteLength) throw invalid10();
2225
3109
  }
2226
- let value = await request2((signal) => exchange(`${route}/part`, {
3110
+ let value = await request3((signal) => exchange(`${route}/part`, {
2227
3111
  method: "POST",
2228
3112
  headers: { "content-type": "application/octet-stream", "x-os-transfer": ticket, "x-os-part": String(partNumber) },
2229
3113
  body: part.buffer
2230
3114
  }, "control", signal));
2231
3115
  part = void 0;
2232
3116
  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();
3117
+ 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
3118
  receipts.push({ partNumber, etag: receipt.etag }), sent += length, lastProgress = Date.now();
2235
3119
  }
2236
3120
  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)}`, {
3121
+ let bytes = await request3(() => upload.enrichment(name2));
3122
+ if (bytes.byteLength !== upload.file.enrichments[name2].size || bytes.byteLength > MAX_BYTES) throw invalid10();
3123
+ await request3((signal) => exchange(`${route}/enrichments/${encodeURIComponent(name2)}`, {
2240
3124
  method: "POST",
2241
3125
  headers: { "content-type": "application/octet-stream", "x-os-transfer": ticket },
2242
3126
  body: bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
@@ -2244,20 +3128,20 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
2244
3128
  }
2245
3129
  await upload?.beforeComplete();
2246
3130
  let completion = control({ parts: receipts });
2247
- if (new TextEncoder().encode(completion.body).byteLength > 128 * 1024) throw unavailable2();
2248
- let completed = parseFileDescriptor(await request2(
3131
+ if (new TextEncoder().encode(completion.body).byteLength > 128 * 1024) throw unavailable3();
3132
+ let completed2 = parseFileDescriptor(await request3(
2249
3133
  (signal) => exchange(`${route}/complete`, completion, !0, signal),
2250
3134
  TIMEOUT_MS + Math.ceil(metadata.size / (1024 * 1024)) * 1e3
2251
3135
  ));
2252
3136
  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();
3137
+ let acknowledged = await request3((signal) => exchange(`${route}/acknowledge`, control(completed2), "control", signal));
3138
+ if (!acknowledged || typeof acknowledged != "object" || Object.keys(acknowledged).join(",") !== "acknowledged" || acknowledged.acknowledged !== !0) throw unavailable3();
2255
3139
  }
2256
- return completed;
3140
+ return completed2;
2257
3141
  } catch (error) {
2258
3142
  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();
3143
+ }), ticket && await request3((signal) => exchange(`${route}/abort`, control({}), "control", signal)).catch(() => {
3144
+ }), error instanceof FileOperationError ? error : unavailable3();
2261
3145
  } finally {
2262
3146
  chunk = void 0, reader?.releaseLock(), pending.size ? Promise.allSettled([...pending]).then(release) : release();
2263
3147
  }
@@ -2271,13 +3155,13 @@ async function operation(work, initial, parent) {
2271
3155
  }
2272
3156
  };
2273
3157
  return context.localFiles ? execute(signal ?? new AbortController().signal) : timed(execute, signal).catch((error) => {
2274
- throw error instanceof FileOperationError ? error : unavailable2();
3158
+ throw error instanceof FileOperationError ? error : unavailable3();
2275
3159
  });
2276
3160
  }
2277
3161
  function contentPath(id3, name2) {
2278
3162
  let path = idPath(id3);
2279
3163
  if (name2 === void 0) return `${path}/content`;
2280
- if (!safeEnrichmentName(name2)) throw invalid7();
3164
+ if (!safeEnrichmentName(name2)) throw invalid10();
2281
3165
  return `${path}/enrichments/${encodeURIComponent(name2)}/content`;
2282
3166
  }
2283
3167
  async function read(id3, names) {
@@ -2286,12 +3170,12 @@ async function read(id3, names) {
2286
3170
  let path = contentPath(id3, names);
2287
3171
  return operation((context2, signal) => send(path, { method: "GET" }, !1, context2, signal), context);
2288
3172
  }
2289
- if (!Array.isArray(names)) throw invalid7();
3173
+ if (!Array.isArray(names)) throw invalid10();
2290
3174
  let distinct = [], seen = /* @__PURE__ */ new Set();
2291
3175
  for (let name2 of names) {
2292
- if (typeof name2 != "string" || !safeEnrichmentName(name2)) throw invalid7();
3176
+ if (typeof name2 != "string" || !safeEnrichmentName(name2)) throw invalid10();
2293
3177
  if (!seen.has(name2)) {
2294
- if (seen.size === 16) throw invalid7();
3178
+ if (seen.size === 16) throw invalid10();
2295
3179
  seen.add(name2), distinct.push(name2);
2296
3180
  }
2297
3181
  }
@@ -2316,16 +3200,16 @@ var files = {
2316
3200
  async upload(id3) {
2317
3201
  return operation(async (context, signal) => {
2318
3202
  let file2 = await send(`${idPath(id3)}/upload`, { method: "POST" }, !0, context, signal);
2319
- if (file2.id !== id3) throw unavailable2();
3203
+ if (file2.id !== id3) throw unavailable3();
2320
3204
  return file2;
2321
3205
  });
2322
3206
  },
2323
3207
  async create(input, options) {
2324
3208
  let context = await resolveFilesContext();
2325
3209
  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();
3210
+ throw invalid10();
2327
3211
  let blob = input.file instanceof Blob, array3 = input.file instanceof Uint8Array, stream = input.file instanceof ReadableStream;
2328
- if (!blob && !array3 && !stream) throw invalid7();
3212
+ if (!blob && !array3 && !stream) throw invalid10();
2329
3213
  let intrinsic = blob ? input.file.size : array3 ? input.file.byteLength : void 0;
2330
3214
  if (intrinsic !== void 0 && input.size !== void 0 && input.size !== intrinsic)
2331
3215
  throw !Number.isSafeInteger(input.size) || input.size < 0 ? new FileOperationError("invalid_input", 400, !1, { reason: "invalid_size" }) : new FileOperationError(
@@ -2346,7 +3230,7 @@ var files = {
2346
3230
  }, FILE_ORIGINAL_MAX_BYTES);
2347
3231
  if (!context.local && !context.localFiles && metadata.storage === "local") throw new FileOperationError("unsupported_context", 400);
2348
3232
  let header = encodeURIComponent(JSON.stringify(metadata));
2349
- if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid7();
3233
+ if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid10();
2350
3234
  let release = await acquireSlot(context.signal);
2351
3235
  if (context.localFiles && !routineTransport() && metadata.size > MAX_BYTES)
2352
3236
  try {
@@ -2380,7 +3264,7 @@ var files = {
2380
3264
  !1,
2381
3265
  { reason: "size_mismatch", expectedBytes: metadata.size, receivedBytes: bytes.byteLength }
2382
3266
  );
2383
- if (signal.aborted) throw unavailable2();
3267
+ if (signal.aborted) throw unavailable3();
2384
3268
  return await send("", {
2385
3269
  method: "POST",
2386
3270
  headers: { "content-type": "application/octet-stream", "x-os-file": header },
@@ -2390,12 +3274,12 @@ var files = {
2390
3274
  release();
2391
3275
  }
2392
3276
  }, context.signal).catch((error) => {
2393
- throw error instanceof FileOperationError ? error : unavailable2();
3277
+ throw error instanceof FileOperationError ? error : unavailable3();
2394
3278
  });
2395
3279
  },
2396
3280
  async enrich(input) {
2397
3281
  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();
3282
+ 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
3283
  let path = `${idPath(input.file)}/enrichments`;
2400
3284
  if (typeof input.content == "string" ? input.content.length > MAX_BYTES : input.content.byteLength > MAX_BYTES)
2401
3285
  throw new FileOperationError("request_too_large", 413);
@@ -2412,12 +3296,12 @@ var files = {
2412
3296
  ...input.mediaType === void 0 ? {} : { mediaType: input.mediaType },
2413
3297
  ...input.replace === void 0 ? {} : { replace: input.replace }
2414
3298
  }, MAX_BYTES), header = encodeURIComponent(JSON.stringify(metadata));
2415
- if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid7();
3299
+ if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid10();
2416
3300
  let result2 = await send(path, { method: "POST", headers: {
2417
3301
  "content-type": "application/octet-stream",
2418
3302
  "x-os-enrichment": header
2419
3303
  }, body: bytes.buffer }, "enrichment", context2, signal);
2420
- if (result2.name !== metadata.name) throw unavailable2();
3304
+ if (result2.name !== metadata.name) throw unavailable3();
2421
3305
  return result2;
2422
3306
  }, context);
2423
3307
  },
@@ -2519,30 +3403,30 @@ var AirtableOperationError = class extends Error {
2519
3403
  };
2520
3404
 
2521
3405
  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) {
3406
+ function fail5(message2) {
2523
3407
  throw new AirtableOperationError(message2);
2524
3408
  }
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;
3409
+ function object6(v) {
3410
+ return (!v || typeof v != "object" || Array.isArray(v) || ![null, Object.prototype].includes(Object.getPrototypeOf(v))) && fail5("Invalid Airtable data"), v;
2527
3411
  }
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");
3412
+ function keys4(v, allowed, required = allowed) {
3413
+ (Object.keys(v).some((k) => !allowed.includes(k)) || required.some((k) => !Object.hasOwn(v, k))) && fail5("Invalid Airtable input");
2530
3414
  }
2531
3415
  function text3(v) {
2532
3416
  return typeof v == "string" && v.length > 0 && v.length <= 1024;
2533
3417
  }
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");
3418
+ function fields3(v, nonempty = !1) {
3419
+ let result2 = object6(v);
3420
+ (nonempty && !Object.keys(result2).length || Object.keys(result2).some((k) => !text3(k))) && fail5("Invalid Airtable fields");
2537
3421
  try {
2538
3422
  return serializable(result2);
2539
3423
  } catch {
2540
- return fail2("Invalid Airtable fields");
3424
+ return fail5("Invalid Airtable fields");
2541
3425
  }
2542
3426
  }
2543
3427
  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) };
3428
+ let r = object6(v);
3429
+ 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
3430
  }
2547
3431
  function equal(a, b) {
2548
3432
  if (a === b) return !0;
@@ -2557,7 +3441,7 @@ function createConnections(transport) {
2557
3441
  return { async get() {
2558
3442
  throw new Error("Connection unavailable");
2559
3443
  }, airtable(name2) {
2560
- (typeof name2 != "string" || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(name2)) && fail2("Invalid Airtable connection name");
3444
+ (typeof name2 != "string" || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(name2)) && fail5("Invalid Airtable connection name");
2561
3445
  let call = (operation2, input) => transport(name2, operation2, input);
2562
3446
  return {
2563
3447
  tables: { list: async () => await call("tables.list", {}) },
@@ -2573,12 +3457,12 @@ function createConnections(transport) {
2573
3457
  }
2574
3458
  async function executeAirtableOperation(authority2, operation2, raw, options = {}) {
2575
3459
  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");
3460
+ (!/^[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
3461
  let input;
2578
3462
  try {
2579
- input = object3(serializable(raw));
3463
+ input = object6(serializable(raw));
2580
3464
  } catch {
2581
- return fail2("Invalid Airtable input");
3465
+ return fail5("Invalid Airtable input");
2582
3466
  }
2583
3467
  let mutation = ["records.create", "records.update", "records.delete"].includes(operation2), receipt = (ids2) => ({
2584
3468
  provider: "airtable",
@@ -2588,7 +3472,7 @@ async function executeAirtableOperation(authority2, operation2, raw, options = {
2588
3472
  operation: operation2.slice(8),
2589
3473
  records: ids2.map((id3) => ({ id: id3 }))
2590
3474
  });
2591
- async function request2(path2, init2 = {}, write = !1) {
3475
+ async function request3(path2, init2 = {}, write = !1) {
2592
3476
  let response2;
2593
3477
  try {
2594
3478
  response2 = await (options.fetch ?? fetch)(`https://api.airtable.com/v0/${path2}`, {
@@ -2605,7 +3489,7 @@ async function executeAirtableOperation(authority2, operation2, raw, options = {
2605
3489
  }), new AirtableOperationError("Airtable request rejected", write && (response2.status >= 500 || response2.status === 408 || response2.status < 400) ? "uncertain" : "unapplied");
2606
3490
  try {
2607
3491
  if (!response2.headers.get("content-type")?.toLowerCase().includes("application/json")) throw new Error();
2608
- let value = object3(await response2.json()), safe = serializable(value);
3492
+ let value = object6(await response2.json()), safe = serializable(value);
2609
3493
  if (Object.hasOwn(value, "error") || JSON.stringify(safe).includes(accessToken)) throw new Error();
2610
3494
  return value;
2611
3495
  } catch {
@@ -2613,74 +3497,74 @@ async function executeAirtableOperation(authority2, operation2, raw, options = {
2613
3497
  }
2614
3498
  }
2615
3499
  if (operation2 === "tables.list") {
2616
- keys2(input, []);
3500
+ keys4(input, []);
2617
3501
  let tables = [], seen = /* @__PURE__ */ new Set(), offset;
2618
3502
  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");
3503
+ let query2 = new URLSearchParams(offset ? { offset } : {}), page = await request3(`meta/bases/${baseId}/tables?${query2}`);
3504
+ Array.isArray(page.tables) || fail5("Malformed Airtable tables");
2621
3505
  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");
3506
+ let t = object6(value);
3507
+ (!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
3508
  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) } };
3509
+ let f = object6(value2);
3510
+ 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
3511
  });
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 });
3512
+ (!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
3513
  }
2630
3514
  offset = nextOffset(page.offset, seen);
2631
3515
  } while (offset);
2632
3516
  return tables;
2633
3517
  }
2634
- (!text3(input.table) || input.table === "." || input.table === "..") && fail2("Invalid Airtable table"), mutation && !tableId(input.table) && fail2("Airtable writes require a stable table ID");
3518
+ (!text3(input.table) || input.table === "." || input.table === "..") && fail5("Invalid Airtable table"), mutation && !tableId(input.table) && fail5("Airtable writes require a stable table ID");
2635
3519
  let path = `${baseId}/${encodeURIComponent(input.table)}`;
2636
3520
  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;
3521
+ keys4(input, ["table", "id"]), recordId(input.id) || fail5("Invalid Airtable record ID");
3522
+ let result3 = record2(await request3(`${path}/${input.id}`));
3523
+ return result3.id !== input.id && fail5("Malformed Airtable record"), result3;
2640
3524
  }
2641
3525
  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");
3526
+ 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
3527
  let records2 = [], ids2 = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set(), offset;
2644
3528
  do {
2645
3529
  let query2 = new URLSearchParams();
2646
3530
  for (let field of input.fields ?? []) query2.append("fields[]", field);
2647
3531
  offset && query2.set("offset", offset);
2648
- let page = await request2(`${path}?${query2}`);
2649
- Array.isArray(page.records) || fail2("Malformed Airtable records");
3532
+ let page = await request3(`${path}?${query2}`);
3533
+ Array.isArray(page.records) || fail5("Malformed Airtable records");
2650
3534
  for (let value of page.records) {
2651
3535
  let r = record2(value);
2652
- ids2.has(r.id) && fail2("Malformed Airtable pagination"), ids2.add(r.id), records2.push(r);
3536
+ ids2.has(r.id) && fail5("Malformed Airtable pagination"), ids2.add(r.id), records2.push(r);
2653
3537
  }
2654
3538
  offset = nextOffset(page.offset, seen);
2655
3539
  } while (offset);
2656
3540
  return records2;
2657
3541
  }
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");
3542
+ 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
3543
  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 } : {} };
3544
+ let r = object6(value);
3545
+ if (keys4(r, kind === "create" ? ["fields"] : kind === "update" ? ["id", "expected", "set"] : ["id", "expected"]), kind === "create") return { fields: fields3(r.fields, !0) };
3546
+ (!recordId(r.id) || ids.has(r.id)) && fail5("Invalid Airtable batch record ID"), ids.add(r.id);
3547
+ let set = kind === "update" ? fields3(r.set, !0) : void 0;
3548
+ 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
3549
  });
2666
3550
  for (let r of records) {
2667
3551
  if (!("id" in r)) continue;
2668
- let current2 = record2(await request2(`${path}/${r.id}`));
2669
- current2.id !== r.id && fail2("Malformed Airtable record");
3552
+ let current2 = record2(await request3(`${path}/${r.id}`));
3553
+ current2.id !== r.id && fail5("Malformed Airtable record");
2670
3554
  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");
3555
+ (value === null ? Object.hasOwn(current2.fields, key) : !Object.hasOwn(current2.fields, key) || !equal(current2.fields[key], value)) && fail5("Airtable reviewed values are stale");
2672
3556
  }
2673
3557
  await options.beforeMutation?.();
2674
3558
  let query = new URLSearchParams();
2675
3559
  if (kind === "delete") for (let id3 of ids) query.append("records[]", id3);
2676
- let result2 = await request2(`${path}${kind === "delete" ? `?${query}` : ""}`, {
3560
+ let result2 = await request3(`${path}${kind === "delete" ? `?${query}` : ""}`, {
2677
3561
  method: kind === "create" ? "POST" : kind === "update" ? "PATCH" : "DELETE",
2678
3562
  ...kind === "delete" ? {} : { body: JSON.stringify({ records: records.map((r) => "id" in r ? { id: r.id, fields: r.set } : r) }) }
2679
3563
  }, !0), acknowledged = [], returned = [];
2680
3564
  try {
2681
3565
  if (!Array.isArray(result2.records)) throw new Error();
2682
3566
  for (let value of result2.records) {
2683
- let r = object3(value);
3567
+ let r = object6(value);
2684
3568
  if (!recordId(r.id) || acknowledged.includes(r.id) || kind !== "create" && !ids.has(r.id) || kind === "delete" && r.deleted !== !0) throw new Error();
2685
3569
  acknowledged.push(r.id), kind !== "delete" && returned.push(record2(r));
2686
3570
  }
@@ -2696,7 +3580,7 @@ async function executeAirtableOperation(authority2, operation2, raw, options = {
2696
3580
  }
2697
3581
  function nextOffset(value, seen) {
2698
3582
  if (value !== void 0)
2699
- return (!text3(value) || seen.has(value)) && fail2("Malformed Airtable pagination"), seen.add(value), value;
3583
+ return (!text3(value) || seen.has(value)) && fail5("Malformed Airtable pagination"), seen.add(value), value;
2700
3584
  }
2701
3585
 
2702
3586
  var MANAGED_CONNECTION_CAPABILITY_ENV = "OS_MANAGED_CONNECTION_CAPABILITY";
@@ -2941,8 +3825,8 @@ var InboxOperationError = class extends Error {
2941
3825
  reason;
2942
3826
  };
2943
3827
  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 }) : {};
3828
+ let state = object7(value);
3829
+ return keys5(state, ["unavailableReason"], []), "unavailableReason" in state ? (assert(!available && state.unavailableReason === "handler_unavailable"), { unavailableReason: state.unavailableReason }) : {};
2946
3830
  }
2947
3831
  function questionAvailability(value, available = !1) {
2948
3832
  return parseQuestionAvailability({
@@ -2951,9 +3835,9 @@ function questionAvailability(value, available = !1) {
2951
3835
  }
2952
3836
  function parseInboxUnavailableFailure(value, status) {
2953
3837
  try {
2954
- let envelope = object4(value);
3838
+ let envelope = object7(value);
2955
3839
  if (status === 409) {
2956
- keys3(envelope, ["error"]);
3840
+ keys5(envelope, ["error"]);
2957
3841
  for (let reason of ["action_processing", "action_failed"]) {
2958
3842
  let error = new InboxOperationError(409, reason);
2959
3843
  if (envelope.error === error.message) return error;
@@ -2961,7 +3845,7 @@ function parseInboxUnavailableFailure(value, status) {
2961
3845
  return;
2962
3846
  }
2963
3847
  if (status !== 503) return;
2964
- keys3(envelope, ["error", "unavailableReason"], ["error", "unavailableReason"]), assert(text4(envelope.error));
3848
+ keys5(envelope, ["error", "unavailableReason"], ["error", "unavailableReason"]), assert(text4(envelope.error));
2965
3849
  let state = questionAvailability(envelope);
2966
3850
  return new InboxOperationError(503, state.unavailableReason);
2967
3851
  } catch {
@@ -2990,13 +3874,13 @@ var operations = {
2990
3874
  function assert(value) {
2991
3875
  if (!value) throw new Error("Invalid Inbox result");
2992
3876
  }
2993
- function object4(value) {
3877
+ function object7(value) {
2994
3878
  return assert(value && typeof value == "object" && !Array.isArray(value) && [Object.prototype, null].includes(Object.getPrototypeOf(value)) && Reflect.ownKeys(value).every((key) => {
2995
3879
  let descriptor = typeof key == "string" ? Object.getOwnPropertyDescriptor(value, key) : void 0;
2996
3880
  return !!descriptor?.enumerable && "value" in descriptor;
2997
3881
  })), value;
2998
3882
  }
2999
- function keys3(value, allowed, required = allowed) {
3883
+ function keys5(value, allowed, required = allowed) {
3000
3884
  assert(Object.keys(value).every((key) => allowed.includes(key)) && required.every((key) => Object.hasOwn(value, key)));
3001
3885
  }
3002
3886
  function text4(value, empty2 = !1) {
@@ -3024,65 +3908,65 @@ function json(value, ancestors = /* @__PURE__ */ new Set()) {
3024
3908
  if (value === null || typeof value == "boolean" || typeof value == "string" || typeof value == "number" && Number.isFinite(value)) return value;
3025
3909
  assert(value && typeof value == "object" && !ancestors.has(value)), ancestors.add(value);
3026
3910
  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)]));
3911
+ 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
3912
  } finally {
3029
3913
  ancestors.delete(value);
3030
3914
  }
3031
3915
  }
3032
3916
  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;
3917
+ let record4 = object7(value);
3918
+ 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
3919
  }
3036
3920
  function responseDefinition(value) {
3037
- let definition = object4(value);
3038
- keys3(definition, ["type", "source"]), assert(definition.type === "selection");
3039
- let source2 = object4(definition.source);
3921
+ let definition = object7(value);
3922
+ keys5(definition, ["type", "source"]), assert(definition.type === "selection");
3923
+ let source2 = object7(definition.source);
3040
3924
  if (source2.type === "authored") {
3041
- keys3(source2, ["type", "options", "suggestions", "search"], ["type", "options"]);
3925
+ keys5(source2, ["type", "options", "suggestions", "search"], ["type", "options"]);
3042
3926
  let options = array2(source2.options);
3043
3927
  assert(options.length > 0);
3044
3928
  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));
3929
+ let option = object7(value2);
3930
+ 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) {
3931
+ let note = object7(option.note);
3932
+ keys5(note, ["placeholder"]), assert(text4(note.placeholder));
3049
3933
  }
3050
3934
  return option.value;
3051
3935
  });
3052
3936
  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));
3937
+ let search = object7(source2.search);
3938
+ keys5(search, ["triggerLabel", "placeholder", "emptyLabel"]), assert(text4(search.triggerLabel) && text4(search.placeholder) && text4(search.emptyLabel));
3055
3939
  let suggestions2 = array2(source2.suggestions);
3056
3940
  assert(suggestions2.length <= 8 && suggestions2.every((value2) => text4(value2) && values.includes(value2)) && new Set(suggestions2).size === suggestions2.length);
3057
3941
  } else assert(options.length <= 9);
3058
3942
  return;
3059
3943
  }
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 ?? {});
3944
+ assert(source2.type === "records"), keys5(source2, ["type", "collection", "refPrefix", "where", "display", "suggestions"], ["type", "collection", "display"]);
3945
+ let collection = object7(source2.collection);
3946
+ 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));
3947
+ let where = object7(source2.where ?? {});
3064
3948
  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"]);
3949
+ let display = object7(source2.display);
3950
+ keys5(display, ["labelFields"]);
3067
3951
  let labels = array2(display.labelFields);
3068
3952
  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
3953
  let suggestions = array2(source2.suggestions ?? []), refs = suggestions.map((value2) => {
3070
- let suggestion = object4(value2);
3071
- keys3(suggestion, ["record", "reason"], ["record"]);
3954
+ let suggestion = object7(value2);
3955
+ keys5(suggestion, ["record", "reason"], ["record"]);
3072
3956
  let record4 = recordReference(suggestion.record);
3073
3957
  return assert(record4.repository === collection.repository), "reason" in suggestion && assert(text4(suggestion.reason)), record4.ref;
3074
3958
  });
3075
3959
  assert(suggestions.length <= 8 && new Set(refs).size === refs.length);
3076
3960
  }
3077
3961
  function response(value) {
3078
- let answer = object4(value);
3962
+ let answer = object7(value);
3079
3963
  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
3964
  }
3081
3965
  function parseInboxRequest(value) {
3082
3966
  try {
3083
- let envelope = object4(value);
3967
+ let envelope = object7(value);
3084
3968
  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];
3969
+ let operation2 = envelope.operation, input = { ...object7(envelope.input) }, required = operations[operation2];
3086
3970
  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
3971
  for (let key of ["itemId", "personId", "fileId"]) key in input && assert(id2(input[key]));
3088
3972
  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 +3975,54 @@ function parseInboxRequest(value) {
3091
3975
  }
3092
3976
  }
3093
3977
  function parseInboxCurrent(value) {
3094
- let current2 = object4(value), workspace = object4(current2.workspace), viewer = object4(current2.viewer);
3978
+ let current2 = object7(value), workspace = object7(current2.workspace), viewer = object7(current2.viewer);
3095
3979
  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
3980
  workspace: { id: workspace.id, slug: workspace.slug, name: workspace.name, locale: workspace.locale, timezone: workspace.timezone },
3097
3981
  viewer: { id: viewer.id, name: viewer.name, email: viewer.email }
3098
3982
  };
3099
3983
  }
3100
3984
  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);
3985
+ let item = object7(json(value));
3986
+ 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) => {
3987
+ let view = object7(value2);
3104
3988
  assert(text4(view.id) && text4(view.view) && text4(view.implementation)), json(view.input);
3105
3989
  }), array2(item.people).forEach((value2) => {
3106
- let person = object4(value2);
3990
+ let person = object7(value2);
3107
3991
  assert(id2(person.id) && text4(person.name));
3108
3992
  }), array2(item.questions).forEach((value2) => {
3109
- let question2 = object4(value2);
3993
+ let question2 = object7(value2);
3110
3994
  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);
3995
+ let accepted = object7(question2.acceptedResponse);
3112
3996
  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
3997
  }
3114
3998
  if (question2.execution !== null) {
3115
- let execution = object4(question2.execution);
3999
+ let execution = object7(question2.execution);
3116
4000
  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);
4001
+ let consequence = object7(execution.consequence);
3118
4002
  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);
4003
+ let receipt = object7(value3);
3120
4004
  assert(text4(receipt.repository) && text4(receipt.commit) && text4(receipt.diff, !0));
3121
4005
  });
3122
4006
  }
3123
4007
  }
3124
4008
  }), array2(item.linkedAsks).forEach((value2) => {
3125
- let linked = object4(value2);
4009
+ let linked = object7(value2);
3126
4010
  if (assert(id2(linked.id)), linked.state === "unavailable") assert(typeof linked.done == "boolean");
3127
4011
  else if (assert(["yours", "done", "open", "theirs"].includes(String(linked.state)) && text4(linked.title)), linked.state === "theirs") {
3128
- let assignee = object4(linked.assignee);
4012
+ let assignee = object7(linked.assignee);
3129
4013
  assert(id2(assignee.id) && text4(assignee.name));
3130
4014
  }
3131
4015
  }), 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);
4016
+ let event = object7(value2);
4017
+ 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
4018
  }), array2(item.work).forEach((value2) => {
3135
- let work = object4(value2);
4019
+ let work = object7(value2);
3136
4020
  assert(id2(work.id) && text4(work.questionId) && text4(work.reason) && optionalDate(work.settledAt));
3137
4021
  }), item;
3138
4022
  }
3139
4023
  function parseAnswerableQuestion(value) {
3140
- let entry = object4(json(value));
3141
- keys3(
4024
+ let entry = object7(json(value));
4025
+ keys5(
3142
4026
  entry,
3143
4027
  ["itemId", "number", "revision", "title", "inboxUrl", "questionId", "routine", "prompt", "response", "answerable", "tags", "recordRefs", "instructions", "unavailableReason"],
3144
4028
  ["itemId", "number", "revision", "title", "inboxUrl", "questionId", "routine", "prompt", "response", "answerable"]
@@ -3151,29 +4035,29 @@ function askMetadata(entry) {
3151
4035
  assert(tags.length <= 32 && tags.every((tag) => text4(tag) && new TextEncoder().encode(tag).byteLength <= 64)), assert(new Set(tags).size === tags.length);
3152
4036
  let refs = array2(entry.recordRefs === void 0 ? [] : entry.recordRefs);
3153
4037
  refs.forEach((value) => {
3154
- let ref = object4(value);
3155
- keys3(ref, ["repository", "id"]), recordReference({ repository: ref.repository, ref: ref.id });
4038
+ let ref = object7(value);
4039
+ keys5(ref, ["repository", "id"]), recordReference({ repository: ref.repository, ref: ref.id });
3156
4040
  }), assert(new Set(refs.map((value) => {
3157
- let ref = object4(value);
4041
+ let ref = object7(value);
3158
4042
  return JSON.stringify([ref.repository, ref.id]);
3159
4043
  })).size === refs.length), entry.tags = tags, entry.recordRefs = refs;
3160
4044
  }
3161
4045
  function parseInboxAcceptance(value) {
3162
- let accepted = object4(value);
4046
+ let accepted = object7(value);
3163
4047
  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
4048
  }
3165
4049
  function parseInboxResult(operation2, value) {
3166
4050
  if (operation2 === "current") return parseInboxCurrent(value);
3167
4051
  if (operation2 === "questions.list") {
3168
- let page = object4(value);
3169
- keys3(page, ["questions", "nextBeforeNumber"]);
4052
+ let page = object7(value);
4053
+ keys5(page, ["questions", "nextBeforeNumber"]);
3170
4054
  let questions = array2(page.questions).map(parseAnswerableQuestion);
3171
4055
  return assert(page.nextBeforeNumber === null || integer(page.nextBeforeNumber)), { questions, nextBeforeNumber: page.nextBeforeNumber };
3172
4056
  }
3173
4057
  if (operation2 === "items.readRecords") return parseInboxRecords(value);
3174
4058
  if (operation2 === "items.read") return parseInboxItem(value);
3175
4059
  if (operation2 === "items.list") {
3176
- let page = object4(value), items = array2(page.items).map(parseInboxItem);
4060
+ let page = object7(value), items = array2(page.items).map(parseInboxItem);
3177
4061
  return assert(items.length <= 100 && (page.nextBeforeNumber === null || integer(page.nextBeforeNumber))), { items, nextBeforeNumber: page.nextBeforeNumber };
3178
4062
  }
3179
4063
  if (operation2 === "items.see") {
@@ -3181,30 +4065,30 @@ function parseInboxResult(operation2, value) {
3181
4065
  return;
3182
4066
  }
3183
4067
  if (operation2 === "items.markDigestRead") {
3184
- let read2 = object4(value);
4068
+ let read2 = object7(value);
3185
4069
  return assert(integer(read2.activityId) && date(read2.readAt)), read2;
3186
4070
  }
3187
4071
  if (operation2 === "items.rename" || operation2 === "items.setLifecycle") {
3188
- let update = object4(value), item = parseInboxItem(update.item);
4072
+ let update = object7(value), item = parseInboxItem(update.item);
3189
4073
  return assert((update.activityId === null || integer(update.activityId)) && optionalDate(update.changedAt)), { ...update, item };
3190
4074
  }
3191
4075
  if (operation2 === "items.listRecipientCandidates") {
3192
4076
  let candidates = array2(value);
3193
4077
  return candidates.forEach((value2) => {
3194
- let person = object4(value2);
4078
+ let person = object7(value2);
3195
4079
  assert(id2(person.id) && text4(person.name) && text4(person.email));
3196
- }), assert(new Set(candidates.map((value2) => object4(value2).id)).size === candidates.length), candidates;
4080
+ }), assert(new Set(candidates.map((value2) => object7(value2).id)).size === candidates.length), candidates;
3197
4081
  }
3198
4082
  if (operation2 === "items.addRecipient") {
3199
- let addition = object4(value), item = parseInboxItem(addition.item);
4083
+ let addition = object7(value), item = parseInboxItem(addition.item);
3200
4084
  return assert(id2(addition.addedPersonId) && item.people.some((person) => person.id === addition.addedPersonId)), { ...addition, item };
3201
4085
  }
3202
4086
  if (operation2 === "questions.answer") return parseInboxAcceptance(value);
3203
4087
  if (operation2 === "questions.searchRecords") {
3204
- let result2 = object4(value);
4088
+ let result2 = object7(value);
3205
4089
  assert(text4(result2.recordType) && integer(result2.eligibleCount, 0) && integer(result2.matchCount, 0) && Number(result2.matchCount) <= Number(result2.eligibleCount));
3206
4090
  let labeled = (value2) => {
3207
- let record4 = object4(value2);
4091
+ let record4 = object7(value2);
3208
4092
  recordReference({ repository: record4.repository, ref: record4.ref }), assert(text4(record4.label)), "reason" in record4 && assert(text4(record4.reason));
3209
4093
  };
3210
4094
  return array2(result2.matches).forEach(labeled), array2(result2.suggestions).forEach(labeled), "selected" in result2 && labeled(result2.selected), result2;
@@ -3212,9 +4096,9 @@ function parseInboxResult(operation2, value) {
3212
4096
  throw new Error("File content is not a JSON result");
3213
4097
  }
3214
4098
 
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(() => {
4099
+ async function limitedBody(request3, limit, timeoutMs) {
4100
+ if (!request3.body) return new Uint8Array();
4101
+ let reader = request3.body.getReader(), expired = !1, timer = timeoutMs === void 0 ? void 0 : setTimeout(() => {
3218
4102
  expired = !0, reader.cancel().catch(() => {
3219
4103
  });
3220
4104
  }, timeoutMs), chunks = [], length = 0;
@@ -3573,16 +4457,16 @@ function appContext(origin, active2, changed) {
3573
4457
  return requestChecked(`routines/${encodeURIComponent(key)}/${suffix}`, { signal }, !1, !0);
3574
4458
  }
3575
4459
  async function requestFiles(suffix, init2, parent) {
3576
- let unavailable5 = () => new FileOperationError("unsupported_context", 400);
4460
+ let unavailable6 = () => new FileOperationError("unsupported_context", 400);
3577
4461
  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();
4462
+ throw unavailable6();
4463
+ let admitted = credential, signal = parent ? AbortSignal.any([access.signal, parent]) : access.signal, failure = () => current2() && !signal.aborted ? new FileOperationError("unavailable", 503, !0) : unavailable6();
3580
4464
  try {
3581
- return await hostedContent("", init2, signal, (_url, request2) => untilAborted(
3582
- send3(`files${suffix}`, admitted, signal, request2).then((value) => {
4465
+ return await hostedContent("", init2, signal, (_url, request3) => untilAborted(
4466
+ send3(`files${suffix}`, admitted, signal, request3).then((value) => {
3583
4467
  if (signal.aborted)
3584
4468
  throw value.body?.cancel().catch(() => {
3585
- }), unavailable5();
4469
+ }), unavailable6();
3586
4470
  return value;
3587
4471
  }),
3588
4472
  signal
@@ -3741,9 +4625,9 @@ var WorkspaceAccessError = class extends Error {
3741
4625
  status;
3742
4626
  };
3743
4627
 
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();
4628
+ 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
4629
  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();
4630
+ 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
4631
  }
3748
4632
  async function send2(operation2, input, resolved) {
3749
4633
  let envelope = parseInboxRequest({ operation: operation2, input }), context;
@@ -3763,11 +4647,11 @@ async function send2(operation2, input, resolved) {
3763
4647
  [400, 401, 403, 409].includes(response2.status) ? response2.status : 503,
3764
4648
  response2.status === 400 ? "invalid_input" : response2.status === 401 ? "authority_unavailable" : response2.status === 403 ? "access_denied" : response2.status === 409 ? "conflict" : "unavailable"
3765
4649
  );
3766
- if (response2.status !== 200) throw unavailable3();
4650
+ if (response2.status !== 200) throw unavailable4();
3767
4651
  let parsed = parseInboxResult(operation2, value);
3768
4652
  return check2(), parsed;
3769
4653
  } catch (error) {
3770
- throw check2(), error instanceof InboxOperationError ? error : unavailable3();
4654
+ throw check2(), error instanceof InboxOperationError ? error : unavailable4();
3771
4655
  }
3772
4656
  }
3773
4657
  if (context.endpoint !== `https://${context.workspace}.oddington.ai` || ["auth", "www", "api", "os"].includes(context.workspace)) throw stale();
@@ -3778,7 +4662,7 @@ async function send2(operation2, input, resolved) {
3778
4662
  } catch (error) {
3779
4663
  throw hostFailure(error, context);
3780
4664
  }
3781
- if (!host) throw unavailable3();
4665
+ if (!host) throw unavailable4();
3782
4666
  }
3783
4667
  let check = () => {
3784
4668
  if (!context.isCurrent() || host && !host.isCurrent() || !Number.isFinite(context.expiresAt) || context.expiresAt <= Date.now()) throw stale();
@@ -3816,18 +4700,18 @@ async function send2(operation2, input, resolved) {
3816
4700
  }
3817
4701
  if (response2.status !== 200)
3818
4702
  throw response2.body?.cancel().catch(() => {
3819
- }), unavailable3();
4703
+ }), unavailable4();
3820
4704
  let bytes = await limitedBody(response2, INBOX_RESULT_BYTES);
3821
- if (check(), !bytes) throw unavailable3();
4705
+ if (check(), !bytes) throw unavailable4();
3822
4706
  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();
4707
+ if (check(), operation2 === "current" && parsed.workspace.slug !== context.workspace) throw unavailable4();
3824
4708
  if ("itemId" in envelope.input) {
3825
4709
  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();
4710
+ 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
4711
  }
3828
4712
  return parsed;
3829
4713
  } catch (error) {
3830
- throw check(), error instanceof InboxOperationError ? error : unavailable3();
4714
+ throw check(), error instanceof InboxOperationError ? error : unavailable4();
3831
4715
  }
3832
4716
  }
3833
4717
  var inbox = {
@@ -3847,14 +4731,14 @@ var inbox = {
3847
4731
  throw hostFailure(error, initial);
3848
4732
  }
3849
4733
  if (initial.kind === "local") throw new InboxOperationError(403, "access_denied");
3850
- if (!host) throw unavailable3();
4734
+ if (!host) throw unavailable4();
3851
4735
  let check = () => {
3852
4736
  if (!initial.isCurrent() || !host.isCurrent() || initial.expiresAt <= Date.now()) throw stale();
3853
4737
  };
3854
4738
  do {
3855
4739
  check();
3856
4740
  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();
4741
+ if (check(), beforeNumber !== void 0 && (page.items.some((item) => item.number >= beforeNumber) || page.nextBeforeNumber !== null && page.nextBeforeNumber >= beforeNumber)) throw unavailable4();
3858
4742
  if (items.push(...page.items), page.nextBeforeNumber === null) return items;
3859
4743
  beforeNumber = page.nextBeforeNumber;
3860
4744
  } while (!0);
@@ -3889,7 +4773,7 @@ var inbox = {
3889
4773
  routines,
3890
4774
  ...beforeNumber === void 0 ? {} : { beforeNumber }
3891
4775
  }, 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();
4776
+ 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
4777
  if (questions.push(...page.questions), page.nextBeforeNumber === null) return questions;
3894
4778
  beforeNumber = page.nextBeforeNumber;
3895
4779
  } while (!0);
@@ -3965,7 +4849,7 @@ function init({ auth: input }) {
3965
4849
  throw new Error("Hosted Data context unavailable.");
3966
4850
  if (person = session.user.id, registered && await registered.checkWorkspaceAccess(), !active2 || globalThis.location.origin !== endpoint || started !== revision || person !== session.user.id)
3967
4851
  throw new Error("Hosted Data context unavailable.");
3968
- let isCurrent = () => active2 && globalThis.location.origin === endpoint && revision === started && person === session.user.id;
4852
+ let isCurrent = () => active2 && globalThis.location.origin === endpoint && revision === started && person === session.user.id && expiresAt > Date.now();
3969
4853
  return {
3970
4854
  workspace,
3971
4855
  endpoint,
@@ -3984,6 +4868,7 @@ function init({ auth: input }) {
3984
4868
  active2 && (active2 = !1, installation.abort(), sharedLocal || local2?.dispose(), revision++, subscription?.unsubscribe(), stopDisposal?.(), uninstall(), installedDispose === dispose && (installedDispose = void 0));
3985
4869
  };
3986
4870
  installedDispose = dispose, stopDisposal = registered?.onDispose(dispose), active2 && (sharedLocal || (subscription = auth2.onAuthStateChange((event, session) => {
4871
+ if (registered && event === "INITIAL_SESSION" && !session) return;
3987
4872
  let next = session?.user.id ?? null;
3988
4873
  (event === "SIGNED_OUT" || person !== void 0 && next !== person || person !== void 0 && event === "SIGNED_IN" && token !== session?.access_token) && (revision++, local2?.invalidate()), person = next, token = session?.access_token;
3989
4874
  }).data.subscription), sharedLocal || local2?.start());
@@ -4094,10 +4979,10 @@ function createLocalBrowserAuth(origin, failure) {
4094
4979
  coordinator.listeners.add(observe);
4095
4980
  let assertActive = () => {
4096
4981
  if (!active2) throw failure("disposed");
4097
- }, unavailable5 = async () => Object.freeze({
4982
+ }, unavailable6 = async () => Object.freeze({
4098
4983
  status: active2 ? "unavailable" : "disposed"
4099
4984
  }), handle2 = Object.freeze({
4100
- authorization: Object.freeze({ get: unavailable5, approve: unavailable5, deny: unavailable5 }),
4985
+ authorization: Object.freeze({ get: unavailable6, approve: unavailable6, deny: unavailable6 }),
4101
4986
  getState() {
4102
4987
  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;
4103
4988
  },
@@ -4177,36 +5062,89 @@ function createBrowserAuth(runtime) {
4177
5062
  }
4178
5063
  }
4179
5064
  function expire(c) {
4180
- !c.active || !c.session && c.state.status === "expired" || (c.revision++, c.timer && clearTimeout(c.timer), c.session = null, publish2(c, { status: "expired" }), notify(c, "SIGNED_OUT"));
5065
+ !c.active || !c.session && c.state.status === "expired" || (c.revision++, c.resolution?.cancel(), c.timer && clearTimeout(c.timer), c.session = null, publish2(c, { status: "expired" }), notify(c, "SIGNED_OUT"));
4181
5066
  }
4182
5067
  function accept(c, event, session) {
4183
- if (!c.active || event === "INITIAL_SESSION" && c.state.status !== "initializing" || event === "TOKEN_REFRESHED" && !c.session && c.state.status !== "initializing") return;
5068
+ if (!c.active || event === "SIGNED_OUT" && c.state.pending === "sign_out" && !c.session || event === "INITIAL_SESSION" && c.state.status !== "initializing" || event === "TOKEN_REFRESHED" && !c.session && c.state.status !== "initializing") return;
4184
5069
  let replaced = c.session?.user?.id !== session?.user?.id || event === "SIGNED_OUT" || !!(event === "SIGNED_IN" && c.session && session?.access_token !== c.session.access_token);
4185
- replaced && c.revision++, c.timer && clearTimeout(c.timer);
5070
+ replaced && (c.revision++, c.resolution?.cancel()), c.timer && clearTimeout(c.timer);
4186
5071
  let pending = c.state.pending;
4187
5072
  if (!session) {
4188
5073
  c.session = null, publish2(c, { status: c.state.status === "expired" ? "expired" : "signed_out", ...pending ? { pending } : {} }), notify(c, "SIGNED_OUT");
4189
5074
  return;
4190
5075
  }
4191
5076
  if (!validSession(session)) {
4192
- c.session = session, expire(c);
5077
+ c.session && !replaced ? (c.session = session, noticeExpiry(c)) : (c.session = null, publish2(c, { status: "unavailable", error: "unavailable" }));
4193
5078
  return;
4194
5079
  }
4195
5080
  c.session = session;
4196
5081
  let email = typeof session.user.email == "string" ? session.user.email.trim() : "", metadata = session.user.user_metadata, name2 = ["name", "full_name", "first_name"].map((key) => metadata?.[key]).find((value) => typeof value == "string" && value.trim())?.trim() || email, account = !replaced && c.state.account?.email === email && c.state.account.displayName === name2 ? c.state.account : Object.freeze({ email, displayName: name2 });
4197
- notify(c, event), publish2(c, { status: "signed_in", account, ...pending ? { pending } : {} });
5082
+ notify(c, event), publish2(c, { status: "signed_in", account, ...pending ? { pending } : {} }), event === "TOKEN_REFRESHED" && c.resolution?.complete();
4198
5083
  let checkExpiry = () => {
4199
5084
  if (!c.active || !c.session) return;
4200
5085
  let remaining = c.session.expires_at * 1e3 - Date.now();
4201
- remaining <= 0 ? expire(c) : c.timer = setTimeout(checkExpiry, Math.min(remaining, 2147483647));
5086
+ remaining <= 0 ? noticeExpiry(c) : c.timer = setTimeout(checkExpiry, Math.min(remaining, 2147483647));
4202
5087
  };
4203
5088
  checkExpiry();
4204
5089
  }
4205
5090
  function validSession(session) {
4206
5091
  return typeof session.access_token == "string" && /^[^\s]{1,8192}$/.test(session.access_token) && typeof session.user?.id == "string" && !!session.user.id && Number.isFinite(session.expires_at) && session.expires_at * 1e3 > Date.now();
4207
5092
  }
5093
+ function noticeExpiry(c) {
5094
+ c.resolution?.checkBound(), c.active && c.session && !validSession(c.session) && c.state.status === "signed_in" && c.state.pending !== "sign_out" && (c.resolution ? publish2(c, { status: "reconnecting", account: c.state.account, pending: c.state.pending }) : resolveSession(c));
5095
+ }
5096
+ function resolveSession(c) {
5097
+ if (c.resolution) return c.resolution.promise;
5098
+ if (!c.active || !c.session || !c.provider || c.state.pending === "sign_out") return Promise.resolve();
5099
+ let revision = c.revision, person = c.session.user.id, controller = new AbortController(), deadline = Date.now() + 15e3, finish, promise = new Promise((resolve) => {
5100
+ finish = resolve;
5101
+ }), resolution2 = { promise, checkBound() {
5102
+ Date.now() >= deadline && fail7();
5103
+ }, complete() {
5104
+ c.resolution === resolution2 && (clearTimeout(timer), c.resolution = void 0, finish());
5105
+ }, cancel() {
5106
+ c.resolution === resolution2 && (resolution2.complete(), controller.abort());
5107
+ } };
5108
+ c.resolution = resolution2;
5109
+ let fail7 = (error) => {
5110
+ if (c.resolution === resolution2) {
5111
+ if (terminalSessionFailure(error)) {
5112
+ expire(c);
5113
+ return;
5114
+ }
5115
+ if (c.session && validSession(c.session)) {
5116
+ resolution2.cancel();
5117
+ return;
5118
+ }
5119
+ c.revision++, resolution2.cancel(), c.timer && clearTimeout(c.timer), publish2(c, { status: "unavailable", account: c.state.account, error: "unavailable" });
5120
+ }
5121
+ }, timer = setTimeout(() => fail7(), 15e3);
5122
+ return validSession(c.session) || publish2(c, { status: "reconnecting", account: c.state.account, pending: c.state.pending }), Promise.resolve().then(async () => {
5123
+ if (c.resolution === resolution2)
5124
+ try {
5125
+ let result2 = await c.provider.getSession(controller.signal);
5126
+ if (c.resolution !== resolution2) return;
5127
+ if (!current2(c, c.origin, revision)) {
5128
+ resolution2.cancel();
5129
+ return;
5130
+ }
5131
+ if (result2.error) {
5132
+ fail7(result2.error);
5133
+ return;
5134
+ }
5135
+ if (!result2.data.session || !validSession(result2.data.session)) {
5136
+ fail7();
5137
+ return;
5138
+ }
5139
+ accept(c, result2.data.session.user.id === person ? "TOKEN_REFRESHED" : "SIGNED_IN", result2.data.session), resolution2.complete();
5140
+ } catch (error) {
5141
+ fail7(error);
5142
+ }
5143
+ }), promise;
5144
+ }
4208
5145
  function createCoordinator(origin) {
4209
5146
  let c = {
5147
+ origin,
4210
5148
  state: Object.freeze({ status: "initializing" }),
4211
5149
  session: null,
4212
5150
  revision: 0,
@@ -4230,7 +5168,8 @@ function createBrowserAuth(runtime) {
4230
5168
  revision: () => c.revision,
4231
5169
  current: (revision2) => current2(c, origin, revision2),
4232
5170
  canPersistSession: () => c.active && (c.state.status === "initializing" || !!c.session || c.state.pending === "verify_code"),
4233
- canAuthorize: (accessToken) => current2(c, origin, c.revision) && !!c.session && c.session.access_token === accessToken && c.state.pending !== "sign_out"
5171
+ canRefresh: (userId) => c.state.status === "initializing" || !!c.session && c.session.user.id === userId && c.state.pending !== "sign_out",
5172
+ canAuthorize: (accessToken) => current2(c, origin, c.revision) && !!c.session && validSession(c.session) && c.session.access_token === accessToken && c.state.pending !== "sign_out"
4234
5173
  }), !c.active || globalThis.location?.origin !== origin) {
4235
5174
  c.provider.dispose();
4236
5175
  return;
@@ -4247,13 +5186,16 @@ function createBrowserAuth(runtime) {
4247
5186
  }
4248
5187
  })(), c;
4249
5188
  }
5189
+ async function ready(c) {
5190
+ (!c.provider || c.state.status === "initializing") && await c.ready;
5191
+ }
4250
5192
  function current2(c, origin, revision) {
4251
- return c.session && !validSession(c.session) && expire(c), c.active && c.revision === revision && globalThis.location?.origin === origin;
5193
+ return noticeExpiry(c), c.active && c.revision === revision && globalThis.location?.origin === origin;
4252
5194
  }
4253
5195
  async function checkWorkspaceAccess(c, origin) {
4254
5196
  if (origin === "https://auth.oddington.ai" || origin === "http://127.0.0.1:5176") return;
4255
5197
  let revision = c.revision;
4256
- if (!current2(c, origin, revision) || !c.session || c.state.pending === "sign_out") throw runtime.failure("stale");
5198
+ if (!current2(c, origin, revision) || !c.session || !validSession(c.session) || c.state.pending === "sign_out") throw runtime.failure("stale");
4257
5199
  if (c.workspaceAccess?.revision !== revision) {
4258
5200
  let token = c.session.access_token, result2 = (async () => {
4259
5201
  let status;
@@ -4301,13 +5243,13 @@ function createBrowserAuth(runtime) {
4301
5243
  };
4302
5244
  async function action(kind, work) {
4303
5245
  if (assertActive(), coordinator.action && kind !== "sign_out" || kind === "sign_out" && coordinator.state.pending === "sign_out") throw runtime.failure("busy");
4304
- kind === "sign_out" && (coordinator.revision++, notify(coordinator, "SIGNED_OUT"));
5246
+ kind === "sign_out" && (coordinator.revision++, coordinator.resolution?.cancel(), coordinator.timer && clearTimeout(coordinator.timer), coordinator.session = null, publish2(coordinator, { status: "signed_out", pending: "sign_out" }), notify(coordinator, "SIGNED_OUT"));
4305
5247
  let marker = {};
4306
5248
  coordinator.action = marker, ownedAction = marker;
4307
5249
  let revision = coordinator.revision;
4308
5250
  publish2(coordinator, { ...coordinator.state, error: void 0, pending: kind });
4309
5251
  try {
4310
- if (await coordinator.ready, assertActive(), !coordinator.provider || !coordinator.active || globalThis.location?.origin !== origin) throw runtime.failure("unavailable");
5252
+ if (await ready(coordinator), assertActive(), !coordinator.provider || !coordinator.active || globalThis.location?.origin !== origin) throw runtime.failure("unavailable");
4311
5253
  if (!current2(coordinator, origin, revision) || coordinator.action !== marker || (await work(coordinator.provider), assertActive(), coordinator.action !== marker) || !current2(coordinator, origin, revision) && kind !== "verify_code" && kind !== "sign_out") throw runtime.failure("stale");
4312
5254
  } catch (error) {
4313
5255
  let reason = active2 ? current2(coordinator, origin, revision) ? safeReason(error) ?? "unavailable" : "stale" : "disposed";
@@ -4321,18 +5263,20 @@ function createBrowserAuth(runtime) {
4321
5263
  if (id3 !== authorizationId && (authorizationId = id3, authorizationGeneration++, inspected = void 0), !id3) return Object.freeze({ status: "missing" });
4322
5264
  if (typeof id3 != "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(id3)) return Object.freeze({ status: "invalid" });
4323
5265
  let generation = authorizationGeneration;
4324
- if (await coordinator.ready, !active2) return Object.freeze({ status: "disposed" });
5266
+ if (await ready(coordinator), !active2) return Object.freeze({ status: "disposed" });
4325
5267
  if (generation !== authorizationGeneration) return Object.freeze({ status: "stale" });
4326
5268
  let revision = coordinator.revision;
4327
5269
  if (!current2(coordinator, origin, revision)) return Object.freeze({ status: "stale" });
4328
5270
  if (!coordinator.session || coordinator.state.pending === "sign_out") return Object.freeze({ status: coordinator.state.status === "expired" ? "expired" : coordinator.state.status === "unavailable" ? "unavailable" : "signed_out" });
5271
+ if (!validSession(coordinator.session)) return Object.freeze({ status: "unavailable" });
5272
+ let expiresAt = coordinator.session.expires_at * 1e3;
4329
5273
  if (!coordinator.authorization || !coordinator.provider) return Object.freeze({ status: "unavailable" });
4330
5274
  if (coordinator.action) return Object.freeze({ status: "busy" });
4331
5275
  if (kind !== "get" && (!inspected || inspected.id !== id3 || inspected.revision !== revision)) return Object.freeze({ status: "stale" });
4332
5276
  if (kind !== "get" && inspected?.result.status !== "consent") return inspected.result;
4333
5277
  let marker = {};
4334
5278
  coordinator.action = marker, ownedAction = marker;
4335
- let requestCurrent = () => active2 && generation === authorizationGeneration && current2(coordinator, origin, revision) && coordinator.action === marker && !!coordinator.session && coordinator.state.pending !== "sign_out", stale2 = () => Object.freeze({ status: active2 ? "stale" : "disposed" });
5279
+ let requestCurrent = () => active2 && generation === authorizationGeneration && current2(coordinator, origin, revision) && coordinator.action === marker && !!coordinator.session && validSession(coordinator.session) && expiresAt > Date.now() && coordinator.state.pending !== "sign_out", stale2 = () => Object.freeze({ status: active2 ? "stale" : "disposed" });
4336
5280
  try {
4337
5281
  let provider2 = coordinator.provider, response2 = await provider2.authorization.get(id3, requestCurrent);
4338
5282
  if (!requestCurrent()) return stale2();
@@ -4361,7 +5305,7 @@ function createBrowserAuth(runtime) {
4361
5305
  deny: (id3) => authorize("deny", id3)
4362
5306
  }),
4363
5307
  getState() {
4364
- return active2 && coordinator.session && !validSession(coordinator.session) && expire(coordinator), lastState;
5308
+ return active2 && noticeExpiry(coordinator), lastState;
4365
5309
  },
4366
5310
  subscribe(listener) {
4367
5311
  return assertActive(), observers.add(listener), () => {
@@ -4410,13 +5354,13 @@ function createBrowserAuth(runtime) {
4410
5354
  }
4411
5355
  disposalObservers.clear();
4412
5356
  for (let listener of sessionObservers) coordinator.sessions.delete(listener);
4413
- sessionObservers.clear(), --coordinator.refs === 0 && (coordinator.active = !1, coordinator.revision++, coordinator.timer && clearTimeout(coordinator.timer), coordinator.unsubscribe?.(), coordinator.provider?.dispose(), coordinator.provider = void 0, coordinator.session = null, coordinator.listeners.clear(), coordinator.sessions.clear(), coordinators2.delete(origin));
5357
+ sessionObservers.clear(), --coordinator.refs === 0 && (coordinator.active = !1, coordinator.revision++, coordinator.resolution?.cancel(), coordinator.timer && clearTimeout(coordinator.timer), coordinator.unsubscribe?.(), coordinator.provider?.dispose(), coordinator.provider = void 0, coordinator.session = null, coordinator.listeners.clear(), coordinator.sessions.clear(), coordinators2.delete(origin));
4414
5358
  }
4415
5359
  }
4416
5360
  });
4417
5361
  return registerBrowserAuth(handle2, {
4418
5362
  async ready() {
4419
- assertActive(), await coordinator.ready, assertActive();
5363
+ assertActive(), await ready(coordinator), assertActive();
4420
5364
  },
4421
5365
  async checkWorkspaceAccess() {
4422
5366
  assertActive(), await checkWorkspaceAccess(coordinator, origin), assertActive();
@@ -4428,23 +5372,16 @@ function createBrowserAuth(runtime) {
4428
5372
  });
4429
5373
  },
4430
5374
  async getSession() {
4431
- assertActive(), await coordinator.ready, assertActive();
5375
+ assertActive(), await ready(coordinator), assertActive();
4432
5376
  let revision = coordinator.revision;
4433
- if (!current2(coordinator, origin, revision) || !coordinator.provider || !coordinator.session || coordinator.state.pending === "sign_out") return { data: { session: null }, error: null };
4434
- let result2;
4435
- try {
4436
- result2 = await coordinator.provider.getSession();
4437
- } catch {
4438
- result2 = { data: { session: null }, error: runtime.failure("unavailable") };
4439
- }
4440
- return !active2 || !current2(coordinator, origin, revision) ? { data: { session: null }, error: runtime.failure("stale") } : result2.error ? !terminalSessionFailure(result2.error) && coordinator.session && validSession(coordinator.session) ? { data: { session: coordinator.session }, error: null } : (expire(coordinator), { data: { session: null }, error: runtime.failure("unavailable") }) : (accept(coordinator, "TOKEN_REFRESHED", result2.data.session), { data: { session: coordinator.session }, error: null });
5377
+ return !current2(coordinator, origin, revision) || !coordinator.provider || !coordinator.session || coordinator.state.pending === "sign_out" ? { data: { session: null }, error: null } : (await resolveSession(coordinator), active2 ? !current2(coordinator, origin, revision) || !coordinator.session || !validSession(coordinator.session) ? { data: { session: null }, error: runtime.failure("unavailable") } : { data: { session: coordinator.session }, error: null } : { data: { session: null }, error: runtime.failure("disposed") });
4441
5378
  },
4442
5379
  onAuthStateChange(callback) {
4443
5380
  if (!active2)
4444
5381
  return callback("SIGNED_OUT", null), { data: { subscription: { unsubscribe() {
4445
5382
  } } } };
4446
5383
  let listener = (event, session) => callback(event, session);
4447
- return coordinator.sessions.add(listener), sessionObservers.add(listener), callback("INITIAL_SESSION", coordinator.session), { data: { subscription: { unsubscribe() {
5384
+ return coordinator.sessions.add(listener), sessionObservers.add(listener), callback("INITIAL_SESSION", coordinator.session && validSession(coordinator.session) ? coordinator.session : null), { data: { subscription: { unsubscribe() {
4448
5385
  coordinator.sessions.delete(listener), sessionObservers.delete(listener);
4449
5386
  } } } };
4450
5387
  }
@@ -4459,7 +5396,8 @@ function accountRefusal(error) {
4459
5396
  return [400, 401, 403, 404, 422].includes(error?.status ?? 0);
4460
5397
  }
4461
5398
  function terminalSessionFailure(error) {
4462
- return [400, 401, 403, 404, 422].includes(error?.status ?? 0);
5399
+ let code = error?.code;
5400
+ return ["refresh_token_not_found", "refresh_token_already_used", "session_not_found", "session_expired", "user_banned"].includes(code);
4463
5401
  }
4464
5402
  function validEmail(email) {
4465
5403
  return typeof email == "string" && email.length <= 320 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
@@ -4496,56 +5434,111 @@ var BrowserAuthError = class extends Error {
4496
5434
  async function provider(configuration, guard) {
4497
5435
  let { AuthClient } = await prepareProvider();
4498
5436
  if (!guard.current(guard.revision())) throw new BrowserAuthError("stale");
4499
- let provenance = /* @__PURE__ */ new Map(), removalRevision, authorizationRequest, authorizationQueue = Promise.resolve(), storage = globalThis.localStorage, client = new AuthClient({
4500
- url: `${configuration.providerUrl}/auth/v1`,
4501
- headers: { apikey: configuration.publishableKey, Authorization: `Bearer ${configuration.publishableKey}` },
4502
- storageKey: `sb-${new URL(configuration.providerUrl).hostname.split(".")[0]}-auth-token`,
4503
- persistSession: !0,
4504
- autoRefreshToken: !0,
4505
- detectSessionInUrl: !1,
4506
- storage: {
4507
- getItem: (key) => storage.getItem(key),
4508
- removeItem(key) {
4509
- if (!guard.current(removalRevision ?? guard.revision())) throw new BrowserAuthError("stale");
4510
- storage.removeItem(key);
5437
+ let authorizationRequest, authorizationQueue = Promise.resolve(), storage = globalThis.localStorage, storageKey = `sb-${new URL(configuration.providerUrl).hostname.split(".")[0]}-auth-token`, listeners = /* @__PURE__ */ new Set(), instance;
5438
+ function createClient(clearing = !1) {
5439
+ let provenance = /* @__PURE__ */ new Map(), revocation, removalRevision = clearing ? guard.revision() : void 0, lifetime = new AbortController(), alive = () => !lifetime.signal.aborted, client = new AuthClient({
5440
+ url: `${configuration.providerUrl}/auth/v1`,
5441
+ headers: { apikey: configuration.publishableKey, Authorization: `Bearer ${configuration.publishableKey}` },
5442
+ storageKey,
5443
+ // The coordinator owns the expiry timer and bounded, operation-driven
5444
+ // recovery. A provider ticker/visibility retry must not outlive that bound.
5445
+ persistSession: !0,
5446
+ autoRefreshToken: !1,
5447
+ detectSessionInUrl: !1,
5448
+ storage: {
5449
+ getItem: (key) => alive() && removalRevision === void 0 ? storage.getItem(key) : null,
5450
+ removeItem(key) {
5451
+ if (!alive()) return;
5452
+ let current2 = guard.current(removalRevision ?? guard.revision());
5453
+ if (alive()) {
5454
+ if (!current2) throw new BrowserAuthError("stale");
5455
+ storage.removeItem(key);
5456
+ }
5457
+ },
5458
+ setItem(key, value) {
5459
+ let token = JSON.parse(value).access_token, revision = token ? provenance.get(token) : void 0, current2 = guard.current(revision ?? guard.revision());
5460
+ if (!alive() || !current2 || token && !guard.canPersistSession()) throw new BrowserAuthError("stale");
5461
+ storage.setItem(key, value);
5462
+ }
4511
5463
  },
4512
- setItem(key, value) {
4513
- let token = JSON.parse(value).access_token, revision = token ? provenance.get(token) : void 0;
4514
- if (!guard.current(revision ?? guard.revision()) || token && !guard.canPersistSession()) throw new BrowserAuthError("stale");
4515
- storage.setItem(key, value);
5464
+ fetch: Object.assign(async (input, init2) => {
5465
+ 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 = () => {
5466
+ throw request3 && (request3.rejected = !0), new BrowserAuthError("stale");
5467
+ };
5468
+ if (request3 && (!request3.current() || !guard.canAuthorize(new Headers(init2?.headers).get("authorization")?.replace(/^Bearer /, "") ?? "")) && rejectStale(), !alive() && refresh2) return cancelled();
5469
+ (!guard.current(revision) || !alive()) && rejectStale();
5470
+ let response2, body;
5471
+ try {
5472
+ response2 = await fetch(input, {
5473
+ ...init2,
5474
+ redirect: "error",
5475
+ signal: init2?.signal ? AbortSignal.any([init2.signal, lifetime.signal]) : lifetime.signal
5476
+ }), body = await response2.arrayBuffer();
5477
+ } catch (error) {
5478
+ if (!alive() && refresh2) return cancelled();
5479
+ throw error;
5480
+ }
5481
+ if (!alive() && refresh2) return cancelled();
5482
+ if ((!guard.current(revision) || !alive() || request3 && !request3.current()) && rejectStale(), refresh2) {
5483
+ let value;
5484
+ try {
5485
+ value = JSON.parse(new TextDecoder().decode(body));
5486
+ } catch {
5487
+ }
5488
+ let code = value?.code ?? value?.error_code, revoked = !response2.ok && [
5489
+ "refresh_token_not_found",
5490
+ "refresh_token_already_used",
5491
+ "session_not_found",
5492
+ "session_expired",
5493
+ "user_banned"
5494
+ ].includes(code);
5495
+ if (revoked && (revocation = { code }), !(response2.ok && typeof value?.access_token == "string" && /^[^\s]{1,8192}$/.test(value.access_token) && typeof value.refresh_token == "string" && !!value.refresh_token && typeof value.expires_in == "number" && value.expires_in > 0 && typeof value.user?.id == "string" && guard.canRefresh(value.user.id) && Number.isFinite(value.expires_at ?? (typeof value.expires_in == "number" ? Date.now() / 1e3 + value.expires_in : NaN)) && Number(value.expires_at ?? Date.now() / 1e3 + Number(value.expires_in)) * 1e3 > Date.now()) && !revoked) return Response.json({ message: "Refresh unavailable" }, { status: 503 });
5496
+ }
5497
+ let result2 = new Response(
5498
+ [204, 205, 304].includes(response2.status) ? null : body,
5499
+ { status: response2.status, statusText: response2.statusText, headers: response2.headers }
5500
+ ), json2 = result2.json.bind(result2);
5501
+ return result2.json = async () => {
5502
+ let value = await json2();
5503
+ return (!guard.current(revision) || !alive() || request3 && !request3.current()) && rejectStale(), value && typeof value.access_token == "string" && provenance.set(value.access_token, revision), value;
5504
+ }, result2;
5505
+ }, { preconnect: fetch.preconnect })
5506
+ });
5507
+ return client.onAuthStateChange((event, session) => {
5508
+ let revision = session ? provenance.get(session.access_token) : void 0, current2 = revision === void 0 || guard.current(revision);
5509
+ if (!(!alive() || !current2)) {
5510
+ for (let callback of listeners) callback(event, session);
5511
+ session && provenance.delete(session.access_token);
4516
5512
  }
4517
- },
4518
- fetch: Object.assign(async (input, init2) => {
4519
- let revision = guard.revision(), request2 = String(input).startsWith(`${configuration.providerUrl}/auth/v1/oauth/authorizations/`) ? authorizationRequest : void 0, rejectStale = () => {
4520
- throw request2 && (request2.rejected = !0), new BrowserAuthError("stale");
4521
- };
4522
- request2 && (!request2.current() || !guard.canAuthorize(new Headers(init2?.headers).get("authorization")?.replace(/^Bearer /, "") ?? "")) && rejectStale();
4523
- let response2 = await fetch(input, { ...init2, redirect: "error" }), body = await response2.arrayBuffer();
4524
- (!guard.current(revision) || request2 && !request2.current()) && rejectStale();
4525
- let result2 = new Response(
4526
- [204, 205, 304].includes(response2.status) ? null : body,
4527
- { status: response2.status, statusText: response2.statusText, headers: response2.headers }
4528
- ), json2 = result2.json.bind(result2);
4529
- return result2.json = async () => {
4530
- let value = await json2();
4531
- return (!guard.current(revision) || request2 && !request2.current()) && rejectStale(), value && typeof value.access_token == "string" && provenance.set(value.access_token, revision), value;
4532
- }, result2;
4533
- }, { preconnect: fetch.preconnect })
4534
- });
5513
+ }), { client, alive, revocation: () => revocation, async clearSession() {
5514
+ removalRevision = guard.revision();
5515
+ try {
5516
+ return await client.signOut({ scope: "local" });
5517
+ } finally {
5518
+ removalRevision = void 0;
5519
+ }
5520
+ }, close() {
5521
+ lifetime.abort(), provenance.clear(), client.dispose();
5522
+ } };
5523
+ }
5524
+ let activeClient = () => (instance ??= createClient()).client, retire = () => {
5525
+ instance?.close(), instance = void 0;
5526
+ };
5527
+ activeClient();
4535
5528
  async function authorization(kind, id3, current2) {
4536
5529
  let previous = authorizationQueue, release;
4537
5530
  authorizationQueue = new Promise((resolve) => {
4538
5531
  release = resolve;
4539
5532
  }), await previous;
4540
- let request2 = { current: current2, rejected: !1 };
4541
- authorizationRequest = request2;
5533
+ let request3 = { current: current2, rejected: !1 };
5534
+ authorizationRequest = request3;
4542
5535
  try {
4543
5536
  if (!current2()) throw new BrowserAuthError("stale");
4544
- let result2 = await (kind === "get" ? client.oauth.getAuthorizationDetails(id3) : kind === "approve" ? client.oauth.approveAuthorization(id3, { skipBrowserRedirect: !0 }) : client.oauth.denyAuthorization(id3, { skipBrowserRedirect: !0 }));
4545
- if (request2.rejected || !current2()) throw new BrowserAuthError("stale");
5537
+ 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 }));
5538
+ if (request3.rejected || !current2()) throw new BrowserAuthError("stale");
4546
5539
  return result2;
4547
5540
  } catch (error) {
4548
- throw request2.rejected || !current2() ? new BrowserAuthError("stale") : error;
5541
+ throw request3.rejected || !current2() ? new BrowserAuthError("stale") : error;
4549
5542
  } finally {
4550
5543
  authorizationRequest = void 0, release();
4551
5544
  }
@@ -4556,23 +5549,46 @@ async function provider(configuration, guard) {
4556
5549
  approve: (id3, current2) => authorization("approve", id3, current2),
4557
5550
  deny: (id3, current2) => authorization("deny", id3, current2)
4558
5551
  },
4559
- getSession: () => client.getSession(),
4560
- onAuthStateChange: (callback) => client.onAuthStateChange((event, session) => {
4561
- let revision = session ? provenance.get(session.access_token) : void 0;
4562
- revision !== void 0 && !guard.current(revision) || (callback(event, session), session && provenance.delete(session.access_token));
4563
- }),
4564
- signInWithOtp: (input) => client.signInWithOtp(input),
4565
- verifyOtp: (input) => client.verifyOtp(input),
4566
- async signOut(input) {
4567
- removalRevision = guard.revision();
5552
+ async getSession(signal) {
5553
+ let client = activeClient(), owned = instance, revision = guard.revision(), abort = () => {
5554
+ instance === owned && retire();
5555
+ };
5556
+ signal?.addEventListener("abort", abort, { once: !0 });
4568
5557
  try {
4569
- return await client.signOut(input);
5558
+ if (signal?.aborted)
5559
+ throw abort(), new BrowserAuthError("stale");
5560
+ let result2 = await client.getSession();
5561
+ return owned?.revocation() && guard.current(revision) && owned.alive() ? (await owned.clearSession(), { data: { session: null }, error: owned.revocation() }) : result2;
4570
5562
  } finally {
4571
- removalRevision = void 0;
5563
+ signal?.removeEventListener("abort", abort);
5564
+ }
5565
+ },
5566
+ onAuthStateChange(callback) {
5567
+ return listeners.add(callback), { data: { subscription: { unsubscribe() {
5568
+ listeners.delete(callback);
5569
+ } } } };
5570
+ },
5571
+ signInWithOtp: (input) => activeClient().signInWithOtp(input),
5572
+ verifyOtp: (input) => activeClient().verifyOtp(input),
5573
+ async signOut(input) {
5574
+ let session = null;
5575
+ try {
5576
+ session = JSON.parse(storage.getItem(storageKey) ?? "null");
5577
+ } catch {
4572
5578
  }
5579
+ retire();
5580
+ let revision = guard.revision();
5581
+ instance = createClient(!0);
5582
+ let client = instance.client, cleared = await instance.clearSession();
5583
+ if (!guard.current(revision)) throw new BrowserAuthError("stale");
5584
+ if (cleared.error) return cleared;
5585
+ if (!session?.access_token) return { error: null };
5586
+ let { error } = await client.admin.signOut(session.access_token, input.scope);
5587
+ if (!guard.current(revision)) throw new BrowserAuthError("stale");
5588
+ return { error: error && error.name !== "AuthSessionMissingError" && ![401, 403, 404].includes(error.status ?? 0) ? error : null };
4573
5589
  },
4574
5590
  dispose() {
4575
- provenance.clear(), client.dispose();
5591
+ retire(), listeners.clear();
4576
5592
  }
4577
5593
  };
4578
5594
  }
@@ -4602,29 +5618,29 @@ function routineRunHandle(operations2) {
4602
5618
  });
4603
5619
  }
4604
5620
 
4605
- 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 = () => {
5621
+ 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 = () => {
4606
5622
  throw new Error("Run state unavailable");
4607
- }, record3 = (value) => value && typeof value == "object" && !Array.isArray(value) ? value : invalid8();
4608
- function time(value) {
4609
- return typeof value != "string" || value.length > 40 || !Number.isFinite(Date.parse(value)) ? invalid8() : value;
5623
+ }, record3 = (value) => value && typeof value == "object" && !Array.isArray(value) ? value : invalid11();
5624
+ function time2(value) {
5625
+ return typeof value != "string" || value.length > 40 || !Number.isFinite(Date.parse(value)) ? invalid11() : value;
4610
5626
  }
4611
5627
  function times(value) {
4612
5628
  return {
4613
- ...value.startedAt === void 0 ? {} : { startedAt: time(value.startedAt) },
4614
- ...value.finishedAt === void 0 ? {} : { finishedAt: time(value.finishedAt) }
5629
+ ...value.startedAt === void 0 ? {} : { startedAt: time2(value.startedAt) },
5630
+ ...value.finishedAt === void 0 ? {} : { finishedAt: time2(value.finishedAt) }
4615
5631
  };
4616
5632
  }
4617
5633
  function bounded(value) {
4618
- return assertRoutineJson(value), new TextEncoder().encode(JSON.stringify(value)).byteLength > 256 * 1024 ? invalid8() : value;
5634
+ return assertRoutineJson(value), new TextEncoder().encode(JSON.stringify(value)).byteLength > 256 * 1024 ? invalid11() : value;
4619
5635
  }
4620
5636
  function progress(value) {
4621
5637
  if (value === void 0) return {};
4622
5638
  let v = record3(value);
4623
- 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 } };
5639
+ 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 } };
4624
5640
  }
4625
5641
  function parseRunStep(value, expected) {
4626
5642
  let v = record3(value);
4627
- 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();
5643
+ 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();
4628
5644
  let output = captureRetainedStepOutput(v.id, {
4629
5645
  ...Object.hasOwn(v, "summary") ? { summary: v.summary } : {},
4630
5646
  ...Object.hasOwn(v, "data") ? { data: v.data } : {}
@@ -4641,28 +5657,28 @@ function parseRunStep(value, expected) {
4641
5657
  }
4642
5658
  function parseRemoteRun(value, expected = {}) {
4643
5659
  let v = record3(value);
4644
- 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();
5660
+ 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();
4645
5661
  let steps = v.steps.map((value2) => {
4646
5662
  let step = record3(value2);
4647
- return typeof step.detailAvailable != "boolean" || Object.hasOwn(step, "data") ? invalid8() : { ...parseRunStep(step), detailAvailable: step.detailAvailable };
5663
+ return typeof step.detailAvailable != "boolean" || Object.hasOwn(step, "data") ? invalid11() : { ...parseRunStep(step), detailAvailable: step.detailAvailable };
4648
5664
  });
4649
- if (new Set(steps.map((step) => step.id)).size !== steps.length) return invalid8();
5665
+ if (new Set(steps.map((step) => step.id)).size !== steps.length) return invalid11();
4650
5666
  let failure;
4651
5667
  if (v.failure !== void 0) {
4652
5668
  let f = record3(v.failure);
4653
- if (v.status !== "failed" || typeof f.message != "string" || !f.message || f.message.length > 512) return invalid8();
5669
+ if (v.status !== "failed" || typeof f.message != "string" || !f.message || f.message.length > 512) return invalid11();
4654
5670
  if (f.code === "step_output_too_large") {
4655
5671
  let { code, message: message2, ...facts } = f, detail = parseRoutineStepOutputDetail(facts);
4656
- if (!steps.some((step) => step.id === detail.step && step.status === "failed") || message2 !== routineStepOutputMessage(detail)) return invalid8();
5672
+ if (!steps.some((step) => step.id === detail.step && step.status === "failed") || message2 !== routineStepOutputMessage(detail)) return invalid11();
4657
5673
  failure = { code, message: message2, ...detail };
4658
5674
  } else failure = { message: f.message };
4659
5675
  }
4660
- return Object.hasOwn(v, "result") && v.status !== "succeeded" ? invalid8() : {
5676
+ return Object.hasOwn(v, "result") && v.status !== "succeeded" ? invalid11() : {
4661
5677
  id: v.id,
4662
5678
  routine: v.routine,
4663
5679
  placement: "remote",
4664
5680
  status: v.status,
4665
- createdAt: time(v.createdAt),
5681
+ createdAt: time2(v.createdAt),
4666
5682
  ...times(v),
4667
5683
  steps,
4668
5684
  ...Object.hasOwn(v, "result") ? { result: bounded(v.result) } : {},
@@ -4670,7 +5686,7 @@ function parseRemoteRun(value, expected = {}) {
4670
5686
  };
4671
5687
  }
4672
5688
 
4673
- 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([
5689
+ 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([
4674
5690
  "context_unavailable",
4675
5691
  "unauthenticated",
4676
5692
  "access_denied",
@@ -4688,26 +5704,26 @@ var identifier = /^[a-z0-9]+(?:-[a-z0-9]+)*(?![\s\S])/, uuid2 = /^[0-9a-f]{8}-[0
4688
5704
  this.name = "AppRoutineError";
4689
5705
  }
4690
5706
  reason;
4691
- }, fail3 = (reason) => {
5707
+ }, fail6 = (reason) => {
4692
5708
  throw new AppRoutineError(reason);
4693
5709
  };
4694
5710
  function current(context) {
4695
- (!context.isCurrent() || context.kind === "local" && context.signal.aborted) && fail3("authority_unavailable");
5711
+ (!context.isCurrent() || context.kind === "local" && context.signal.aborted) && fail6("authority_unavailable");
4696
5712
  }
4697
5713
  function appDescriptors() {
4698
5714
  return globalThis[/* @__PURE__ */ Symbol.for("oddington.app.descriptor")]?.routines ?? [];
4699
5715
  }
4700
5716
  async function authority(retained = !1) {
4701
- let context = await resolveAppContext(retained).catch(() => fail3("authority_unavailable"));
4702
- 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;
5717
+ let context = await resolveAppContext(retained).catch(() => fail6("authority_unavailable"));
5718
+ 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;
4703
5719
  }
4704
5720
  async function live(context, read2) {
4705
5721
  if (current(context), context.kind === "local") return context;
4706
5722
  let resolved = await authority(read2);
4707
- 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;
5723
+ 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;
4708
5724
  }
4709
- async function request(key, suffix, init2, maximum = SUMMARY_BYTES, retained, read2 = !1) {
4710
- (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail3("authority_unavailable");
5725
+ async function request2(key, suffix, init2, maximum = SUMMARY_BYTES, retained, read2 = !1) {
5726
+ (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail6("authority_unavailable");
4711
5727
  let context = retained ? await live(retained, read2) : await authority(read2);
4712
5728
  current(context);
4713
5729
  let deadline = new AbortController(), timeout = context.kind === "local" ? void 0 : setTimeout(() => deadline.abort(), 2e4);
@@ -4719,22 +5735,22 @@ async function request(key, suffix, init2, maximum = SUMMARY_BYTES, retained, re
4719
5735
  signal: deadline.signal,
4720
5736
  headers: { authorization: `Bearer ${context.accessToken}`, ...init2?.body ? { "content-type": "application/json" } : {} }
4721
5737
  }));
4722
- response2.redirected && fail3("execution_unavailable");
5738
+ response2.redirected && fail6("execution_unavailable");
4723
5739
  let value = await appResponse(response2, maximum, context.kind === "local" ? context.signal : deadline.signal);
4724
5740
  if (current(context), context.kind !== "local" && await live(context, read2), !response2.ok) {
4725
5741
  if (context.kind !== "local") {
4726
5742
  let code = value?.code;
4727
- 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"))
4728
- return unavailable4(key, code === "current_deployment_unavailable" ? "not_deployed" : "capability_unavailable");
4729
- fail3("execution_unavailable");
5743
+ 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"))
5744
+ return unavailable5(key, code === "current_deployment_unavailable" ? "not_deployed" : "capability_unavailable");
5745
+ fail6("execution_unavailable");
4730
5746
  }
4731
5747
  let reason = value?.error;
4732
- reason === "authority_unavailable" && (context.kind === "local" && context.invalidate(), fail3(reason)), (reason === "invalid_input" || reason === "execution_unavailable") && fail3(reason), fail3("execution_unavailable");
5748
+ reason === "authority_unavailable" && (context.kind === "local" && context.invalidate(), fail6(reason)), (reason === "invalid_input" || reason === "execution_unavailable") && fail6(reason), fail6("execution_unavailable");
4733
5749
  }
4734
5750
  return value;
4735
5751
  } catch (error) {
4736
5752
  if (current(context), error instanceof AppRoutineError) throw error;
4737
- fail3("execution_unavailable");
5753
+ fail6("execution_unavailable");
4738
5754
  } finally {
4739
5755
  clearTimeout(timeout);
4740
5756
  }
@@ -4742,12 +5758,12 @@ async function request(key, suffix, init2, maximum = SUMMARY_BYTES, retained, re
4742
5758
  function summary(value, key, context, id3) {
4743
5759
  if (context.kind !== "local")
4744
5760
  try {
4745
- 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 });
5761
+ 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 });
4746
5762
  } catch {
4747
- return fail3("execution_unavailable");
5763
+ return fail6("execution_unavailable");
4748
5764
  }
4749
5765
  let run = value;
4750
- 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;
5766
+ 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;
4751
5767
  }
4752
5768
  function validFailure(value, steps) {
4753
5769
  if (!only(value, "message,code,step,sizeBytes,limitBytes,summaryBytes,dataBytes") || !message(value.message)) return !1;
@@ -4787,18 +5803,18 @@ function validLocalActivity(value) {
4787
5803
  } catch {
4788
5804
  return !1;
4789
5805
  }
4790
- })())) && 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)));
5806
+ })())) && 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)));
4791
5807
  }
4792
5808
  function jsonInput(value, ancestors = /* @__PURE__ */ new Set()) {
4793
5809
  if (value === null || typeof value == "string" || typeof value == "boolean" || typeof value == "number" && Number.isFinite(value)) return;
4794
- if (!value || typeof value != "object" || ancestors.has(value)) return fail3("invalid_input");
4795
- let array3 = Array.isArray(value), keys4 = Reflect.ownKeys(value);
4796
- 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");
5810
+ if (!value || typeof value != "object" || ancestors.has(value)) return fail6("invalid_input");
5811
+ let array3 = Array.isArray(value), keys6 = Reflect.ownKeys(value);
5812
+ 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");
4797
5813
  ancestors.add(value);
4798
- for (let key of keys4) {
5814
+ for (let key of keys6) {
4799
5815
  if (array3 && key === "length") continue;
4800
5816
  let descriptor = Object.getOwnPropertyDescriptor(value, key);
4801
- if (typeof key != "string" || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) return fail3("invalid_input");
5817
+ if (typeof key != "string" || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) return fail6("invalid_input");
4802
5818
  jsonInput(descriptor.value, ancestors);
4803
5819
  }
4804
5820
  ancestors.delete(value);
@@ -4807,26 +5823,26 @@ function structure(value) {
4807
5823
  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);
4808
5824
  }
4809
5825
  function handle(key, id3, context) {
4810
- (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail3("authority_unavailable"), (typeof id3 != "string" || !uuid2.test(id3)) && fail3("invalid_input");
4811
- let read2 = async () => summary(await request(key, `runs/${id3}`, void 0, SUMMARY_BYTES, context, !0), key, context, id3);
5826
+ (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail6("authority_unavailable"), (typeof id3 != "string" || !uuid3.test(id3)) && fail6("invalid_input");
5827
+ let read2 = async () => summary(await request2(key, `runs/${id3}`, void 0, SUMMARY_BYTES, context, !0), key, context, id3);
4812
5828
  return routineRunHandle({
4813
5829
  async current() {
4814
5830
  return current(context), read2();
4815
5831
  },
4816
5832
  async step(step) {
4817
- (typeof step != "string" || !identifier.test(step)) && fail3("invalid_input");
4818
- let value = await request(key, `runs/${id3}/steps/${step}`, void 0, ROUTINE_STEP_OUTPUT_BYTES + 4096, context, !0);
5833
+ (typeof step != "string" || !identifier.test(step)) && fail6("invalid_input");
5834
+ let value = await request2(key, `runs/${id3}/steps/${step}`, void 0, ROUTINE_STEP_OUTPUT_BYTES + 4096, context, !0);
4819
5835
  if (context.kind !== "local")
4820
5836
  try {
4821
- return only(value, "id,title,status,startedAt,finishedAt,progress,summary,data") || fail3("execution_unavailable"), parseRunStep(value, step);
5837
+ return only(value, "id,title,status,startedAt,finishedAt,progress,summary,data") || fail6("execution_unavailable"), parseRunStep(value, step);
4822
5838
  } catch {
4823
- return fail3("execution_unavailable");
5839
+ return fail6("execution_unavailable");
4824
5840
  }
4825
- return (!only(value, "id,title,status,startedAt,finishedAt,progress,summary,data") || value.id !== step || !validStep(value)) && fail3("execution_unavailable"), value;
5841
+ return (!only(value, "id,title,status,startedAt,finishedAt,progress,summary,data") || value.id !== step || !validStep(value)) && fail6("execution_unavailable"), value;
4826
5842
  }
4827
5843
  });
4828
5844
  }
4829
- function unavailable4(key, reason) {
5845
+ function unavailable5(key, reason) {
4830
5846
  let descriptor = appDescriptors().find((item) => item.id === key);
4831
5847
  return {
4832
5848
  ...structuredClone(descriptor),
@@ -4835,7 +5851,7 @@ function unavailable4(key, reason) {
4835
5851
  };
4836
5852
  }
4837
5853
  function deployedDescription(value, key) {
4838
- (!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");
5854
+ (!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");
4839
5855
  let { default: inputDefault, ...input } = value.input, contract = parseAppRoutineContract({
4840
5856
  routine: key,
4841
5857
  input,
@@ -4845,44 +5861,44 @@ function deployedDescription(value, key) {
4845
5861
  }
4846
5862
  async function describeAppRoutine(key) {
4847
5863
  let descriptor = appDescriptors().find((item) => item.id === key);
4848
- if (!descriptor) return fail3("authority_unavailable");
5864
+ if (!descriptor) return fail6("authority_unavailable");
4849
5865
  try {
4850
- let context = await authority(), value = await request(key, "describe", void 0, 1024 * 1024, context);
4851
- 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;
5866
+ let context = await authority(), value = await request2(key, "describe", void 0, 1024 * 1024, context);
5867
+ 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;
4852
5868
  } catch {
4853
- return unavailable4(key, "capability_unavailable");
5869
+ return unavailable5(key, "capability_unavailable");
4854
5870
  }
4855
5871
  }
4856
5872
  function appRoutineBinding(key) {
4857
- return (typeof key != "string" || !identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail3("authority_unavailable"), Object.freeze({
5873
+ return (typeof key != "string" || !identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail6("authority_unavailable"), Object.freeze({
4858
5874
  describe: () => describeAppRoutine(key),
4859
5875
  async run(...args) {
4860
- args.length > 1 && fail3("invalid_input");
5876
+ args.length > 1 && fail6("invalid_input");
4861
5877
  let encoded;
4862
5878
  try {
4863
5879
  if (args[0] === void 0) encoded = "{}";
4864
5880
  else {
4865
5881
  jsonInput(args[0]);
4866
5882
  let input = JSON.stringify(args[0]);
4867
- new TextEncoder().encode(input).byteLength > 256 * 1024 && fail3("invalid_input"), encoded = `{"input":${input}}`;
5883
+ new TextEncoder().encode(input).byteLength > 256 * 1024 && fail6("invalid_input"), encoded = `{"input":${input}}`;
4868
5884
  }
4869
5885
  } catch {
4870
- return fail3("invalid_input");
5886
+ return fail6("invalid_input");
4871
5887
  }
4872
5888
  let context = await authority();
4873
5889
  context.kind !== "local" && (encoded = JSON.stringify({ ...JSON.parse(encoded), startKey: crypto.randomUUID() }));
4874
- let run = summary(await request(key, "runs", { method: "POST", body: encoded }, SUMMARY_BYTES, context), key, context);
5890
+ let run = summary(await request2(key, "runs", { method: "POST", body: encoded }, SUMMARY_BYTES, context), key, context);
4875
5891
  return handle(key, run.id, context);
4876
5892
  },
4877
5893
  runs: Object.freeze({
4878
5894
  async list() {
4879
- let context = await authority(!0), value = await request(key, "runs", void 0, 20 * SUMMARY_BYTES, context, !0);
4880
- if (!Array.isArray(value) || value.length > 20) return fail3("execution_unavailable");
5895
+ let context = await authority(!0), value = await request2(key, "runs", void 0, 20 * SUMMARY_BYTES, context, !0);
5896
+ if (!Array.isArray(value) || value.length > 20) return fail6("execution_unavailable");
4881
5897
  let runs = value.map((run) => summary(run, key, context));
4882
- return new Set(runs.map((run) => run.id)).size !== runs.length && fail3("execution_unavailable"), runs;
5898
+ return new Set(runs.map((run) => run.id)).size !== runs.length && fail6("execution_unavailable"), runs;
4883
5899
  },
4884
5900
  async get(id3) {
4885
- 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));
5901
+ 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));
4886
5902
  }
4887
5903
  })
4888
5904
  });
@@ -4902,11 +5918,11 @@ var app = /* @__PURE__ */ Object.freeze({
4902
5918
  })
4903
5919
  });
4904
5920
 
4905
- async function requestInboxPublication(operation2, request2, caller) {
5921
+ async function requestInboxPublication(operation2, request3, caller) {
4906
5922
  let attempt = () => {
4907
5923
  if (caller?.aborted) throw caller.reason;
4908
5924
  let timeout = AbortSignal.timeout(3e4);
4909
- return request2(caller ? AbortSignal.any([caller, timeout]) : timeout);
5925
+ return request3(caller ? AbortSignal.any([caller, timeout]) : timeout);
4910
5926
  };
4911
5927
  if (operation2 !== "publish") return attempt();
4912
5928
  try {
@@ -4924,7 +5940,7 @@ function routinePublicationClient2(options = {}) {
4924
5940
  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);
4925
5941
  if (!workspace || !/^[a-z0-9][a-z0-9-]*$/.test(workspace) || capability !== void 0 && !/^[0-9a-f]{64}$/.test(capability))
4926
5942
  throw new Error("A workspace and valid optional routine capability are required");
4927
- let headers = capability ? { "x-os-run": capability } : {}, request2 = options.request ?? (capability ? async (path, init2) => {
5943
+ let headers = capability ? { "x-os-run": capability } : {}, request3 = options.request ?? (capability ? async (path, init2) => {
4928
5944
  let origin = `https://${workspace}.oddington.ai`, target = new URL(path, `${origin}/`);
4929
5945
  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")
4930
5946
  throw new Error("Invalid routine endpoint");
@@ -4934,7 +5950,7 @@ function routinePublicationClient2(options = {}) {
4934
5950
  });
4935
5951
  async function send3(operation2, body) {
4936
5952
  if (local2) return await local2(operation2, body);
4937
- let response2 = await requestInboxPublication(operation2, (signal) => request2(`/api/inbox/${operation2}`, {
5953
+ let response2 = await requestInboxPublication(operation2, (signal) => request3(`/api/inbox/${operation2}`, {
4938
5954
  method: "POST",
4939
5955
  headers: { "content-type": "application/json", ...headers },
4940
5956
  body: JSON.stringify(body),