@oddington/sdk 0.1.75 → 0.1.77

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
@@ -5302,26 +5302,27 @@ function asksBlock(value) {
5302
5302
  }
5303
5303
  function selection(value) {
5304
5304
  let input = object(value, "selection");
5305
- return keys(input, ["source"], "selection"), validateResponseDefinition({ type: "selection", source: input.source });
5305
+ return keys(input, ["source", "options"], "selection"), validateResponseDefinition({ type: "selection", ...input });
5306
+ }
5307
+ function validateChoice(entry) {
5308
+ let option = object(entry, "choice");
5309
+ keys(option, ["value", "label", "description", "note"], "choice");
5310
+ let note;
5311
+ if (option.note !== void 0) {
5312
+ let declaration2 = object(option.note, "choice note");
5313
+ keys(declaration2, ["placeholder"], "choice note"), note = { placeholder: text(declaration2.placeholder, "note placeholder") };
5314
+ }
5315
+ return {
5316
+ value: id(option.value, "choice value"),
5317
+ label: text(option.label, "choice label"),
5318
+ ...option.description === void 0 ? {} : { description: text(option.description, "choice description") },
5319
+ ...note ? { note } : {}
5320
+ };
5306
5321
  }
5307
5322
  function validateAuthoredSource(value) {
5308
5323
  let source2 = object(value, "response definition");
5309
5324
  keys(source2, ["type", "options", "suggestions", "search"], "response definition"), source2.type !== "authored" && fail("Expected authored options");
5310
- let options = array(source2.options, "options").map((entry) => {
5311
- let option = object(entry, "choice");
5312
- keys(option, ["value", "label", "description", "note"], "choice");
5313
- let note;
5314
- if (option.note !== void 0) {
5315
- let declaration2 = object(option.note, "choice note");
5316
- keys(declaration2, ["placeholder"], "choice note"), note = { placeholder: text(declaration2.placeholder, "note placeholder") };
5317
- }
5318
- return {
5319
- value: id(option.value, "choice value"),
5320
- label: text(option.label, "choice label"),
5321
- ...option.description === void 0 ? {} : { description: text(option.description, "choice description") },
5322
- ...note ? { note } : {}
5323
- };
5324
- });
5325
+ let options = array(source2.options, "options").map(validateChoice);
5325
5326
  if (options.length || fail("Choices require at least one option"), new Set(options.map((option) => option.value)).size !== options.length && fail("Duplicate choice value"), Object.hasOwn(source2, "search") || Object.hasOwn(source2, "suggestions")) {
5326
5327
  let labels = object(source2.search, "choice search");
5327
5328
  keys(labels, ["triggerLabel", "placeholder", "emptyLabel"], "choice search");
@@ -5340,10 +5341,8 @@ function validateRecordReference(value) {
5340
5341
  let repository = id(row.repository, "repository"), ref = id(row.ref, "Record reference");
5341
5342
  return (!/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(repository) || /\.\.|\/\//.test(repository) || ref.length > 512 || !/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(ref)) && fail("Invalid Record identity"), { repository, ref };
5342
5343
  }
5343
- function validateRecordSource(value) {
5344
- let source2 = object(value, "Record selection");
5345
- keys(source2, ["type", "collection", "refPrefix", "where", "display", "suggestions"], "Record selection"), source2.type !== "records" && fail("Expected Record options");
5346
- let collection = object(source2.collection, "collection");
5344
+ function recordPickerSource(value) {
5345
+ let source2 = object(value, "Record selection"), collection = object(source2.collection, "collection");
5347
5346
  keys(collection, ["repository", "name"], "collection");
5348
5347
  let repository = validateRecordReference({ repository: collection.repository, ref: "records/example" }).repository, name2 = id(collection.name, "collection name");
5349
5348
  /^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(name2) || fail("Invalid collection name");
@@ -5352,10 +5351,23 @@ function validateRecordSource(value) {
5352
5351
  let where = object(source2.where ?? {}, "Record filter"), fieldName = (name3) => /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name3) && !["constructor", "prototype"].includes(name3);
5353
5352
  for (let [name3, value2] of Object.entries(where))
5354
5353
  (!fieldName(name3) || !(value2 === null || ["string", "number", "boolean"].includes(typeof value2)) || typeof value2 == "number" && !Number.isFinite(value2)) && fail("Record filters require scalar equality");
5355
- let display = object(source2.display, "Record display");
5354
+ return {
5355
+ collection: { repository, name: name2 },
5356
+ ...refPrefix ? { refPrefix } : {},
5357
+ ...source2.where === void 0 ? {} : { where: { ...where } }
5358
+ };
5359
+ }
5360
+ function validateRecordPickerSource(value) {
5361
+ let source2 = object(value, "Record picker source");
5362
+ return keys(source2, ["collection", "refPrefix", "where"], "Record picker source"), Object.hasOwn(source2, "where") && object(source2.where, "Record filter"), recordPickerSource(source2);
5363
+ }
5364
+ function validateRecordSource(value) {
5365
+ let source2 = object(value, "Record selection");
5366
+ keys(source2, ["type", "collection", "refPrefix", "where", "display", "suggestions"], "Record selection"), source2.type !== "records" && fail("Expected Record options");
5367
+ let bounded3 = recordPickerSource(source2), { repository } = bounded3.collection, fieldName = (name2) => /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name2) && !["constructor", "prototype"].includes(name2), display = object(source2.display, "Record display");
5356
5368
  keys(display, ["labelFields"], "Record display");
5357
5369
  let labelFields = distinctIds(display.labelFields, "label fields");
5358
- (labelFields.length > 2 || labelFields.some((name3) => !fieldName(name3))) && fail("Select one or two scalar label fields");
5370
+ (labelFields.length > 2 || labelFields.some((name2) => !fieldName(name2))) && fail("Select one or two scalar label fields");
5359
5371
  let suggestions = array(source2.suggestions ?? [], "suggestions").map((value2) => {
5360
5372
  let entry = object(value2, "suggestion");
5361
5373
  keys(entry, ["record", "reason"], "suggestion");
@@ -5364,14 +5376,13 @@ function validateRecordSource(value) {
5364
5376
  });
5365
5377
  return (suggestions.length > 8 || new Set(suggestions.map((entry) => entry.record.ref)).size !== suggestions.length) && fail("Record selection permits at most eight unique suggestions"), {
5366
5378
  type: "records",
5367
- collection: { repository, name: name2 },
5368
- ...refPrefix ? { refPrefix } : {},
5369
- where: { ...where },
5379
+ ...bounded3,
5380
+ where: bounded3.where ?? {},
5370
5381
  display: { labelFields },
5371
5382
  suggestions
5372
5383
  };
5373
5384
  }
5374
- function validateResponseDefinition(value) {
5385
+ function validateLegacyResponseDefinition(value) {
5375
5386
  let definition = object(value, "response definition");
5376
5387
  keys(definition, ["type", "source"], "response definition"), definition.type !== "selection" && fail("Expected a selection definition");
5377
5388
  let source2 = object(definition.source, "option source");
@@ -5384,6 +5395,41 @@ function validateResponseDefinition(value) {
5384
5395
  return fail("Unsupported option source");
5385
5396
  }
5386
5397
  }
5398
+ function selectionOptions(value, published) {
5399
+ let options = array(value, "options");
5400
+ return (!options.length || options.length > 9) && fail("Selections require one to nine options"), options.map((value2, index) => {
5401
+ let option = object(value2, "option"), common = published ? ["type", "id"] : ["type"];
5402
+ published && option.id !== index + 1 && fail("Published option IDs must be consecutive from one");
5403
+ let numbered = published ? { id: index + 1 } : {};
5404
+ switch (option.type) {
5405
+ case "choice":
5406
+ return keys(option, [...common, "value", "label", "description", "note"], "choice"), { type: "choice", ...validateChoice(
5407
+ Object.fromEntries(Object.entries(option).filter(([key]) => !["type", "id"].includes(key)))
5408
+ ), ...numbered };
5409
+ case "record":
5410
+ return keys(option, [...common, "value", "label", "description"], "Record option"), {
5411
+ type: "record",
5412
+ value: validateRecordReference(option.value),
5413
+ label: text(option.label, "Record label"),
5414
+ ...option.description === void 0 ? {} : { description: text(option.description, "Record description") },
5415
+ ...numbered
5416
+ };
5417
+ case "record-picker":
5418
+ return keys(option, [...common, "label", "source"], "Record picker option"), {
5419
+ type: "record-picker",
5420
+ label: text(option.label, "picker label"),
5421
+ source: validateRecordPickerSource(option.source),
5422
+ ...numbered
5423
+ };
5424
+ default:
5425
+ return fail("Unsupported option kind");
5426
+ }
5427
+ });
5428
+ }
5429
+ function validateResponseDefinition(value) {
5430
+ let definition = object(value, "response definition");
5431
+ return Object.hasOwn(definition, "options") ? (keys(definition, ["type", "options"], "response definition"), definition.type !== "selection" && fail("Expected a selection definition"), { type: "selection", options: selectionOptions(definition.options, !1) }) : validateLegacyResponseDefinition(definition);
5432
+ }
5387
5433
  function handlerReference(value) {
5388
5434
  let source2 = object(value, "handler reference");
5389
5435
  return keys(source2, ["id", "input"], "handler reference"), { id: id(source2.id, "handler ID"), input: serializable(source2.input) };
@@ -5528,11 +5574,11 @@ var RecordSelectionError = class extends InboxContractError {
5528
5574
  constructor(problem, source2) {
5529
5575
  let collection = `${source2.collection.repository}/${source2.collection.name}`, messages = {
5530
5576
  collection_unavailable: `The ${collection} collection is unavailable. Check the collection name and its schema.`,
5531
- display_fields_invalid: `The label fields for ${collection} must be scalar fields in its schema. Check display.labelFields.`,
5577
+ display_fields_invalid: "display" in source2 ? `The label fields for ${collection} must be scalar fields in its schema. Check display.labelFields.` : `The ${collection} schema must declare one or two scalar title fields. Check display.title.`,
5532
5578
  filter_fields_invalid: `The filters for ${collection} must use scalar schema fields and matching values. Check the Question\u2019s where fields.`,
5533
5579
  ref_prefix_invalid: `The record reference prefix does not belong to ${collection}. Check refPrefix against the collection\u2019s record references.`,
5534
5580
  suggestion_unavailable: `A suggested record is missing or isn\u2019t eligible for ${collection}. Update the suggestions and try again.`,
5535
- label_unavailable: `A record in ${collection} has no value in the configured label fields. Update display.labelFields or the record.`
5581
+ label_unavailable: "display" in source2 ? `A record in ${collection} has no value in the configured label fields. Update display.labelFields or the record.` : `A record in ${collection} has no value in the declared title fields. Update display.title or the record.`
5536
5582
  };
5537
5583
  super(messages[problem]);
5538
5584
  this.problem = problem;
@@ -5952,8 +5998,8 @@ function parseRoutineDeclaration(value) {
5952
5998
  for (let key of Object.keys(repositories).sort())
5953
5999
  (!routineAlias(key) || !["read", "write"].includes(repositories[key])) && invalid(`access.repositories.${key}`), grants[key] = repositories[key];
5954
6000
  access.files !== void 0 && !["read", "read-write"].includes(access.files) && invalid("access.files");
5955
- let runtime = object2(v.runtime === void 0 ? {} : v.runtime, ["features", "resources", "maxDuration"], "runtime");
5956
- runtime.features !== void 0 && (!Array.isArray(runtime.features) || runtime.features.length !== 0) && invalid("runtime.features"), runtime.resources !== void 0 && runtime.resources !== "standard" && invalid("runtime.resources"), runtime.maxDuration !== void 0 && !["15m", "60m"].includes(runtime.maxDuration) && invalid("runtime.maxDuration");
6001
+ let runtime2 = object2(v.runtime === void 0 ? {} : v.runtime, ["features", "resources", "maxDuration"], "runtime");
6002
+ runtime2.features !== void 0 && (!Array.isArray(runtime2.features) || runtime2.features.length !== 0) && invalid("runtime.features"), runtime2.resources !== void 0 && runtime2.resources !== "standard" && invalid("runtime.resources"), runtime2.maxDuration !== void 0 && !["15m", "60m"].includes(runtime2.maxDuration) && invalid("runtime.maxDuration");
5957
6003
  let retry = object2(v.retry === void 0 ? {} : v.retry, ["maxAttempts"], "retry");
5958
6004
  retry.maxAttempts !== void 0 && retry.maxAttempts !== 1 && invalid("retry.maxAttempts");
5959
6005
  let assets = v.assets === void 0 ? [] : v.assets;
@@ -5969,7 +6015,7 @@ function parseRoutineDeclaration(value) {
5969
6015
  runtime: {
5970
6016
  features: [],
5971
6017
  resources: "standard",
5972
- maxDuration: runtime.maxDuration ?? "60m"
6018
+ maxDuration: runtime2.maxDuration ?? "60m"
5973
6019
  },
5974
6020
  retry: { maxAttempts: 1 },
5975
6021
  assets: [...assets].sort()
@@ -6403,8 +6449,8 @@ var schema = {
6403
6449
  steps: Object.freeze(executable),
6404
6450
  responses: Object.freeze(responses.map((handler) => defineHandler({
6405
6451
  ...handler,
6406
- async run(context, runtime) {
6407
- let active2 = !0, capabilities = runtime ? createCapabilityRuntime(contract, runtime, () => active2, "Response") : void 0;
6452
+ async run(context, runtime2) {
6453
+ let active2 = !0, capabilities = runtime2 ? createCapabilityRuntime(contract, runtime2, () => active2, "Response") : void 0;
6408
6454
  try {
6409
6455
  return await handler.run(context, capabilities?.os);
6410
6456
  } catch (error) {
@@ -6437,11 +6483,11 @@ function captureRoutineInput(definition, input) {
6437
6483
  let contract = inspectRoutineDefinition(definition);
6438
6484
  return capture2(contract.input, input === void 0 && Object.hasOwn(contract, "inputDefault") ? contract.inputDefault : input);
6439
6485
  }
6440
- function createCapabilityRuntime(contract, runtime, current2, owner) {
6486
+ function createCapabilityRuntime(contract, runtime2, current2, owner) {
6441
6487
  let aiWork = /* @__PURE__ */ new Set(), generate = (kind, value) => {
6442
6488
  let operation2 = (async () => {
6443
6489
  if (!current2() || contract.access.ai !== !0) throw new AIError("access_denied");
6444
- if (!runtime.ai) throw new AIError("capability_unavailable");
6490
+ if (!runtime2.ai) throw new AIError("capability_unavailable");
6445
6491
  let request3;
6446
6492
  try {
6447
6493
  assertRoutineFields(value, kind === "generateObject" ? ["instructions", "input", "schema", "tools"] : ["instructions", "input", "tools"]), request3 = parseRoutineAIRequest({
@@ -6454,7 +6500,7 @@ function createCapabilityRuntime(contract, runtime, current2, owner) {
6454
6500
  } catch (error) {
6455
6501
  throw error instanceof AIError ? error : new AIError("invalid_input");
6456
6502
  }
6457
- let result2 = await runtime.ai[kind](request3);
6503
+ let result2 = await runtime2.ai[kind](request3);
6458
6504
  if (!current2()) throw new AIError("access_denied");
6459
6505
  return parseRoutineAIResult(request3, result2);
6460
6506
  })();
@@ -6473,35 +6519,35 @@ function createCapabilityRuntime(contract, runtime, current2, owner) {
6473
6519
  return value;
6474
6520
  };
6475
6521
  return { os: Object.freeze({ ...guarded({
6476
- data: runtime.data,
6477
- files: runtime.files,
6522
+ data: runtime2.data,
6523
+ files: runtime2.files,
6478
6524
  ai: {
6479
6525
  generateText: (value) => generate("generateText", value),
6480
6526
  generateObject: (value) => generate("generateObject", value)
6481
6527
  },
6482
- connections: { ...runtime.connections, get: async (identity) => {
6528
+ connections: { ...runtime2.connections, get: async (identity) => {
6483
6529
  if (!current2() || !contract.access.connections?.includes(identity)) throw new Error("Connection unavailable");
6484
- let value = await runtime.connections.get(identity);
6530
+ let value = await runtime2.connections.get(identity);
6485
6531
  if (!current2()) throw new Error(`${owner} authority ended`);
6486
6532
  return value;
6487
6533
  } },
6488
- inbox: { ...runtime.inbox, publishAsk: (value, options) => runtime.inbox.publishAsk(validateHandlers(value), options) }
6534
+ inbox: { ...runtime2.inbox, publishAsk: (value, options) => runtime2.inbox.publishAsk(validateHandlers(value), options) }
6489
6535
  }) }), guarded, async drain() {
6490
6536
  for (; aiWork.size; ) await Promise.allSettled([...aiWork]);
6491
6537
  } };
6492
6538
  }
6493
- async function executeRoutineDefinition(definition, input, runtime) {
6494
- let captured = captureRoutineInput(definition, input), { contract, steps, run } = definitions.get(definition), active2 = !0, accepting = !0, broken = !1, outputFailure, work = Promise.resolve(), capabilities = createCapabilityRuntime(contract, runtime, () => active2 && !broken, "Run"), called = /* @__PURE__ */ new Set(), reached = /* @__PURE__ */ new Set(), activeStep, progress2 = /* @__PURE__ */ new Map(), os2 = Object.freeze({
6539
+ async function executeRoutineDefinition(definition, input, runtime2) {
6540
+ let captured = captureRoutineInput(definition, input), { contract, steps, run } = definitions.get(definition), active2 = !0, accepting = !0, broken = !1, outputFailure, work = Promise.resolve(), capabilities = createCapabilityRuntime(contract, runtime2, () => active2 && !broken, "Run"), called = /* @__PURE__ */ new Set(), reached = /* @__PURE__ */ new Set(), activeStep, progress2 = /* @__PURE__ */ new Map(), os2 = Object.freeze({
6495
6541
  ...capabilities.os,
6496
6542
  ...capabilities.guarded({
6497
- run: freezeRoutineMetadata({ id: runtime.run.id, async progress(value) {
6543
+ run: freezeRoutineMetadata({ id: runtime2.run.id, async progress(value) {
6498
6544
  assertRoutineFields(value, ["completed", "total"]);
6499
6545
  let { completed: completed2, total } = value, prior = activeStep ? progress2.get(activeStep) : void 0;
6500
6546
  if (!active2 || broken || !activeStep || !Number.isSafeInteger(completed2) || !Number.isSafeInteger(total) || completed2 < 1 || completed2 > total || prior && (prior.total !== total || completed2 <= prior.completed)) return invalid3();
6501
6547
  let accepted = freezeRoutineMetadata({ step: activeStep, completed: completed2, total });
6502
- await runtime.run.progress(accepted), progress2.set(activeStep, accepted);
6548
+ await runtime2.run.progress(accepted), progress2.set(activeStep, accepted);
6503
6549
  } }),
6504
- ...runtime.artifact ? { artifact: runtime.artifact } : {}
6550
+ ...runtime2.artifact ? { artifact: runtime2.artifact } : {}
6505
6551
  }),
6506
6552
  step(id3, ...input2) {
6507
6553
  let saved;
@@ -6515,13 +6561,13 @@ async function executeRoutineDefinition(definition, input, runtime) {
6515
6561
  if (broken) return invalid3();
6516
6562
  reached.add(id3);
6517
6563
  try {
6518
- await runtime.step(id3, { status: "running" }), activeStep = id3;
6564
+ await runtime2.step(id3, { status: "running" }), activeStep = id3;
6519
6565
  let output = await steps[id3].run(saved, os2);
6520
6566
  if (assertRoutineFields(output, ["summary", "data"]), !Object.hasOwn(output, "summary") || !Object.hasOwn(output, "data")) return invalid3();
6521
6567
  let { summary: summary3, data: data3 } = captureRoutineStepOutput(id3, output.summary, output.data);
6522
- return await runtime.step(id3, { status: "completed", summary: summary3, data: data3 }), activeStep = void 0, freezeRoutineMetadata({ summary: summary3, data: data3 });
6568
+ return await runtime2.step(id3, { status: "completed", summary: summary3, data: data3 }), activeStep = void 0, freezeRoutineMetadata({ summary: summary3, data: data3 });
6523
6569
  } catch (error) {
6524
- throw error instanceof RoutineStepOutputError && (outputFailure ??= error), broken = !0, activeStep = void 0, await runtime.step(id3, { status: "failed" }), error;
6570
+ throw error instanceof RoutineStepOutputError && (outputFailure ??= error), broken = !0, activeStep = void 0, await runtime2.step(id3, { status: "failed" }), error;
6525
6571
  }
6526
6572
  });
6527
6573
  return work = next.then(() => {
@@ -6537,7 +6583,7 @@ async function executeRoutineDefinition(definition, input, runtime) {
6537
6583
  }
6538
6584
  accepting = !1, await work, await capabilities.drain(), active2 = !1;
6539
6585
  try {
6540
- for (let step of contract.steps) reached.has(step.id) || await runtime.step(step.id, { status: "skipped" });
6586
+ for (let step of contract.steps) reached.has(step.id) || await runtime2.step(step.id, { status: "skipped" });
6541
6587
  } catch (error) {
6542
6588
  throw outputFailure ?? error;
6543
6589
  }
@@ -7164,6 +7210,9 @@ function installMemberContext(resolve, retained = resolve, inbox2 = resolve) {
7164
7210
  memberContext === resolve && (memberLifetime?.abort(), memberContext = void 0, retainedContext = void 0, inboxContext = void 0);
7165
7211
  };
7166
7212
  }
7213
+ function memberContextSignal() {
7214
+ return memberLifetime?.signal;
7215
+ }
7167
7216
  async function resolveAppContext(retained = !1, inbox2 = !1) {
7168
7217
  let host = memberContext;
7169
7218
  if (!host) throw new Error("App context unavailable.");
@@ -8215,15 +8264,15 @@ function applySnapshotMutation(envelope, prior, mutation, installation) {
8215
8264
 
8216
8265
  var unavailable2 = () => {
8217
8266
  throw new DataOperationError("unavailable", !0);
8218
- };
8267
+ }, cacheUnavailable = () => new DataOperationError("unavailable", !0, void 0, "snapshot_cache");
8219
8268
  function request(value) {
8220
8269
  return new Promise((resolve, reject) => {
8221
- value.onsuccess = () => resolve(value.result), value.onerror = () => reject(new DataOperationError("unavailable", !0));
8270
+ value.onsuccess = () => resolve(value.result), value.onerror = () => reject(cacheUnavailable());
8222
8271
  });
8223
8272
  }
8224
8273
  function completed(transaction) {
8225
8274
  let done = new Promise((resolve, reject) => {
8226
- transaction.oncomplete = () => resolve(), transaction.onabort = transaction.onerror = () => reject(new DataOperationError("unavailable", !0));
8275
+ transaction.oncomplete = () => resolve(), transaction.onabort = transaction.onerror = () => reject(cacheUnavailable());
8227
8276
  });
8228
8277
  return done.catch(() => {
8229
8278
  }), done;
@@ -8242,28 +8291,54 @@ async function openSnapshotStore() {
8242
8291
  close() {
8243
8292
  database.close();
8244
8293
  },
8294
+ async compact() {
8295
+ let transaction = database.transaction(["current", "records", "changes", "bases"], "readwrite"), done = completed(transaction);
8296
+ try {
8297
+ let pointers = transaction.objectStore("current"), current2 = [];
8298
+ for (let key of await request(pointers.getAllKeys())) {
8299
+ let value = await request(pointers.get(key));
8300
+ value && current2.push(value);
8301
+ }
8302
+ let installationIds = new Set(current2.map((value) => value.id).filter(Boolean)), recordIds = new Set(current2.map((value) => value.recordsId ?? value.id).filter(Boolean)), artifactTokens = new Set(current2.map((value) => value.artifactToken).filter(Boolean)), changes = transaction.objectStore("changes"), stale2 = (await request(changes.getAllKeys())).filter((key) => typeof key == "string" && !installationIds.has(key));
8303
+ for (let id3 of stale2)
8304
+ changes.delete(id3), recordIds.has(id3) || transaction.objectStore("records").delete(IDBKeyRange.bound([id3], [id3, []]));
8305
+ let bases = transaction.objectStore("bases");
8306
+ for (let key of await request(bases.getAllKeys()))
8307
+ typeof key == "string" && !artifactTokens.has(key) && bases.delete(key);
8308
+ await done;
8309
+ } catch (error) {
8310
+ try {
8311
+ transaction.abort();
8312
+ } catch {
8313
+ }
8314
+ throw await done.catch(() => {
8315
+ }), error;
8316
+ }
8317
+ },
8245
8318
  async current(partition) {
8246
8319
  let transaction = database.transaction(["current", "records", "changes", "bases"], "readonly"), done = completed(transaction), value = await request(transaction.objectStore("current").get(partition));
8247
8320
  if (!value) {
8248
8321
  await done;
8249
8322
  return;
8250
8323
  }
8251
- if (value.format !== "data-snapshot.v2" || !Array.isArray(value.timelineCollections) || value.partition !== partition || !value.id || !value.snapshotId || value.pairToken !== "" && !validSnapshotPairToken(value.pairToken) || !validSnapshotArtifactToken(value.artifactToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
8324
+ let recordsId = value.recordsId ?? value.id;
8325
+ if (value.format !== "data-snapshot.v2" || !Array.isArray(value.timelineCollections) || value.partition !== partition || !value.id || !recordsId || !value.snapshotId || value.pairToken !== "" && !validSnapshotPairToken(value.pairToken) || !validSnapshotArtifactToken(value.artifactToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
8252
8326
  await done;
8253
8327
  return;
8254
8328
  }
8255
8329
  let changes = await request(transaction.objectStore("changes").get(value.id)), complete = !!await request(transaction.objectStore("bases").getKey(value.artifactToken)) && Array.isArray(changes) && changes.length === value.changeCount;
8256
8330
  for (let collection of value.catalogue)
8257
- await request(transaction.objectStore("records").index("collection").count([value.id, collection.name])) !== value.counts[collection.name] && (complete = !1);
8258
- return await done, complete ? value : void 0;
8331
+ await request(transaction.objectStore("records").index("collection").count([recordsId, collection.name])) !== value.counts[collection.name] && (complete = !1);
8332
+ return await done, complete ? { ...value, recordsId } : void 0;
8259
8333
  },
8260
8334
  async base(installation) {
8261
8335
  let transaction = database.transaction("bases", "readonly"), done = completed(transaction), base = await request(transaction.objectStore("bases").get(installation.artifactToken));
8262
8336
  return await done, base;
8263
8337
  },
8264
8338
  async install(partition, pairToken, envelope, changes, assertCurrent, snapshotId, artifact, unchangedRecords) {
8265
- let installation = {
8266
- id: crypto.randomUUID(),
8339
+ let id3 = crypto.randomUUID(), recordsId = unchangedRecords?.recordsId ?? id3, installation = {
8340
+ id: id3,
8341
+ recordsId,
8267
8342
  partition,
8268
8343
  pairToken,
8269
8344
  version: envelope.version,
@@ -8283,8 +8358,8 @@ async function openSnapshotStore() {
8283
8358
  try {
8284
8359
  assertCurrent(), transaction.objectStore("bases").put(artifact.base, artifact.token);
8285
8360
  let records = transaction.objectStore("records");
8286
- for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
8287
- records.put({ installation: installation.id, collection, ref: record4.$ref, record: record4 });
8361
+ if (!unchangedRecords) for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
8362
+ records.put({ installation: recordsId, collection, ref: record4.$ref, record: record4 });
8288
8363
  return await request(transaction.objectStore("changes").put(changes, installation.id)), await request(transaction.objectStore("current").put(installation, partition)), assertCurrent(), await done, assertCurrent(), installation;
8289
8364
  } catch (error) {
8290
8365
  try {
@@ -8306,7 +8381,7 @@ async function openSnapshotStore() {
8306
8381
  let records = transaction.objectStore("records"), collections = {}, prior = await request(transaction.objectStore("changes").get(installation.id));
8307
8382
  if (!prior || prior.length !== installation.changeCount) return unavailable2();
8308
8383
  for (let c of installation.catalogue) {
8309
- let rows = await request(records.index("collection").getAll([installation.id, c.name]));
8384
+ let rows = await request(records.index("collection").getAll([installation.recordsId, c.name]));
8310
8385
  if (rows.length !== installation.counts[c.name]) return unavailable2();
8311
8386
  collections[c.name] = rows.map((r) => r.record);
8312
8387
  }
@@ -8319,17 +8394,18 @@ async function openSnapshotStore() {
8319
8394
  timelineCollections: installation.timelineCollections,
8320
8395
  catalogue: installation.catalogue,
8321
8396
  collections
8322
- }, prior, mutation, installation), id3 = crypto.randomUUID(), next = {
8397
+ }, prior, mutation, installation), id3 = crypto.randomUUID(), recordsId = mutation.kind === "publish" ? id3 : installation.recordsId, next = {
8323
8398
  ...installation,
8324
8399
  id: id3,
8400
+ recordsId,
8325
8401
  pairToken: "",
8326
8402
  version: envelope.version,
8327
8403
  queryIdentity: mutation.kind === "publish" ? id3 : installation.queryIdentity ?? installation.id,
8328
8404
  changeCount: changes.length,
8329
8405
  counts: Object.fromEntries(Object.entries(envelope.collections).map(([name2, rows]) => [name2, rows.length]))
8330
8406
  };
8331
- for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
8332
- records.put({ installation: id3, collection, ref: record4.$ref, record: record4 });
8407
+ if (mutation.kind === "publish") for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
8408
+ records.put({ installation: recordsId, collection, ref: record4.$ref, record: record4 });
8333
8409
  return transaction.objectStore("changes").put(changes, id3), (await request(transaction.objectStore("current").get(installation.partition)))?.id === installation.id && transaction.objectStore("current").put(next, installation.partition), assertCurrent(), await done, assertCurrent(), next;
8334
8410
  } catch (error) {
8335
8411
  try {
@@ -8341,7 +8417,7 @@ async function openSnapshotStore() {
8341
8417
  }
8342
8418
  },
8343
8419
  async read(installation, ref) {
8344
- let transaction = database.transaction("records", "readonly"), done = completed(transaction), row = await request(transaction.objectStore("records").get([installation.id, ref])), collection = snapshotCollection(installation.catalogue, ref).name, count = await request(transaction.objectStore("records").index("collection").count([installation.id, collection]));
8420
+ let transaction = database.transaction("records", "readonly"), done = completed(transaction), row = await request(transaction.objectStore("records").get([installation.recordsId, ref])), collection = snapshotCollection(installation.catalogue, ref).name, count = await request(transaction.objectStore("records").index("collection").count([installation.recordsId, collection]));
8345
8421
  return await done, count !== installation.counts[collection] ? unavailable2() : row?.record ?? null;
8346
8422
  },
8347
8423
  async changes(installation) {
@@ -8369,11 +8445,11 @@ async function openSnapshotStore() {
8369
8445
  for (; !step.done; ) {
8370
8446
  let work = step.value, value;
8371
8447
  if (work.operation === "scan") {
8372
- let rows = await request(records().index("collection").getAll([installation.id, work.collection]));
8448
+ let rows = await request(records().index("collection").getAll([installation.recordsId, work.collection]));
8373
8449
  if (rows.length !== installation.counts[work.collection]) return unavailable2();
8374
8450
  value = rows.map((row) => row.record);
8375
8451
  } else if (work.operation === "lookup") {
8376
- let row = await request(records().get([installation.id, work.ref]));
8452
+ let row = await request(records().get([installation.recordsId, work.ref]));
8377
8453
  value = row && { record: row.record, collection: row.collection };
8378
8454
  } else if (await finish(), work.operation === "seal") {
8379
8455
  let iv = crypto.getRandomValues(new Uint8Array(12)), sealed = new Uint8Array(await crypto.subtle.encrypt(
@@ -8470,22 +8546,30 @@ async function acquireSnapshot(store, partition, url, headers, repository, snaps
8470
8546
  version = `snapshot-${Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
8471
8547
  }
8472
8548
  let materialized = materializeSnapshot(base, acquired.changes, version);
8473
- return assertCurrent(), { installation: await store.install(
8549
+ assertCurrent();
8550
+ let artifactBase = base, install = () => store.install(
8474
8551
  partition,
8475
8552
  pairToken,
8476
8553
  materialized,
8477
8554
  acquired.changes,
8478
8555
  assertCurrent,
8479
8556
  acquired.snapshot.id,
8480
- { token: artifactToken, base },
8557
+ { token: artifactToken, base: artifactBase },
8481
8558
  update.records ? void 0 : reusable
8482
- ), update };
8559
+ ), installation;
8560
+ try {
8561
+ installation = await install();
8562
+ } catch (error) {
8563
+ if (!(error instanceof DataOperationError) || error.component !== "snapshot_cache") throw error;
8564
+ await store.compact(), assertCurrent(), installation = await install();
8565
+ }
8566
+ return { installation, update };
8483
8567
  }
8484
8568
  unavailable3();
8485
8569
  }
8486
8570
 
8487
8571
  function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile, connect) {
8488
- let listeners = /* @__PURE__ */ new Set(), session, socket, retry, expiry, stopAuthority, stopCredentials, delay = 250, stop = () => {
8572
+ let listeners = /* @__PURE__ */ new Set(), session, socket, retry, expiry, stopAuthority, stopCredentials, pending = { records: !1, changes: !1 }, delay = 250, stop = () => {
8489
8573
  session?.abort(), session = void 0;
8490
8574
  let prior = socket;
8491
8575
  socket = void 0, prior?.close(), clearTimeout(retry), clearTimeout(expiry), retry = expiry = void 0, stopAuthority?.(), stopAuthority = void 0, stopCredentials?.(), stopCredentials = void 0;
@@ -8496,7 +8580,12 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
8496
8580
  return stop(), !1;
8497
8581
  }
8498
8582
  }, notify = (update) => {
8499
- if (!(!update.records && !update.changes || !current2()))
8583
+ if (!(!update.records && !update.changes || !current2())) {
8584
+ if (!listeners.size) {
8585
+ pending = { records: pending.records || update.records, changes: pending.changes || update.changes };
8586
+ return;
8587
+ }
8588
+ update = { records: pending.records || update.records, changes: pending.changes || update.changes }, pending = { records: !1, changes: !1 };
8500
8589
  for (let listener of [...listeners]) {
8501
8590
  if (!current2()) break;
8502
8591
  if (listeners.has(listener))
@@ -8505,6 +8594,7 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
8505
8594
  } catch {
8506
8595
  }
8507
8596
  }
8597
+ }
8508
8598
  }, start = () => {
8509
8599
  if (!listeners.size || !current2()) return;
8510
8600
  let owned = new AbortController();
@@ -8531,7 +8621,7 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
8531
8621
  }
8532
8622
  } catch (error) {
8533
8623
  if (session !== owned) return;
8534
- error instanceof DataOperationError && ["context_unavailable", "unauthenticated", "access_denied", "not_found"].includes(error.code) ? lostAuthority() : reconnect(socket);
8624
+ error instanceof DataOperationError && (["context_unavailable", "unauthenticated", "access_denied", "not_found"].includes(error.code) || error.component === "snapshot_cache") ? lostAuthority() : reconnect(socket);
8535
8625
  } finally {
8536
8626
  running = !1;
8537
8627
  }
@@ -8579,7 +8669,17 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
8579
8669
  subscribe(listener) {
8580
8670
  if (assertCurrent(), typeof listener != "function") throw new DataOperationError("invalid_query");
8581
8671
  let owned = (update) => listener(update);
8582
- return listeners.add(owned), listeners.size === 1 && start(), () => {
8672
+ if (listeners.add(owned), listeners.size === 1 && start(), pending.records || pending.changes) {
8673
+ let update = pending;
8674
+ pending = { records: !1, changes: !1 }, queueMicrotask(() => {
8675
+ if (!(!listeners.has(owned) || !current2()))
8676
+ try {
8677
+ owned({ ...update });
8678
+ } catch {
8679
+ }
8680
+ });
8681
+ }
8682
+ return () => {
8583
8683
  listeners.delete(owned), listeners.size || stop();
8584
8684
  };
8585
8685
  }
@@ -8655,7 +8755,7 @@ function captureSnapshotAll(query, options) {
8655
8755
  }
8656
8756
  var safeName = (value) => typeof value == "string" && /^[a-z0-9][a-z0-9._-]{0,127}$/.test(value) && !value.includes("..");
8657
8757
  function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore, connect = (url, protocols) => new WebSocket(url, protocols)) {
8658
- let pending = /* @__PURE__ */ new WeakMap();
8758
+ let pending = /* @__PURE__ */ new WeakMap(), maintenance = /* @__PURE__ */ new WeakMap();
8659
8759
  return async function(input) {
8660
8760
  let properties = dataProperties(input), repository = properties.repository?.value, snapshot = properties.snapshot?.value;
8661
8761
  if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid11();
@@ -8682,11 +8782,22 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8682
8782
  } catch (error) {
8683
8783
  throw assertCurrent(), error instanceof DataOperationError ? error : new DataOperationError("unavailable", !0);
8684
8784
  }
8785
+ let compacted = maintenance.get(authority2.binding);
8786
+ compacted || (compacted = (async () => {
8787
+ let store = await open();
8788
+ try {
8789
+ await store.compact();
8790
+ } finally {
8791
+ store.close();
8792
+ }
8793
+ })(), maintenance.set(authority2.binding, compacted), compacted.catch(() => {
8794
+ }));
8685
8795
  let installation;
8686
8796
  if (cached) installation = cached;
8687
8797
  else {
8688
8798
  let installing = work.get(partition);
8689
8799
  installing || (installing = (async () => {
8800
+ await compacted;
8690
8801
  let store = await open();
8691
8802
  try {
8692
8803
  return (await acquireSnapshot(
@@ -8722,7 +8833,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8722
8833
  return writes = result2.catch(() => {
8723
8834
  }), result2;
8724
8835
  }, reconcile = (signal) => serial(async () => {
8725
- await ensureAccess();
8836
+ await compacted, await ensureAccess();
8726
8837
  let headers = authority2.headers, fenced = () => {
8727
8838
  if (assertAccess(), signal.aborted || headers.authorization !== authority2.headers.authorization) throw new DataOperationError("unavailable", !0);
8728
8839
  };
@@ -8750,13 +8861,13 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8750
8861
  if (stopLive = live2.stop, cached) {
8751
8862
  let refresh2 = reconcile(authority2.signal);
8752
8863
  initialRefresh = refresh2, refresh2.then(live2.notify).catch((error) => {
8753
- error instanceof DataOperationError && ["context_unavailable", "unauthenticated", "access_denied", "not_found"].includes(error.code) && (invalidated = !0, live2.stop());
8864
+ error instanceof DataOperationError && (["context_unavailable", "unauthenticated", "access_denied", "not_found"].includes(error.code) || error.component === "snapshot_cache") && (invalidated = !0, live2.stop());
8754
8865
  }).finally(() => {
8755
8866
  initialRefresh === refresh2 && (initialRefresh = void 0);
8756
8867
  });
8757
8868
  }
8758
8869
  let publications = /* @__PURE__ */ new Map(), mutate = async (kind, payload, selected, publication) => {
8759
- if (await ensureAccess(), publication?.complete) return [];
8870
+ if (await compacted, await ensureAccess(), publication?.complete) return [];
8760
8871
  let body = { snapshotId: installation.snapshotId, ...payload };
8761
8872
  checkDataRequestSize(body, 2 * 1024 * 1024);
8762
8873
  let dispatched = !1, applied = !1, store;
@@ -8769,7 +8880,10 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8769
8880
  headers: { ...authority2.headers, "content-type": "application/json" },
8770
8881
  body: JSON.stringify(body)
8771
8882
  });
8772
- if (!response2.ok) throw dataTransportError(response2.status, await response2.json());
8883
+ if (!response2.ok) {
8884
+ let failure = dataTransportError(response2.status, await response2.json());
8885
+ throw publication && failure.effect === "unapplied" && (publication.id = crypto.randomUUID()), failure;
8886
+ }
8773
8887
  applied = !0;
8774
8888
  let value = await response2.json(), mutation;
8775
8889
  if (kind === "discard") {
@@ -8791,15 +8905,15 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8791
8905
  let update = snapshotDifference(before, await store.changes(installation));
8792
8906
  return kind === "publish" && (update.records = !0), assertAccess(), publication && (publication.complete = !0), live2.notify(update), assertAccess(), structuredClone(mutation.changes ?? []);
8793
8907
  } catch (error) {
8794
- let failure = error instanceof DataOperationError ? error : new DataOperationError("unavailable"), effect = applied ? "applied" : dispatched ? failure.effect ?? "uncertain" : "unapplied";
8908
+ let failure = error instanceof DataOperationError ? error : new DataOperationError("unavailable", dispatched && kind === "publish"), effect = applied ? "applied" : dispatched ? failure.effect ?? "uncertain" : "unapplied";
8795
8909
  throw effect !== "unapplied" && (kind !== "publish" || effect === "applied") && (invalidated = !0, live2.stop(), await store?.invalidate(installation).catch(() => {
8796
- })), new DataOperationError(
8910
+ })), explainDataValidation(new DataOperationError(
8797
8911
  failure.code,
8798
- effect === "uncertain" ? kind === "publish" : effect === "applied" ? !1 : failure.retryable,
8912
+ effect === "uncertain" ? kind === "publish" && failure.retryable : effect === "applied" ? !1 : failure.retryable,
8799
8913
  effect,
8800
8914
  failure.component,
8801
8915
  failure.detail
8802
- );
8916
+ ), failure.message, failure.detail);
8803
8917
  } finally {
8804
8918
  store?.close();
8805
8919
  }
@@ -9445,7 +9559,8 @@ var files = {
9445
9559
  } finally {
9446
9560
  release();
9447
9561
  }
9448
- return metadata.size > MAX_BYTES ? multipartCreate(input, metadata, (suffix, init2, kind, signal) => kind === !0 ? send(suffix, init2, !0, context, signal) : send(suffix, init2, "control", context, signal), release) : timed(async (signal) => {
9562
+ if (metadata.size > MAX_BYTES) return multipartCreate(input, metadata, (suffix, init2, kind, signal) => kind === !0 ? send(suffix, init2, !0, context, signal) : send(suffix, init2, "control", context, signal), release);
9563
+ let execute = async (signal) => {
9449
9564
  try {
9450
9565
  let bytes = array3 ? new Uint8Array(input.file) : await boundedBytes(
9451
9566
  blob ? input.file.stream() : input.file,
@@ -9467,7 +9582,8 @@ var files = {
9467
9582
  } finally {
9468
9583
  release();
9469
9584
  }
9470
- }, context.signal).catch((error) => {
9585
+ };
9586
+ return (context.localFiles ? execute(context.signal ?? new AbortController().signal) : timed(execute, context.signal)).catch((error) => {
9471
9587
  throw error instanceof FileOperationError ? error : unavailable4();
9472
9588
  });
9473
9589
  },
@@ -10028,6 +10144,14 @@ var source = {
10028
10144
  }
10029
10145
  };
10030
10146
 
10147
+ function parseInboxLiveSetup(value) {
10148
+ let v = value;
10149
+ if (!v || Object.keys(v).sort().join(",") !== "expiresAt,key,token,topic,url,viewerId,workspaceId" || !INBOX_UUID.test(v.workspaceId) || !INBOX_UUID.test(v.viewerId) || v.topic !== `inbox:${v.workspaceId}:${v.viewerId}` || typeof v.key != "string" || !v.key || typeof v.token != "string" || !/^[A-Za-z0-9._-]{1,8192}$/.test(v.token) || !Number.isSafeInteger(v.expiresAt) || v.expiresAt <= Date.now()) throw new Error("Invalid Inbox subscription");
10150
+ let url = new URL(v.url);
10151
+ if (url.protocol !== "wss:" || url.username || url.password || url.search || url.hash || url.pathname !== "/realtime/v1/websocket") throw new Error("Invalid Inbox subscription");
10152
+ return v;
10153
+ }
10154
+
10031
10155
  function parseInboxRecordRefs(value) {
10032
10156
  let refs = serializable(value);
10033
10157
  if (!Array.isArray(refs) || !refs.length || refs.length > 100) throw new Error("Invalid Record read");
@@ -10036,10 +10160,15 @@ function parseInboxRecordRefs(value) {
10036
10160
  return result2;
10037
10161
  }
10038
10162
  var recordKey = ({ repository, ref }) => JSON.stringify([repository, ref]);
10039
- function parseInboxRecords(value) {
10040
- let result2 = serializable(value);
10041
- if (!result2 || Object.keys(result2).join() !== "records" || !Array.isArray(result2.records) || result2.records.length > 100) throw new Error("Invalid Record result");
10163
+ function authoredInboxRecordRefs(body) {
10164
+ let refs = body.flatMap((block) => block.kind === "record" ? [block.record] : block.kind === "records" ? block.records : []);
10165
+ return [...new Map(refs.map((ref) => [recordKey(ref), ref])).values()];
10166
+ }
10167
+ function parseInboxRecords(value, maximumRecords = 100) {
10168
+ let result2 = serializable(value), keys7 = result2 ? Object.keys(result2).sort().join() : "";
10169
+ if (!result2 || !["records", "links,records"].includes(keys7) || !Array.isArray(result2.records) || result2.records.length > maximumRecords) throw new Error("Invalid Record result");
10042
10170
  for (let entry of result2.records) {
10171
+ if (!entry || typeof entry != "object") throw new Error("Invalid current Record");
10043
10172
  if (validateQualifiedRecordRef({ repository: entry.repository, ref: entry.ref }), Object.keys(entry).sort().join() !== "record,ref,repository,schema" || (entry.record === null ? entry.schema !== null : !entry.schema || entry.record.$ref !== entry.ref || typeof entry.record.$version != "string" || !Array.isArray(entry.schema.fields) || typeof entry.schema.name != "string"))
10044
10173
  throw new Error("Invalid current Record");
10045
10174
  if (entry.schema)
@@ -10051,7 +10180,14 @@ function parseInboxRecords(value) {
10051
10180
  }
10052
10181
  }
10053
10182
  if (new Set(result2.records.map(recordKey)).size !== result2.records.length) throw new Error("Duplicate current Record");
10054
- return result2;
10183
+ let links = keys7 === "records" ? [] : result2.links;
10184
+ if (!Array.isArray(links)) throw new Error("Invalid Record links");
10185
+ for (let link of links) {
10186
+ if (!link || typeof link != "object" || Object.keys(link).sort().join() !== "ref,repository,title" || typeof link.title != "string" || !link.title.trim()) throw new Error("Invalid Record link");
10187
+ validateQualifiedRecordRef({ repository: link.repository, ref: link.ref });
10188
+ }
10189
+ if (new Set(links.map(recordKey)).size !== links.length) throw new Error("Duplicate Record link");
10190
+ return { records: result2.records, links };
10055
10191
  }
10056
10192
 
10057
10193
  var InboxOperationError = class extends Error {
@@ -10096,12 +10232,14 @@ function parseInboxUnavailableFailure(value, status) {
10096
10232
  return;
10097
10233
  }
10098
10234
  }
10099
- var INBOX_RESULT_BYTES = 8 * 1024 * 1024, INBOX_INPUT_BYTES = 8192, INBOX_LOCAL_INPUT_BYTES = 256 * 1024, INBOX_QUESTION_CONTRACT = "question-work-v1", INBOX_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
10235
+ var INBOX_RESULT_BYTES = 8 * 1024 * 1024, INBOX_INPUT_BYTES = 8192, INBOX_LOCAL_INPUT_BYTES = 256 * 1024, INBOX_QUESTION_CONTRACT = "question-work-v2", INBOX_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
10100
10236
  function isAppQuestionOperation(operation2) {
10101
10237
  return operation2 === "questions.list" || operation2 === "questions.answer" || operation2 === "questions.listRecordOptions";
10102
10238
  }
10103
10239
  var operations = {
10104
10240
  current: [],
10241
+ bootstrap: [],
10242
+ "live.connect": [],
10105
10243
  "items.list": [],
10106
10244
  "questions.list": [],
10107
10245
  "items.read": ["itemId"],
@@ -10161,21 +10299,58 @@ function recordReference(value) {
10161
10299
  let record4 = object8(value);
10162
10300
  return keys6(record4, ["repository", "ref"]), assert(text4(record4.repository) && record4.repository === record4.repository.trim() && /^[a-z0-9][a-z0-9._/-]{0,127}$/.test(record4.repository) && !/\.\.|\/\//.test(record4.repository) && text4(record4.ref) && record4.ref === record4.ref.trim() && record4.ref.length <= 512 && /^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(record4.ref)), record4;
10163
10301
  }
10302
+ function choiceValue(value) {
10303
+ assert(text4(value) && value === value.trim());
10304
+ }
10305
+ function choiceDetails(option) {
10306
+ if ("description" in option && assert(text4(option.description)), "note" in option) {
10307
+ let note = object8(option.note);
10308
+ keys6(note, ["placeholder"]), assert(text4(note.placeholder));
10309
+ }
10310
+ }
10311
+ function pickerSource(value) {
10312
+ let source2 = object8(value), collection = object8(source2.collection);
10313
+ keys6(collection, ["repository", "name"]), recordReference({ repository: collection.repository, ref: "records/example" }), assert(text4(collection.name) && /^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(collection.name)), "refPrefix" in source2 && assert(text4(source2.refPrefix) && source2.refPrefix.length <= 512 && /^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)*\/$/.test(source2.refPrefix));
10314
+ let where = object8(source2.where ?? {});
10315
+ return assert(Object.entries(where).every(([name2, value2]) => /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name2) && !["constructor", "prototype"].includes(name2) && (value2 === null || typeof value2 == "string" || typeof value2 == "boolean" || typeof value2 == "number" && Number.isFinite(value2)))), collection;
10316
+ }
10164
10317
  function responseDefinition(value) {
10165
10318
  let definition = object8(value);
10166
- keys6(definition, ["type", "source"]), assert(definition.type === "selection");
10319
+ if (assert(definition.type === "selection"), "options" in definition) {
10320
+ keys6(definition, ["type", "options"]);
10321
+ let options = array2(definition.options);
10322
+ assert(options.length > 0 && options.length <= 9), options.forEach((value2, index) => {
10323
+ let option = object8(value2);
10324
+ switch (assert(option.id === index + 1 && text4(option.label)), option.type) {
10325
+ case "choice":
10326
+ case "record":
10327
+ keys6(
10328
+ option,
10329
+ ["id", "type", "value", "label", "description", ...option.type === "choice" ? ["note"] : []],
10330
+ []
10331
+ ), option.type === "choice" ? choiceValue(option.value) : recordReference(option.value), choiceDetails(option);
10332
+ break;
10333
+ case "record-picker": {
10334
+ keys6(option, ["id", "type", "label", "source"]);
10335
+ let source3 = object8(option.source);
10336
+ keys6(source3, ["collection", "where", "refPrefix"], []), "where" in source3 && object8(source3.where), pickerSource(source3);
10337
+ break;
10338
+ }
10339
+ default:
10340
+ assert(!1);
10341
+ }
10342
+ });
10343
+ return;
10344
+ }
10345
+ keys6(definition, ["type", "source"]);
10167
10346
  let source2 = object8(definition.source);
10168
10347
  if (source2.type === "authored") {
10169
- keys6(source2, ["type", "options", "suggestions", "search"], ["type", "options"]);
10348
+ keys6(source2, ["type", "options", "suggestions", "search"], []);
10170
10349
  let options = array2(source2.options);
10171
10350
  assert(options.length > 0);
10172
10351
  let values = options.map((value2) => {
10173
10352
  let option = object8(value2);
10174
- if (keys6(option, ["value", "label", "description", "note"], ["value", "label"]), assert(text4(option.value) && option.value === option.value.trim() && text4(option.label)), "description" in option && assert(text4(option.description)), "note" in option) {
10175
- let note = object8(option.note);
10176
- keys6(note, ["placeholder"]), assert(text4(note.placeholder));
10177
- }
10178
- return option.value;
10353
+ return keys6(option, ["value", "label", "description", "note"], []), choiceValue(option.value), assert(text4(option.label)), choiceDetails(option), option.value;
10179
10354
  });
10180
10355
  if (assert(new Set(values).size === values.length), "search" in source2 || "suggestions" in source2) {
10181
10356
  let search = object8(source2.search);
@@ -10186,11 +10361,7 @@ function responseDefinition(value) {
10186
10361
  return;
10187
10362
  }
10188
10363
  assert(source2.type === "records"), keys6(source2, ["type", "collection", "refPrefix", "where", "display", "suggestions"], ["type", "collection", "display"]);
10189
- let collection = object8(source2.collection);
10190
- keys6(collection, ["repository", "name"]), recordReference({ repository: collection.repository, ref: "records/example" }), assert(text4(collection.name) && /^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(collection.name)), "refPrefix" in source2 && assert(text4(source2.refPrefix) && source2.refPrefix.length <= 512 && /^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)*\/$/.test(source2.refPrefix));
10191
- let where = object8(source2.where ?? {});
10192
- 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))));
10193
- let display = object8(source2.display);
10364
+ let collection = pickerSource(source2), display = object8(source2.display);
10194
10365
  keys6(display, ["labelFields"]);
10195
10366
  let labels = array2(display.labelFields);
10196
10367
  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)));
@@ -10202,22 +10373,32 @@ function responseDefinition(value) {
10202
10373
  });
10203
10374
  assert(suggestions.length <= 8 && new Set(refs).size === refs.length);
10204
10375
  }
10205
- function response(value) {
10206
- let answer = object8(value);
10207
- 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;
10376
+ function response(value, definition, numbered = !1) {
10377
+ let answer = object8(value), options = definition && "options" in definition ? array2(definition.options) : void 0, selected = options || numbered ? answer.value : answer.selection;
10378
+ if (typeof selected == "string" ? choiceValue(selected) : recordReference(selected), options || numbered) {
10379
+ if (keys6(answer, ["option", "value", "note"], []), assert(integer(answer.option) && answer.option <= (options?.length ?? 9)), options) {
10380
+ let option = object8(options[answer.option - 1]);
10381
+ assert(option.type === "choice" == (typeof selected == "string")), assert("note" in answer == (option.type === "choice" && "note" in option));
10382
+ }
10383
+ } else assert(Object.keys(answer).every((key) => ["selection", "note"].includes(key)));
10384
+ return Object.hasOwn(answer, "note") && assert(text4(answer.note)), answer;
10208
10385
  }
10209
10386
  function parseInboxRequest(value) {
10210
10387
  try {
10211
10388
  let envelope = object8(value);
10212
10389
  assert(typeof envelope.operation == "string" && Object.hasOwn(operations, envelope.operation));
10213
10390
  let operation2 = envelope.operation, questionOperation = isAppQuestionOperation(operation2);
10214
- if (questionOperation && envelope.contract !== INBOX_QUESTION_CONTRACT)
10391
+ if (questionOperation && envelope.contract !== INBOX_QUESTION_CONTRACT && envelope.contract !== "question-work-v1")
10215
10392
  throw new InboxOperationError(426, "client_update_required");
10216
10393
  keys6(envelope, questionOperation ? ["contract", "input", "operation"] : ["input", "operation"]);
10217
10394
  let input = { ...object8(envelope.input) }, required = operations[operation2];
10218
- assert(required.every((key) => Object.hasOwn(input, key)) && Object.keys(input).every((key) => required.includes(key) || operation2 === "questions.answer" && key === "label" || (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)));
10395
+ assert(required.every((key) => Object.hasOwn(input, key)) && Object.keys(input).every((key) => required.includes(key) || operation2 === "questions.answer" && key === "label" || operation2 === "questions.listRecordOptions" && envelope.contract === INBOX_QUESTION_CONTRACT && key === "option" || (operation2 === "items.list" || operation2 === "questions.list") && key === "beforeNumber" || operation2 === "questions.list" && key === "routines")), operation2 === "questions.list" && (assert(Object.hasOwn(input, "routines")), assert(array2(input.routines).every(isAppRoutineName)));
10219
10396
  for (let key of ["itemId", "personId", "fileId"]) key in input && assert(id2(input[key]));
10220
- return "revision" in input && assert(integer(input.revision)), "beforeNumber" in input && assert(integer(input.beforeNumber)), "questionId" in input && assert(text4(input.questionId) && input.questionId === input.questionId.trim()), "submissionKey" in input && assert(text4(input.submissionKey) && input.submissionKey.length <= 128 && input.submissionKey === input.submissionKey.trim()), "title" in input && assert(text4(input.title)), "lifecycle" in input && assert(input.lifecycle === "open" || input.lifecycle === "closed"), "records" in input && (input.records = parseInboxRecordRefs(input.records)), "response" in input && response(input.response), "label" in input && assert(text4(input.label) && typeof input.response?.selection == "object"), assert(new TextEncoder().encode(JSON.stringify(envelope)).byteLength <= INBOX_INPUT_BYTES), "routines" in input && (input.routines = [...new Set(input.routines)]), { operation: operation2, input, ...isAppQuestionOperation(operation2) ? { contract: INBOX_QUESTION_CONTRACT } : {} };
10397
+ if ("revision" in input && assert(integer(input.revision)), "beforeNumber" in input && assert(integer(input.beforeNumber)), "questionId" in input && assert(text4(input.questionId) && input.questionId === input.questionId.trim()), "submissionKey" in input && assert(text4(input.submissionKey) && input.submissionKey.length <= 128 && input.submissionKey === input.submissionKey.trim()), "title" in input && assert(text4(input.title)), "lifecycle" in input && assert(input.lifecycle === "open" || input.lifecycle === "closed"), "records" in input && (input.records = parseInboxRecordRefs(input.records)), "option" in input && assert(integer(input.option) && input.option <= 9), "response" in input && response(input.response, void 0, envelope.contract === INBOX_QUESTION_CONTRACT && "option" in object8(input.response)), "label" in input) {
10398
+ let answer = object8(input.response);
10399
+ assert(text4(input.label) && typeof ("option" in answer ? answer.value : answer.selection) == "object");
10400
+ }
10401
+ return assert(new TextEncoder().encode(JSON.stringify(envelope)).byteLength <= INBOX_INPUT_BYTES), "routines" in input && (input.routines = [...new Set(input.routines)]), { operation: operation2, input, ...isAppQuestionOperation(operation2) ? { contract: envelope.contract } : {} };
10221
10402
  } catch (error) {
10222
10403
  throw error instanceof InboxOperationError ? error : new InboxOperationError(400, "invalid_input");
10223
10404
  }
@@ -10241,7 +10422,7 @@ function parseInboxItem(value) {
10241
10422
  let question2 = object8(value2);
10242
10423
  if (assert(text4(question2.id) && id2(question2.to) && text4(question2.prompt) && (question2.instructions === null || text4(question2.instructions, !0)) && typeof question2.available == "boolean"), questionAvailability(question2, question2.available), parseQuestionStatus(question2.status), assert(!("requirements" in question2) && !("requirementsRepository" in question2) && !("handler" in question2)), responseDefinition(question2.response), assert(array2(question2.allowedResponders).every(id2)), question2.acceptedResponse !== null) {
10243
10424
  let accepted = object8(question2.acceptedResponse);
10244
- 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));
10425
+ assert(id2(accepted.id) && id2(accepted.userId) && date(accepted.acceptedAt)), response(accepted.response, object8(question2.response)), accepted.label === null ? delete accepted.label : "label" in accepted && assert(text4(accepted.label)), "acceptanceOrder" in accepted && assert(integer(accepted.acceptanceOrder));
10245
10426
  }
10246
10427
  if (question2.execution !== null) {
10247
10428
  let execution = object8(question2.execution);
@@ -10273,7 +10454,7 @@ function parseInboxItem(value) {
10273
10454
  assert(id2(work.id) && text4(work.questionId) && text4(work.reason) && optionalDate(work.settledAt));
10274
10455
  }), item;
10275
10456
  }
10276
- function parseQuestionWork(value) {
10457
+ function parseQuestionWork(value, contract = INBOX_QUESTION_CONTRACT) {
10277
10458
  let entry = object8(json2(value));
10278
10459
  keys6(
10279
10460
  entry,
@@ -10285,7 +10466,9 @@ function parseQuestionWork(value) {
10285
10466
  let assignee = object8(entry.assignee);
10286
10467
  keys6(assignee, ["id", "name"]), assert(id2(assignee.id) && text4(assignee.name));
10287
10468
  let status = parseQuestionStatus(entry.status);
10288
- return assert(status.code !== "completed" && (!entry.canAnswer || status.code === "awaiting_answer") && (!("unavailableReason" in entry) || status.code === "awaiting_answer")), status.code === "awaiting_answer" && assert(status.label === "Needs your answer" || !entry.canAnswer && status.label === `Waiting for ${assignee.name}`), responseDefinition(entry.response), askMetadata(entry), entry;
10469
+ if (assert(status.code !== "completed" && (!entry.canAnswer || status.code === "awaiting_answer") && (!("unavailableReason" in entry) || status.code === "awaiting_answer")), status.code === "awaiting_answer" && assert(status.label === "Needs your answer" || !entry.canAnswer && status.label === `Waiting for ${assignee.name}`), contract === "question-work-v1" && "options" in object8(entry.response))
10470
+ throw new InboxOperationError(426, "client_update_required");
10471
+ return responseDefinition(entry.response), askMetadata(entry), entry;
10289
10472
  }
10290
10473
  function parseQuestionStatus(value) {
10291
10474
  let status = object8(value), code = status.code;
@@ -10313,12 +10496,14 @@ function parseInboxAcceptance(value) {
10313
10496
  let accepted = object8(value);
10314
10497
  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;
10315
10498
  }
10316
- function parseInboxResult(operation2, value) {
10499
+ function parseInboxResult(operation2, value, contract = INBOX_QUESTION_CONTRACT) {
10317
10500
  if (operation2 === "current") return parseInboxCurrent(value);
10501
+ if (operation2 === "bootstrap") return parseInboxBootstrap(value);
10502
+ if (operation2 === "live.connect") return parseInboxLiveSetup(value);
10318
10503
  if (operation2 === "questions.list") {
10319
10504
  let page = object8(value);
10320
10505
  keys6(page, ["questions", "nextBeforeNumber"]);
10321
- let questions = array2(page.questions).map(parseQuestionWork);
10506
+ let questions = array2(page.questions).map((value2) => parseQuestionWork(value2, contract));
10322
10507
  return assert(page.nextBeforeNumber === null || integer(page.nextBeforeNumber)), { questions, nextBeforeNumber: page.nextBeforeNumber };
10323
10508
  }
10324
10509
  if (operation2 === "items.readRecords") return parseInboxRecords(value);
@@ -10366,6 +10551,156 @@ function parseInboxResult(operation2, value) {
10366
10551
  }
10367
10552
  throw new Error("File content is not a JSON result");
10368
10553
  }
10554
+ function parseInboxBootstrap(value) {
10555
+ let snapshot = object8(value);
10556
+ keys6(snapshot, ["current", "items", "hydrations"]);
10557
+ let current2 = parseInboxCurrent(snapshot.current), items = array2(snapshot.items).map(parseInboxItem);
10558
+ assert(items.every((item) => item.workspaceId === current2.workspace.id) && new Set(items.map((item) => item.id)).size === items.length && new Set(items.map((item) => item.number)).size === items.length);
10559
+ let entries = array2(snapshot.hydrations);
10560
+ assert(entries.length === items.length);
10561
+ let hydrations = entries.map((value2, index) => {
10562
+ let entry = object8(value2), item = items[index];
10563
+ assert(entry.itemId === item.id && entry.revision === item.revision);
10564
+ let refs = authoredInboxRecordRefs(item.body);
10565
+ if (entry.status === "unavailable")
10566
+ return keys6(entry, ["itemId", "revision", "status"]), assert(refs.length > 0), { itemId: item.id, revision: item.revision, status: "unavailable" };
10567
+ keys6(entry, ["itemId", "revision", "status", "result"]), assert(entry.status === "ready");
10568
+ let result2 = parseInboxRecords(entry.result, refs.length);
10569
+ return assert(result2.records.length === refs.length && result2.records.every((row, index2) => recordKey(row) === recordKey(refs[index2])) && result2.links.every((link) => refs.some((ref) => ref.repository === link.repository))), { itemId: item.id, revision: item.revision, status: "ready", result: result2 };
10570
+ });
10571
+ return assert(new TextEncoder().encode(JSON.stringify({ current: current2, items, hydrations })).byteLength <= INBOX_RESULT_BYTES), { current: current2, items, hydrations };
10572
+ }
10573
+
10574
+ var runtime = {
10575
+ connect: (url) => new WebSocket(url),
10576
+ later: (callback, delay) => setTimeout(callback, delay),
10577
+ cancel: (timer) => clearTimeout(timer),
10578
+ now: Date.now
10579
+ };
10580
+ function subscribeInbox(resolve, authorize, onDirty, onState, rt = runtime, signal) {
10581
+ let active2 = !0, generation = 0, failures2 = 0, sequence = 0, authority2, socket, unsubscribe, retry, heartbeat, renewal, deadline, heartbeatRef, notify = (state) => {
10582
+ if (active2)
10583
+ try {
10584
+ onState?.(state);
10585
+ } catch {
10586
+ }
10587
+ }, clear = () => {
10588
+ for (let timer of [retry, heartbeat, renewal, deadline]) timer !== void 0 && rt.cancel(timer);
10589
+ retry = heartbeat = renewal = deadline = void 0;
10590
+ let prior = socket;
10591
+ socket = void 0, prior?.close(), heartbeatRef = void 0;
10592
+ }, current2 = () => active2 && !!authority2?.isCurrent() && !authority2.signal.aborted, stop = () => {
10593
+ active2 && (active2 = !1, generation++, clear(), unsubscribe?.(), authority2?.signal.removeEventListener("abort", revoked), signal?.removeEventListener("abort", revoked));
10594
+ }, revoked = () => {
10595
+ notify("denied"), stop();
10596
+ };
10597
+ function reconnect() {
10598
+ if (active2) {
10599
+ if (!current2()) {
10600
+ revoked();
10601
+ return;
10602
+ }
10603
+ generation++, clear(), notify("unavailable"), retry = rt.later(() => {
10604
+ retry = void 0, open();
10605
+ }, Math.min(3e4, 500 * 2 ** Math.min(failures2++, 6)));
10606
+ }
10607
+ }
10608
+ async function open() {
10609
+ let started = ++generation;
10610
+ clear();
10611
+ try {
10612
+ let beat2 = function() {
10613
+ if (valid()) {
10614
+ if (heartbeatRef) {
10615
+ reconnect();
10616
+ return;
10617
+ }
10618
+ heartbeatRef = String(++sequence), send3("heartbeat", {}, heartbeatRef, "phoenix"), heartbeat = rt.later(beat2, 25e3);
10619
+ }
10620
+ };
10621
+ var beat = beat2;
10622
+ let setup = await authorize();
10623
+ if (!active2 || started !== generation) return;
10624
+ if (!current2()) {
10625
+ revoked();
10626
+ return;
10627
+ }
10628
+ if (setup.expiresAt <= rt.now()) throw new Error();
10629
+ let url = new URL(setup.url);
10630
+ url.searchParams.set("apikey", setup.key), url.searchParams.set("vsn", "1.0.0");
10631
+ let connection = rt.connect(url.href);
10632
+ socket = connection;
10633
+ let valid = () => active2 && current2() && started === generation && socket === connection, topic = `realtime:${setup.topic}`, join = String(++sequence), joined = !1, send3 = (event, payload, ref = String(++sequence), destination = topic) => connection.send(JSON.stringify({ topic: destination, event, payload, ref }));
10634
+ deadline = rt.later(reconnect, 15e3), connection.addEventListener("open", () => {
10635
+ valid() && send3("phx_join", {
10636
+ config: { private: !0, broadcast: { ack: !1, self: !1 }, presence: { enabled: !1 }, postgres_changes: [] },
10637
+ access_token: setup.token
10638
+ }, join);
10639
+ }), connection.addEventListener("message", (event) => {
10640
+ if (!valid() || typeof event.data != "string" || event.data.length > 8192) return;
10641
+ let value;
10642
+ try {
10643
+ value = JSON.parse(event.data);
10644
+ } catch {
10645
+ return;
10646
+ }
10647
+ if (!(!value || typeof value != "object" || Array.isArray(value))) {
10648
+ if (value.topic === "phoenix" && value.event === "phx_reply" && value.ref === heartbeatRef) {
10649
+ heartbeatRef = void 0;
10650
+ return;
10651
+ }
10652
+ if (value.topic === topic)
10653
+ if (value.event === "phx_reply" && value.ref === join && !joined) {
10654
+ if (value.payload?.status !== "ok") {
10655
+ reconnect();
10656
+ return;
10657
+ }
10658
+ if (joined = !0, failures2 = 0, deadline !== void 0 && rt.cancel(deadline), deadline = void 0, notify("connected"), !valid()) return;
10659
+ heartbeat = rt.later(beat2, 25e3), renewal = rt.later(() => {
10660
+ open();
10661
+ }, Math.max(0, setup.expiresAt - rt.now() - 6e4));
10662
+ } else if (joined && value.event === "broadcast" && value.payload?.event === "dirty" && value.payload.type === "broadcast" && value.payload.payload && typeof value.payload.payload == "object" && !Array.isArray(value.payload.payload) && Object.keys(value.payload.payload).length === 0)
10663
+ try {
10664
+ onDirty();
10665
+ } catch {
10666
+ }
10667
+ else (value.event === "phx_error" || value.event === "phx_close" || value.event === "system" && value.payload?.status === "error") && reconnect();
10668
+ }
10669
+ }), connection.addEventListener("close", () => {
10670
+ valid() && reconnect();
10671
+ }), connection.addEventListener("error", () => {
10672
+ valid() && reconnect();
10673
+ });
10674
+ } catch (error) {
10675
+ if (!active2 || started !== generation) return;
10676
+ if (error instanceof InboxOperationError && (error.status === 401 || error.status === 403)) {
10677
+ revoked();
10678
+ return;
10679
+ }
10680
+ reconnect();
10681
+ }
10682
+ }
10683
+ async function initialize() {
10684
+ if (active2)
10685
+ try {
10686
+ let result2 = await resolve();
10687
+ if (!active2) return;
10688
+ if (authority2 = result2, !current2()) {
10689
+ revoked();
10690
+ return;
10691
+ }
10692
+ authority2.signal.addEventListener("abort", revoked, { once: !0 }), unsubscribe = authority2.subscribe?.(() => {
10693
+ current2() ? open() : revoked();
10694
+ }), open();
10695
+ } catch (error) {
10696
+ if (!active2) return;
10697
+ error instanceof InboxOperationError && (error.status === 401 || error.status === 403) ? revoked() : (notify("unavailable"), retry = rt.later(() => {
10698
+ retry = void 0, initialize();
10699
+ }, Math.min(3e4, 500 * 2 ** Math.min(failures2++, 6))));
10700
+ }
10701
+ }
10702
+ return signal?.aborted ? revoked() : (signal?.addEventListener("abort", revoked, { once: !0 }), initialize()), stop;
10703
+ }
10369
10704
 
10370
10705
  async function limitedBody(request3, limit, timeoutMs) {
10371
10706
  if (!request3.body) return new Uint8Array();
@@ -10416,22 +10751,28 @@ function resolveHostedInboxContext(host, mode = "fresh") {
10416
10751
  return resolve || (resolve = hostedInboxContext(), contexts.set(host.binding, resolve)), resolve({ ...host, memberId: host.memberId }, mode);
10417
10752
  }
10418
10753
  function hostedInboxContext() {
10419
- let installed2, retained, pending, denied, revision = 0, issued = 0, settled = 0;
10754
+ let installed2, retained, pending, denied, revision = 0, issued = 0, settled = 0, observers = /* @__PURE__ */ new Set(), notify = () => {
10755
+ for (let observer2 of observers)
10756
+ try {
10757
+ observer2();
10758
+ } catch {
10759
+ }
10760
+ };
10420
10761
  return async (host, mode = "fresh") => {
10421
10762
  let check = () => {
10422
10763
  if (!host.isCurrent() || host.expiresAt <= Date.now()) throw new Error("Inbox context unavailable");
10423
10764
  };
10424
10765
  check();
10425
10766
  let matches2 = (entry2) => entry2.endpoint === host.endpoint && entry2.memberId === host.memberId && entry2.valid();
10426
- if (mode === "list" && denied && matches2(denied)) throw new InboxContextError(denied.status);
10767
+ if (mode === "member" && denied && matches2(denied)) throw new InboxContextError(denied.status);
10427
10768
  let bind = (value) => ({ ...value, isCurrent: () => host.isCurrent() && host.expiresAt > Date.now() && value.isCurrent() });
10428
- if (mode === "list" && retained && matches2(retained)) return bind(retained.value);
10769
+ if (mode === "member" && retained && matches2(retained)) return bind(retained.value);
10429
10770
  if (mode !== "fresh" && pending && matches2(pending)) {
10430
10771
  let value = await pending.result;
10431
10772
  return check(), bind(value);
10432
10773
  }
10433
10774
  let started = ++issued, valid = host.snapshot?.isCurrent ?? host.isCurrent, invalidate = (status) => {
10434
- installed2 = void 0, retained = void 0, pending = void 0, denied = { endpoint: host.endpoint, memberId: host.memberId, valid, status }, revision++, settled = ++issued;
10775
+ installed2 = void 0, retained = void 0, pending = void 0, denied = { endpoint: host.endpoint, memberId: host.memberId, valid, status }, revision++, settled = ++issued, notify();
10435
10776
  }, result2 = (async () => {
10436
10777
  let response2 = await fetch(`${host.endpoint}/api/inbox/context`, {
10437
10778
  method: "GET",
@@ -10449,8 +10790,19 @@ function hostedInboxContext() {
10449
10790
  if (context.memberId !== host.memberId || context.kind === "inbox" && !current2 || current2 && (context.kind !== "inbox" || current2.viewer.id !== host.memberId || current2.workspace.id !== context.workspaceId || host.endpoint !== `https://${current2.workspace.slug}.oddington.ai`))
10450
10791
  throw new Error("Inbox context unavailable");
10451
10792
  if (started < settled) throw new Error("Inbox context unavailable");
10452
- JSON.stringify(installed2) !== JSON.stringify(context) && (installed2 = context, revision++), settled = started, denied = void 0;
10453
- let generation = revision, startup = Object.freeze({ context, current: current2, invalidate, isCurrent: () => valid() && generation === revision });
10793
+ JSON.stringify(installed2) !== JSON.stringify(context) && (installed2 = context, revision++, notify()), settled = started, denied = void 0;
10794
+ let generation = revision, isRetainedCurrent = () => valid() && generation === revision, startup = Object.freeze({
10795
+ context,
10796
+ current: current2,
10797
+ invalidate,
10798
+ isCurrent: isRetainedCurrent,
10799
+ isRetainedCurrent,
10800
+ onInvalidate(listener) {
10801
+ return observers.add(listener), () => {
10802
+ observers.delete(listener);
10803
+ };
10804
+ }
10805
+ });
10454
10806
  return retained = current2 ? { value: startup, endpoint: host.endpoint, memberId: host.memberId, valid: startup.isCurrent } : void 0, startup;
10455
10807
  } finally {
10456
10808
  response2.body?.cancel().catch(() => {
@@ -10914,8 +11266,8 @@ var WorkspaceAccessError = class extends Error {
10914
11266
  };
10915
11267
 
10916
11268
  var unavailable5 = () => 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();
10917
- function hostFailure(error, context) {
10918
- return !context.isCurrent() || context.expiresAt <= Date.now() || error instanceof InboxContextError && error.status === 401 ? stale() : error instanceof InboxContextError && (error.status === 400 || error.status === 409) ? new InboxOperationError(error.status, error.status === 400 ? "invalid_input" : "conflict") : error instanceof InboxContextError && error.status === 403 ? new InboxOperationError(403, "access_denied") : unavailable5();
11269
+ function hostFailure(error, context, live2 = !1) {
11270
+ return live2 && context.snapshot?.isCurrent() && !context.signal?.aborted && !(error instanceof InboxContextError && (error.status === 401 || error.status === 403)) ? unavailable5() : !context.isCurrent() || context.expiresAt <= Date.now() || error instanceof InboxContextError && error.status === 401 ? stale() : error instanceof InboxContextError && (error.status === 400 || error.status === 409) ? new InboxOperationError(error.status, error.status === 400 ? "invalid_input" : "conflict") : error instanceof InboxContextError && error.status === 403 ? new InboxOperationError(403, "access_denied") : unavailable5();
10919
11271
  }
10920
11272
  async function send2(operation2, input, resolved, admitted) {
10921
11273
  let envelope = parseInboxRequest({
@@ -10924,9 +11276,9 @@ async function send2(operation2, input, resolved, admitted) {
10924
11276
  ...isAppQuestionOperation(operation2) ? { contract: INBOX_QUESTION_CONTRACT } : {}
10925
11277
  }), context;
10926
11278
  try {
10927
- context = resolved ?? await resolveAppContext();
11279
+ context = resolved ?? await resolveAppContext(!1, !isAppQuestionOperation(operation2));
10928
11280
  } catch (error) {
10929
- throw contextFailure(error);
11281
+ throw operation2 === "live.connect" && !(error instanceof WorkspaceAccessError) && !memberContextSignal()?.aborted ? unavailable5() : contextFailure(error);
10930
11282
  }
10931
11283
  if (context.kind === "local") {
10932
11284
  if (!isAppQuestionOperation(operation2)) throw new InboxOperationError(403, "access_denied");
@@ -10950,13 +11302,17 @@ async function send2(operation2, input, resolved, admitted) {
10950
11302
  let host;
10951
11303
  if (!isAppQuestionOperation(operation2)) {
10952
11304
  try {
10953
- host = admitted ?? await resolveHostedInboxContext(context);
11305
+ host = admitted ?? await resolveHostedInboxContext(context, "member");
10954
11306
  } catch (error) {
10955
- throw hostFailure(error, context);
11307
+ throw hostFailure(error, context, operation2 === "live.connect");
10956
11308
  }
10957
11309
  if (!host) throw unavailable5();
10958
11310
  }
10959
11311
  let check = () => {
11312
+ if (operation2 === "live.connect" && context.snapshot) {
11313
+ if (!context.snapshot.isCurrent() || context.signal?.aborted || host && !host.isRetainedCurrent()) throw stale();
11314
+ return;
11315
+ }
10960
11316
  if (!context.isCurrent() || host && !host.isCurrent() || !Number.isFinite(context.expiresAt) || context.expiresAt <= Date.now()) throw stale();
10961
11317
  };
10962
11318
  if (check(), host?.context.kind === "focused")
@@ -10964,7 +11320,11 @@ async function send2(operation2, input, resolved, admitted) {
10964
11320
  try {
10965
11321
  let response2 = await fetch(`${context.endpoint}/api/inbox`, {
10966
11322
  method: "POST",
10967
- headers: { authorization: `Bearer ${context.accessToken}`, "content-type": "application/json" },
11323
+ headers: {
11324
+ authorization: `Bearer ${context.accessToken}`,
11325
+ "content-type": "application/json",
11326
+ ...operation2 === "items.readRecords" ? { "x-os-inbox-records": "links-v1" } : {}
11327
+ },
10968
11328
  body: JSON.stringify(envelope),
10969
11329
  redirect: "error",
10970
11330
  cache: "no-store",
@@ -10996,17 +11356,57 @@ async function send2(operation2, input, resolved, admitted) {
10996
11356
  let bytes = await limitedBody(response2, INBOX_RESULT_BYTES);
10997
11357
  if (check(), !bytes) throw unavailable5();
10998
11358
  let value = JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes)), parsed = parseInboxResult(operation2, value);
10999
- if (check(), operation2 === "current" && parsed.workspace.slug !== context.workspace) throw unavailable5();
11359
+ if (check(), operation2 === "bootstrap") {
11360
+ let snapshot = parsed;
11361
+ if (snapshot.current.workspace.slug !== context.workspace || snapshot.current.viewer.id !== context.memberId || snapshot.current.workspace.id !== host?.context.workspaceId) throw unavailable5();
11362
+ }
11363
+ if (operation2 === "live.connect") {
11364
+ let live2 = parsed;
11365
+ if (live2.workspaceId !== host?.context.workspaceId || live2.viewerId !== context.memberId) throw unavailable5();
11366
+ }
11367
+ if (operation2 === "current" && parsed.workspace.slug !== context.workspace) throw unavailable5();
11000
11368
  if ("itemId" in envelope.input) {
11001
11369
  let item = operation2 === "items.read" ? parsed : operation2 === "items.rename" || operation2 === "items.setLifecycle" || operation2 === "items.addRecipient" ? parsed.item : void 0;
11002
11370
  if (item && (item.id !== envelope.input.itemId || "revision" in envelope.input && item.revision !== envelope.input.revision) || operation2 === "items.addRecipient" && parsed.addedPersonId !== envelope.input.personId) throw unavailable5();
11003
11371
  }
11004
11372
  return parsed;
11005
11373
  } catch (error) {
11006
- throw check(), operation2 === "items.list" && error instanceof InboxOperationError && (error.status === 401 || error.status === 403) && host?.invalidate(error.status), error instanceof InboxOperationError ? error : unavailable5();
11374
+ throw check(), (operation2 === "items.list" || operation2 === "bootstrap" || operation2 === "live.connect") && error instanceof InboxOperationError && (error.status === 401 || error.status === 403) && host?.invalidate(error.status), error instanceof InboxOperationError ? error : unavailable5();
11007
11375
  }
11008
11376
  }
11009
11377
  var inbox = {
11378
+ subscribe: (onDirty, onState) => {
11379
+ let lifetime = memberContextSignal();
11380
+ return subscribeInbox(async () => {
11381
+ if (lifetime?.aborted) throw stale();
11382
+ let context;
11383
+ try {
11384
+ context = await resolveAppContext(!1, !0);
11385
+ } catch (error) {
11386
+ throw !(error instanceof WorkspaceAccessError) && lifetime && !lifetime.aborted ? unavailable5() : contextFailure(error);
11387
+ }
11388
+ if (context.kind === "local" || !lifetime) throw new InboxOperationError(403, "access_denied");
11389
+ let host;
11390
+ try {
11391
+ host = await resolveHostedInboxContext(context, "member");
11392
+ } catch (error) {
11393
+ throw hostFailure(error, context, !0);
11394
+ }
11395
+ if (host.context.kind !== "inbox") throw new InboxOperationError(403, "access_denied");
11396
+ let initial = context;
11397
+ return {
11398
+ signal: initial.signal ? AbortSignal.any([lifetime, initial.signal]) : lifetime,
11399
+ isCurrent: () => (initial.snapshot?.isCurrent() ?? initial.isCurrent()) && host.isRetainedCurrent() && !lifetime.aborted,
11400
+ subscribe(listener) {
11401
+ let credentials = initial.snapshot?.subscribe(listener), scope = host.onInvalidate(listener);
11402
+ return () => {
11403
+ credentials?.(), scope();
11404
+ };
11405
+ }
11406
+ };
11407
+ }, async () => await send2("live.connect", {}), onDirty, onState, void 0, lifetime);
11408
+ },
11409
+ bootstrap: async () => await send2("bootstrap", {}),
11010
11410
  async current() {
11011
11411
  let context;
11012
11412
  try {
@@ -11037,7 +11437,7 @@ var inbox = {
11037
11437
  }
11038
11438
  let host;
11039
11439
  try {
11040
- host = initial.kind !== "local" && await resolveHostedInboxContext(initial, "list");
11440
+ host = initial.kind !== "local" && await resolveHostedInboxContext(initial, "member");
11041
11441
  } catch (error) {
11042
11442
  throw hostFailure(error, initial);
11043
11443
  }
@@ -11378,7 +11778,7 @@ function createLocalBrowserAuth(origin, failure) {
11378
11778
  }), handle2;
11379
11779
  }
11380
11780
 
11381
- function createBrowserAuth(runtime) {
11781
+ function createBrowserAuth(runtime2) {
11382
11782
  let coordinators2 = /* @__PURE__ */ new Map();
11383
11783
  function publish2(c, state) {
11384
11784
  c.state = Object.freeze(state);
@@ -11491,14 +11891,14 @@ function createBrowserAuth(runtime) {
11491
11891
  return c.ready = (async () => {
11492
11892
  let revision = c.revision;
11493
11893
  try {
11494
- if (!allowedOrigin(origin)) throw runtime.failure("unavailable");
11495
- runtime.prepare?.();
11894
+ if (!allowedOrigin(origin)) throw runtime2.failure("unavailable");
11895
+ runtime2.prepare?.();
11496
11896
  let response2 = await fetch(`${origin}/api/auth`, { method: "GET", credentials: "same-origin", redirect: "error", cache: "no-store" });
11497
- if (!response2.ok) throw runtime.failure("unavailable");
11897
+ if (!response2.ok) throw runtime2.failure("unavailable");
11498
11898
  let configuration = validateConfiguration(await response2.json());
11499
- if (configuration.authorization && origin !== "https://auth.oddington.ai" && origin !== "http://127.0.0.1:5176") throw runtime.failure("unavailable");
11899
+ if (configuration.authorization && origin !== "https://auth.oddington.ai" && origin !== "http://127.0.0.1:5176") throw runtime2.failure("unavailable");
11500
11900
  if (c.authorization = configuration.authorization, !c.active || globalThis.location?.origin !== origin) return;
11501
- if (c.provider = await runtime.provider(configuration, {
11901
+ if (c.provider = await runtime2.provider(configuration, {
11502
11902
  revision: () => c.revision,
11503
11903
  current: (revision2) => current2(c, origin, revision2),
11504
11904
  canPersistSession: () => c.active && (c.state.status === "initializing" || !!c.session || c.state.pending === "verify_code"),
@@ -11529,7 +11929,7 @@ function createBrowserAuth(runtime) {
11529
11929
  async function checkWorkspaceAccess(c, origin) {
11530
11930
  if (origin === "https://auth.oddington.ai" || origin === "http://127.0.0.1:5176") return;
11531
11931
  let revision = c.revision;
11532
- if (!current2(c, origin, revision) || !c.session || !validSession(c.session) || c.state.pending === "sign_out") throw runtime.failure("stale");
11932
+ if (!current2(c, origin, revision) || !c.session || !validSession(c.session) || c.state.pending === "sign_out") throw runtime2.failure("stale");
11533
11933
  if (c.workspaceAccess?.revision !== revision) {
11534
11934
  let token = c.session.access_token, result2 = (async () => {
11535
11935
  let status;
@@ -11549,16 +11949,16 @@ function createBrowserAuth(runtime) {
11549
11949
  } catch {
11550
11950
  status = 503;
11551
11951
  }
11552
- if (!current2(c, origin, revision) || c.state.pending === "sign_out") throw runtime.failure("stale");
11952
+ if (!current2(c, origin, revision) || c.state.pending === "sign_out") throw runtime2.failure("stale");
11553
11953
  if (status !== 200) throw new WorkspaceAccessError(status === 401 ? 401 : status === 403 ? 403 : 503);
11554
11954
  })();
11555
11955
  c.workspaceAccess = { revision, result: result2 };
11556
11956
  }
11557
- if (await c.workspaceAccess.result, !current2(c, origin, revision)) throw runtime.failure("stale");
11957
+ if (await c.workspaceAccess.result, !current2(c, origin, revision)) throw runtime2.failure("stale");
11558
11958
  }
11559
11959
  return { create() {
11560
11960
  let origin = globalThis.location?.origin ?? "";
11561
- if (isAppOrigin(origin) && origin !== "http://127.0.0.1:5176") return createLocalBrowserAuth(origin, runtime.failure);
11961
+ if (isAppOrigin(origin) && origin !== "http://127.0.0.1:5176") return createLocalBrowserAuth(origin, runtime2.failure);
11562
11962
  let c = coordinators2.get(origin);
11563
11963
  c || (c = createCoordinator(origin), coordinators2.set(origin, c));
11564
11964
  let coordinator = c;
@@ -11573,21 +11973,21 @@ function createBrowserAuth(runtime) {
11573
11973
  };
11574
11974
  coordinator.listeners.add(observation);
11575
11975
  let assertActive = () => {
11576
- if (!active2) throw runtime.failure("disposed");
11976
+ if (!active2) throw runtime2.failure("disposed");
11577
11977
  };
11578
11978
  async function action(kind, work) {
11579
- if (assertActive(), coordinator.action && kind !== "sign_out" || kind === "sign_out" && coordinator.state.pending === "sign_out") throw runtime.failure("busy");
11979
+ if (assertActive(), coordinator.action && kind !== "sign_out" || kind === "sign_out" && coordinator.state.pending === "sign_out") throw runtime2.failure("busy");
11580
11980
  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"));
11581
11981
  let marker = {};
11582
11982
  coordinator.action = marker, ownedAction = marker;
11583
11983
  let revision = coordinator.revision;
11584
11984
  publish2(coordinator, { ...coordinator.state, error: void 0, pending: kind });
11585
11985
  try {
11586
- if (await ready(coordinator), assertActive(), !coordinator.provider || !coordinator.active || globalThis.location?.origin !== origin) throw runtime.failure("unavailable");
11587
- 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");
11986
+ if (await ready(coordinator), assertActive(), !coordinator.provider || !coordinator.active || globalThis.location?.origin !== origin) throw runtime2.failure("unavailable");
11987
+ 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 runtime2.failure("stale");
11588
11988
  } catch (error) {
11589
11989
  let reason = active2 ? current2(coordinator, origin, revision) ? safeReason(error) ?? "unavailable" : "stale" : "disposed";
11590
- throw active2 && current2(coordinator, origin, revision) && publish2(coordinator, { ...coordinator.state, error: reason }), runtime.failure(reason);
11990
+ throw active2 && current2(coordinator, origin, revision) && publish2(coordinator, { ...coordinator.state, error: reason }), runtime2.failure(reason);
11591
11991
  } finally {
11592
11992
  coordinator.action === marker && (coordinator.action = void 0, coordinator.active && (publish2(coordinator, { ...coordinator.state, pending: void 0 }), kind === "sign_out" && coordinator.session && notify(coordinator, "TOKEN_REFRESHED"))), ownedAction === marker && (ownedAction = void 0);
11593
11993
  }
@@ -11647,21 +12047,21 @@ function createBrowserAuth(runtime) {
11647
12047
  };
11648
12048
  },
11649
12049
  async sendCode(email) {
11650
- if (assertActive(), !validEmail(email)) throw runtime.failure("invalid_input");
12050
+ if (assertActive(), !validEmail(email)) throw runtime2.failure("invalid_input");
11651
12051
  await action("send_code", async (provider2) => {
11652
12052
  let { error } = await provider2.signInWithOtp({ email: email.trim(), options: {
11653
12053
  shouldCreateUser: origin !== "https://auth.oddington.ai" && origin !== "http://127.0.0.1:5176"
11654
12054
  } });
11655
- if (error && !accountRefusal(error)) throw runtime.failure("unavailable");
12055
+ if (error && !accountRefusal(error)) throw runtime2.failure("unavailable");
11656
12056
  });
11657
12057
  },
11658
12058
  async verifyCode(email, code) {
11659
- if (assertActive(), !validEmail(email) || typeof code != "string" || !/^\d{6}$/.test(code)) throw runtime.failure("invalid_input");
12059
+ if (assertActive(), !validEmail(email) || typeof code != "string" || !/^\d{6}$/.test(code)) throw runtime2.failure("invalid_input");
11660
12060
  await action("verify_code", async (provider2) => {
11661
12061
  let revision = coordinator.revision, { data: data3, error } = await provider2.verifyOtp({ email: email.trim(), token: code, type: "email" });
11662
- if (error) throw runtime.failure(accountRefusal(error) ? "invalid_code" : "unavailable");
11663
- if (!data3.session || !validSession(data3.session)) throw runtime.failure("invalid_code");
11664
- if (!current2(coordinator, origin, revision) && (coordinator.session?.access_token !== data3.session.access_token || coordinator.revision !== revision + 1 || coordinator.state.pending !== "verify_code")) throw runtime.failure("stale");
12062
+ if (error) throw runtime2.failure(accountRefusal(error) ? "invalid_code" : "unavailable");
12063
+ if (!data3.session || !validSession(data3.session)) throw runtime2.failure("invalid_code");
12064
+ if (!current2(coordinator, origin, revision) && (coordinator.session?.access_token !== data3.session.access_token || coordinator.revision !== revision + 1 || coordinator.state.pending !== "verify_code")) throw runtime2.failure("stale");
11665
12065
  accept(coordinator, "SIGNED_IN", data3.session);
11666
12066
  try {
11667
12067
  await checkWorkspaceAccess(coordinator, origin);
@@ -11673,8 +12073,8 @@ function createBrowserAuth(runtime) {
11673
12073
  async signOut() {
11674
12074
  assertActive(), await action("sign_out", async (provider2) => {
11675
12075
  let revision = coordinator.revision, { error } = await provider2.signOut({ scope: "local" });
11676
- if (error) throw runtime.failure("unavailable");
11677
- if (!current2(coordinator, origin, revision) && coordinator.session) throw runtime.failure("stale");
12076
+ if (error) throw runtime2.failure("unavailable");
12077
+ if (!current2(coordinator, origin, revision) && coordinator.session) throw runtime2.failure("stale");
11678
12078
  accept(coordinator, "SIGNED_OUT", null);
11679
12079
  });
11680
12080
  },
@@ -11709,7 +12109,7 @@ function createBrowserAuth(runtime) {
11709
12109
  async getSession() {
11710
12110
  assertActive(), await ready(coordinator), assertActive();
11711
12111
  let revision = coordinator.revision;
11712
- 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") });
12112
+ 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: runtime2.failure("unavailable") } : { data: { session: coordinator.session }, error: null } : { data: { session: null }, error: runtime2.failure("disposed") });
11713
12113
  },
11714
12114
  onAuthStateChange(callback) {
11715
12115
  if (!active2)