@oddington/sdk 0.1.61 → 0.1.63

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/README.md CHANGED
@@ -427,7 +427,9 @@ remain body-free. This is one local bounded selection with the same projection,
427
427
  query and graph bounds and required top-level ceiling; it adds no hosted calls
428
428
  or per-Record reads. `$body` cannot be queried as a schema field. Ordinary
429
429
  snapshot `all`, `query` and `pages`, and hosted Data `all`, remain structured-only.
430
- Initialization never refreshes the hosted artifact. Sign-out, context replacement and expiry invalidate local reads.
430
+ Initialization never refreshes the hosted artifact. Sign-out, confirmed access
431
+ loss and context replacement invalidate local reads. Expired access waits for
432
+ the existing bounded session recovery before a new read or write can proceed.
431
433
  Snapshot initialization requires a hosted browser app; Node, routines and local
432
434
  app contexts receive `DataOperationError` with `context_unavailable`.
433
435
 
@@ -438,9 +440,12 @@ declarations refine fields and values, while the normalized runtime schemas and
438
440
  host remain authoritative. Each call makes one authenticated hosted request;
439
441
  transact changes only shared unpublished work. Publish and discard require exact
440
442
  current owned Change IDs and versions. Publication uses the canonical writer and
441
- applies its confirmed effects to local Records and the same Changes before
443
+ installs its canonical Records and settles the same selected Change versions before
442
444
  resolving, without waiting for hosted projection settlement. No operation
443
445
  refreshes the artifact or adds an unpublished query overlay.
446
+ Assignments and link operations already satisfied by canonical Records succeed;
447
+ their selected Changes retire without publication metadata. A whole no-op creates
448
+ no Git commit or snapshot refresh. Mixed publication commits only real changes.
444
449
 
445
450
  `subscribe(listener)` has no initial callback and returns a synchronous,
446
451
  idempotent unsubscribe function. Listeners on one handle share a connection;
@@ -456,8 +461,10 @@ the response. Repeated hints and unchanged state do not notify.
456
461
  The SDK reconciles on connection, reconnection and update hints, with bounded
457
462
  reconnect backoff and no healthy-connection polling. Changes-only updates reuse
458
463
  the unchanged artifact bytes. Subscription never builds or refreshes a snapshot.
459
- Sign-out, context replacement and expiry stop live delivery and invalidate the
460
- handle under the same local-operation rules.
464
+ Ordinary credential renewal for the same account, workspace and app reconnects
465
+ with current authority and reconciles on the same initialized handle. Sign-out,
466
+ confirmed access loss and identity or scope replacement stop live delivery and
467
+ invalidate the handle under the same local-operation rules.
461
468
 
462
469
  After a lost transact/discard response, `DataOperationError.effect` is
463
470
  `uncertain`, `retryable` is false, and that handle is invalid. Explicitly
package/dist/browser.js CHANGED
@@ -324,7 +324,7 @@ function validRecordRef(value) {
324
324
  }
325
325
 
326
326
  function validDropboxRootPath(value) {
327
- return typeof value == "string" && value.length <= 2048 && value.startsWith("/") && !/[\\\x00-\x1f\x7f]/.test(value) && value.slice(1).split("/").every((segment) => segment.length > 0 && segment.trim() === segment && segment !== "." && segment !== "..");
327
+ return value === "" || typeof value == "string" && value.length <= 2048 && value.startsWith("/") && !/[\\\x00-\x1f\x7f]/.test(value) && value.slice(1).split("/").every((segment) => segment.length > 0 && segment.trim() === segment && segment !== "." && segment !== "..");
328
328
  }
329
329
  function validMicrosoftId(value) {
330
330
  return typeof value == "string" && /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value);
@@ -1749,16 +1749,28 @@ async function resolveSnapshotContext() {
1749
1749
  try {
1750
1750
  let context = await resolveAppContext();
1751
1751
  if (context.kind === "local" || !context.memberId || !context.binding || context.endpoint !== globalThis.location.origin || context.endpoint !== `https://${context.workspace}.oddington.ai`) throw new Error();
1752
- let host = memberContext;
1752
+ let host = memberContext, retained = context.snapshot, isCurrent = () => host === memberContext && (retained ? retained.isCurrent() : context.isCurrent() && context.expiresAt > Date.now());
1753
1753
  return {
1754
1754
  workspace: context.workspace,
1755
1755
  endpoint: context.endpoint,
1756
1756
  memberId: context.memberId,
1757
1757
  binding: context.binding,
1758
- expiresAt: context.expiresAt,
1758
+ get expiresAt() {
1759
+ return retained?.credentials().expiresAt ?? context.expiresAt;
1760
+ },
1761
+ get headers() {
1762
+ return { authorization: `Bearer ${retained?.credentials().accessToken ?? context.accessToken}` };
1763
+ },
1759
1764
  signal: context.signal ? AbortSignal.any([context.signal, memberLifetime.signal]) : memberLifetime.signal,
1760
- headers: { authorization: `Bearer ${context.accessToken}` },
1761
- isCurrent: () => host === memberContext && context.isCurrent() && context.expiresAt > Date.now()
1765
+ isCurrent,
1766
+ ...retained ? { subscribe: retained.subscribe, async refresh() {
1767
+ try {
1768
+ let next = await resolveAppContext();
1769
+ if (!isCurrent() || next.kind === "local" || next.binding !== context.binding || next.memberId !== context.memberId || next.workspace !== context.workspace || next.endpoint !== context.endpoint) throw new Error();
1770
+ } catch {
1771
+ throw new DataOperationError(isCurrent() ? "unavailable" : "context_unavailable", isCurrent());
1772
+ }
1773
+ } } : {}
1762
1774
  };
1763
1775
  } catch {
1764
1776
  throw new DataOperationError("context_unavailable");
@@ -2519,13 +2531,43 @@ function applySnapshotMutation(envelope, prior, mutation, installation) {
2519
2531
  changes = prior.filter((c) => !mutation.selected.some((s) => s.id === c.id && s.version === c.version));
2520
2532
  else {
2521
2533
  let accepted = validateSnapshotChanges(mutation.changes, installation.catalogue.map((c) => c.name)), ids = new Set(accepted.map((c) => c.id));
2522
- if (changes = [...prior.filter((c) => !ids.has(c.id)), ...accepted], changes = [...changes.filter((c) => c.publication), ...changes.filter((c) => !c.publication)], mutation.kind === "publish") {
2523
- if (!accepted.length || accepted.some((c) => !c.publication) || !Array.isArray(mutation.effects) || !mutation.effects.length) return rejected();
2534
+ if (changes = [
2535
+ ...prior.filter((c) => mutation.kind === "publish" ? !mutation.selected.some((s) => s.id === c.id && s.version === c.version) : !ids.has(c.id)),
2536
+ ...accepted.filter((c) => mutation.kind !== "publish" || !prior.some((p) => p.id === c.id && p.version !== c.version))
2537
+ ], changes = [...changes.filter((c) => c.publication), ...changes.filter((c) => !c.publication)], mutation.kind === "publish") {
2538
+ if (accepted.some((c) => !c.publication) || !Array.isArray(mutation.effects)) return rejected();
2524
2539
  let effects = mutation.effects.map((e) => {
2525
2540
  let source2 = accepted.find((c) => c.ref === e.ref);
2526
2541
  return !source2 || snapshotCollection(envelope.catalogue, e.ref)?.name !== e.collection || !["set", "create", "delete"].includes(e.effect.kind) ? rejected() : { ...source2, id: crypto.randomUUID(), recordVersion: e.version, effect: e.effect };
2527
2542
  });
2528
- validateSnapshotChanges(effects, installation.catalogue.map((c) => c.name)), envelope = materializeSnapshot(envelope, effects, `snapshot-${crypto.randomUUID()}`);
2543
+ if (validateSnapshotChanges(effects, installation.catalogue.map((c) => c.name)), mutation.records !== void 0) {
2544
+ if (materializeSnapshot(envelope, [...accepted, ...effects].map(({ publication: _publication, ...c }) => c), envelope.version), !Array.isArray(mutation.records) || new Set(mutation.records.map((r) => r.$ref)).size !== mutation.records.length) return rejected();
2545
+ let refs = new Set(mutation.records.map((r) => r.$ref));
2546
+ if ([...accepted, ...prior.filter((c) => mutation.selected.some((s) => s.id === c.id && s.version === c.version))].some((c) => c.effect.kind !== "delete" && !refs.has(c.ref)) || accepted.some((c) => !mutation.effects.some((e) => e.ref === c.ref && ("field" in c.effect ? "field" in e.effect && e.effect.field === c.effect.field : e.effect.kind === c.effect.kind))) || mutation.effects.some((e) => !accepted.some((c) => c.ref === e.ref) || snapshotCollection(envelope.catalogue, e.ref)?.name !== e.collection || !["set", "create", "delete"].includes(e.effect.kind) || e.effect.kind !== "delete" && !mutation.records.some((r) => r.$ref === e.ref && r.$version === e.version))) return rejected();
2547
+ let rows = new Map(Object.values(envelope.collections).flat().map((r) => [r.$ref, r]));
2548
+ for (let e of mutation.effects) e.effect.kind === "delete" && rows.delete(e.ref);
2549
+ for (let record4 of mutation.records) {
2550
+ let collection = snapshotCollection(envelope.catalogue, record4.$ref)?.name;
2551
+ if (!collection) return rejected();
2552
+ let { $body, ...fields4 } = record4;
2553
+ rows.set(record4.$ref, envelope.bodyCollections?.includes(collection) ? record4 : fields4);
2554
+ }
2555
+ return envelope = validateSnapshotEnvelope({
2556
+ format: envelope.format,
2557
+ repository: envelope.repository,
2558
+ name: envelope.name,
2559
+ version: `snapshot-${crypto.randomUUID()}`,
2560
+ schemas: Object.fromEntries(envelope.catalogue.map((c) => [c.name, {
2561
+ name: c.name,
2562
+ type: c.schema.type,
2563
+ ...c.schema.description === void 0 ? {} : { description: c.schema.description },
2564
+ fields: c.schema.fields.map(publicField)
2565
+ }])),
2566
+ collections: Object.fromEntries(envelope.catalogue.map((c) => [c.name, [...rows.values()].filter((r) => snapshotCollection(envelope.catalogue, r.$ref)?.name === c.name).sort((a, b) => a.$ref < b.$ref ? -1 : 1)]))
2567
+ }, envelope.repository, envelope.name, envelope.bodyCollections), { envelope, changes };
2568
+ }
2569
+ if (!accepted.length || !mutation.effects.length) return rejected();
2570
+ envelope = materializeSnapshot(envelope, effects, `snapshot-${crypto.randomUUID()}`);
2529
2571
  } else {
2530
2572
  if (!accepted.length || accepted.some((c) => c.publication)) return rejected();
2531
2573
  materializeSnapshot(envelope, accepted, envelope.version);
@@ -2801,10 +2843,10 @@ async function acquireSnapshot(store, partition, url, headers, repository, snaps
2801
2843
  }
2802
2844
 
2803
2845
  function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile, connect) {
2804
- let listeners = /* @__PURE__ */ new Set(), session, socket, retry, expiry, stopAuthority, delay = 250, stop = () => {
2846
+ let listeners = /* @__PURE__ */ new Set(), session, socket, retry, expiry, stopAuthority, stopCredentials, delay = 250, stop = () => {
2805
2847
  session?.abort(), session = void 0;
2806
2848
  let prior = socket;
2807
- socket = void 0, prior?.close(), clearTimeout(retry), clearTimeout(expiry), retry = expiry = void 0, stopAuthority?.(), stopAuthority = void 0;
2849
+ socket = void 0, prior?.close(), clearTimeout(retry), clearTimeout(expiry), retry = expiry = void 0, stopAuthority?.(), stopAuthority = void 0, stopCredentials?.(), stopCredentials = void 0;
2808
2850
  }, current2 = () => {
2809
2851
  try {
2810
2852
  return assertCurrent(), !0;
@@ -2828,8 +2870,12 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
2828
2870
  let dirty = !1, running = !1, lostAuthority = () => {
2829
2871
  invalidate(), stop();
2830
2872
  };
2831
- authority2.signal.addEventListener("abort", lostAuthority, { once: !0 }), stopAuthority = () => authority2.signal.removeEventListener("abort", lostAuthority), expiry = setTimeout(lostAuthority, Math.max(0, authority2.expiresAt - Date.now()));
2832
- let later = () => {
2873
+ authority2.signal.addEventListener("abort", lostAuthority, { once: !0 }), stopAuthority = () => authority2.signal.removeEventListener("abort", lostAuthority);
2874
+ let armExpiry = () => {
2875
+ clearTimeout(expiry), expiry = setTimeout(() => {
2876
+ authority2.refresh ? restart() : lostAuthority();
2877
+ }, Math.min(2147483647, Math.max(0, authority2.expiresAt - Date.now())));
2878
+ }, later = () => {
2833
2879
  retry = setTimeout(open, delay), delay = Math.min(3e4, delay * 2);
2834
2880
  }, reconnect = (connection) => {
2835
2881
  session !== owned || !connection || socket !== connection || (socket = void 0, connection.close(), later());
@@ -2848,8 +2894,18 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
2848
2894
  running = !1;
2849
2895
  }
2850
2896
  })());
2851
- }, open = () => {
2852
- if (retry = void 0, !(session !== owned || !current2()))
2897
+ }, opening = 0, open = () => {
2898
+ if (retry = void 0, !(session !== owned || !current2())) {
2899
+ if (authority2.expiresAt <= Date.now() && authority2.refresh) {
2900
+ let attempt = ++opening;
2901
+ authority2.refresh().then(() => {
2902
+ session === owned && opening === attempt && current2() && authority2.expiresAt > Date.now() && open();
2903
+ }).catch(() => {
2904
+ session === owned && current2();
2905
+ });
2906
+ return;
2907
+ }
2908
+ armExpiry();
2853
2909
  try {
2854
2910
  let connection = connect(url.replace(/^http/, "ws") + "/updates", [
2855
2911
  snapshotUpdatesProtocol,
@@ -2863,8 +2919,17 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
2863
2919
  } catch {
2864
2920
  session === owned && later();
2865
2921
  }
2922
+ }
2923
+ }, restart = () => {
2924
+ if (session !== owned || !current2()) return;
2925
+ let attempt = ++opening;
2926
+ clearTimeout(retry), clearTimeout(expiry);
2927
+ let prior = socket;
2928
+ socket = void 0, prior?.close(), Promise.resolve().then(() => {
2929
+ session === owned && opening === attempt && open();
2930
+ });
2866
2931
  };
2867
- open();
2932
+ stopCredentials = authority2.subscribe?.(restart), open();
2868
2933
  };
2869
2934
  return {
2870
2935
  notify,
@@ -2948,8 +3013,12 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
2948
3013
  let properties = dataProperties(input), repository = properties.repository?.value, snapshot = properties.snapshot?.value;
2949
3014
  if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid9();
2950
3015
  let authority2 = await resolve(), invalidated = !1, stopLive, assertCurrent = () => {
2951
- if (invalidated || authority2.signal.aborted || authority2.expiresAt <= Date.now() || !authority2.isCurrent())
3016
+ if (invalidated || authority2.signal.aborted || !authority2.isCurrent() || !authority2.refresh && authority2.expiresAt <= Date.now())
2952
3017
  throw invalidated = !0, stopLive?.(), new DataOperationError("context_unavailable");
3018
+ }, assertAccess = () => {
3019
+ if (assertCurrent(), authority2.expiresAt <= Date.now()) throw new DataOperationError("unavailable", !0);
3020
+ }, ensureAccess = async () => {
3021
+ assertCurrent(), authority2.expiresAt <= Date.now() && await authority2.refresh?.(), assertAccess();
2953
3022
  };
2954
3023
  assertCurrent();
2955
3024
  let partition = JSON.stringify([authority2.endpoint, authority2.memberId, authority2.workspace, repository, snapshot]), work = pending.get(authority2.binding);
@@ -2962,7 +3031,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
2962
3031
  } finally {
2963
3032
  store.close();
2964
3033
  }
2965
- assertCurrent(), cached && (cached.repository !== repository || cached.name !== snapshot || !validSnapshotArtifactToken(cached.artifactToken) || cached.pairToken !== "" && !validSnapshotPairToken(cached.pairToken)) && (cached = void 0);
3034
+ assertAccess(), cached && (cached.repository !== repository || cached.name !== snapshot || !validSnapshotArtifactToken(cached.artifactToken) || cached.pairToken !== "" && !validSnapshotPairToken(cached.pairToken)) && (cached = void 0);
2966
3035
  } catch (error) {
2967
3036
  throw assertCurrent(), error instanceof DataOperationError ? error : new DataOperationError("unavailable", !0);
2968
3037
  }
@@ -2980,7 +3049,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
2980
3049
  authority2.headers,
2981
3050
  repository,
2982
3051
  snapshot,
2983
- assertCurrent,
3052
+ assertAccess,
2984
3053
  authority2.signal,
2985
3054
  null
2986
3055
  )).installation;
@@ -2992,7 +3061,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
2992
3061
  }).catch(() => {
2993
3062
  }));
2994
3063
  try {
2995
- installation = await installing, assertCurrent();
3064
+ installation = await installing, assertAccess();
2996
3065
  } catch (error) {
2997
3066
  throw assertCurrent(), error instanceof DataOperationError ? error : new DataOperationError("unavailable", !0);
2998
3067
  }
@@ -3006,8 +3075,9 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
3006
3075
  return writes = result2.catch(() => {
3007
3076
  }), result2;
3008
3077
  }, reconcile = (signal) => serial(async () => {
3009
- let fenced = () => {
3010
- if (assertCurrent(), signal.aborted) throw new DataOperationError("unavailable", !0);
3078
+ await ensureAccess();
3079
+ let headers = authority2.headers, fenced = () => {
3080
+ if (assertAccess(), signal.aborted || headers.authorization !== authority2.headers.authorization) throw new DataOperationError("unavailable", !0);
3011
3081
  };
3012
3082
  fenced();
3013
3083
  let store = await open();
@@ -3016,7 +3086,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
3016
3086
  store,
3017
3087
  partition,
3018
3088
  url,
3019
- authority2.headers,
3089
+ headers,
3020
3090
  repository,
3021
3091
  snapshot,
3022
3092
  fenced,
@@ -3039,12 +3109,12 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
3039
3109
  });
3040
3110
  }
3041
3111
  let publications = /* @__PURE__ */ new Map(), mutate = async (kind, payload, selected, publication) => {
3042
- if (assertCurrent(), publication?.complete) return [];
3112
+ if (await ensureAccess(), publication?.complete) return [];
3043
3113
  let body = { snapshotId: installation.snapshotId, ...payload };
3044
3114
  checkDataRequestSize(body, 2 * 1024 * 1024);
3045
3115
  let dispatched = !1, applied = !1, store;
3046
3116
  try {
3047
- store = await open(), assertCurrent(), dispatched = !0;
3117
+ store = await open(), assertAccess(), dispatched = !0;
3048
3118
  let response2 = await fetch(`${authority2.endpoint}/api/data/snapshots/${repository}/${snapshot}/changes/${kind}`, {
3049
3119
  method: "POST",
3050
3120
  redirect: "error",
@@ -3060,11 +3130,19 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
3060
3130
  mutation = { kind, selected };
3061
3131
  } else if (kind === "transact") mutation = { kind, changes: value };
3062
3132
  else {
3063
- if (!value || Object.keys(value).sort().join(",") !== "changes,effects" || !Array.isArray(value.changes) || value.changes.length !== selected.length || value.changes.some((c) => !selected.some((s) => s.id === c.id && s.version === c.version))) throw new Error();
3064
- mutation = { kind, changes: value.changes, effects: value.effects };
3133
+ if (!value || !["changes,effects", "changes,effects,records"].includes(Object.keys(value).sort().join(",")) || !Array.isArray(value.changes) || value.changes.length > selected.length || value.changes.some((c) => !selected.some((s) => s.id === c.id && s.version === c.version)) || !Object.hasOwn(value, "records") && value.changes.length !== selected.length) throw new Error();
3134
+ mutation = {
3135
+ kind,
3136
+ selected,
3137
+ changes: value.changes,
3138
+ effects: value.effects,
3139
+ ...Object.hasOwn(value, "records") ? { records: value.records } : {}
3140
+ };
3065
3141
  }
3066
3142
  let before = await store.changes(installation);
3067
- return installation = await store.mutate(installation, mutation, assertCurrent), assertCurrent(), publication && (publication.complete = !0), live2.notify(snapshotDifference(before, await store.changes(installation))), structuredClone(mutation.changes ?? []);
3143
+ installation = await store.mutate(installation, mutation, assertAccess), assertAccess();
3144
+ let update = snapshotDifference(before, await store.changes(installation));
3145
+ return kind === "publish" && (update.records = !0), assertAccess(), publication && (publication.complete = !0), live2.notify(update), assertAccess(), structuredClone(mutation.changes ?? []);
3068
3146
  } catch (error) {
3069
3147
  let failure = error instanceof DataOperationError ? error : new DataOperationError("unavailable"), effect = applied ? "applied" : dispatched ? failure.effect ?? "uncertain" : "unapplied";
3070
3148
  throw effect !== "unapplied" && (kind !== "publish" || effect === "applied") && (invalidated = !0, live2.stop(), await store?.invalidate(installation).catch(() => {
@@ -3080,7 +3158,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
3080
3158
  }
3081
3159
  }, query = async (query2, maxRecords, body = !1) => {
3082
3160
  let pinned = installation;
3083
- assertCurrent();
3161
+ await ensureAccess();
3084
3162
  let captured = captureRecordsQuery(query2);
3085
3163
  checkDataRequestSize({
3086
3164
  repository,
@@ -3090,23 +3168,23 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
3090
3168
  });
3091
3169
  let store;
3092
3170
  try {
3093
- store = await open(), assertCurrent();
3171
+ store = await open(), assertAccess();
3094
3172
  let result2 = await store.query(pinned, captured, maxRecords, body);
3095
- return assertCurrent(), result2;
3173
+ return assertAccess(), result2;
3096
3174
  } catch (error) {
3097
- throw assertCurrent(), error instanceof DataOperationError ? error : error instanceof RecordValidationError ? new DataOperationError("invalid_query") : new DataOperationError("unavailable", !0);
3175
+ throw assertAccess(), error instanceof DataOperationError ? error : error instanceof RecordValidationError ? new DataOperationError("invalid_query") : new DataOperationError("unavailable", !0);
3098
3176
  } finally {
3099
3177
  store?.close();
3100
3178
  }
3101
3179
  }, localRead = async (operation2) => {
3102
- assertCurrent();
3180
+ await ensureAccess();
3103
3181
  let store;
3104
3182
  try {
3105
- store = await open(), assertCurrent();
3183
+ store = await open(), assertAccess();
3106
3184
  let value = await operation2(store);
3107
- return assertCurrent(), value;
3185
+ return assertAccess(), value;
3108
3186
  } catch (error) {
3109
- throw assertCurrent(), error instanceof DataOperationError ? error : new DataOperationError("unavailable", !0);
3187
+ throw assertAccess(), error instanceof DataOperationError ? error : new DataOperationError("unavailable", !0);
3110
3188
  } finally {
3111
3189
  store?.close();
3112
3190
  }
@@ -5230,7 +5308,11 @@ function init({ auth: input }) {
5230
5308
  url.protocol === "https:" && !url.port && !url.username && !url.password && !url.search && !url.hash && url.pathname === "/" && /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(slug) && slug !== "auth" && (endpoint = url.origin, workspace = slug);
5231
5309
  } catch {
5232
5310
  }
5233
- let active2 = !0, revision = 0, person, token, binding = {}, installation = new AbortController(), hostedAuthority = new AbortController(), sharedLocal = localOrigin && registered?.localContext?.origin === localOrigin ? registered.localContext.connection : void 0, local2 = sharedLocal ?? (localOrigin ? appContext(localOrigin, () => active2) : void 0), subscription, stopDisposal, owned = (context) => {
5311
+ let active2 = !0, revision = 0, person, token, credentials = { accessToken: "", expiresAt: 0 }, credentialListeners = /* @__PURE__ */ new Set(), updateCredentials = (next) => {
5312
+ (!Number.isFinite(next.expiresAt) || typeof next.accessToken != "string" || !/^[^\s]{1,8192}$/.test(next.accessToken)) && (next = { accessToken: "", expiresAt: 0 });
5313
+ let changed = credentials.accessToken !== next.accessToken || credentials.expiresAt !== next.expiresAt;
5314
+ if (credentials = next, changed) for (let listener of credentialListeners) listener();
5315
+ }, binding = {}, installation = new AbortController(), hostedAuthority = new AbortController(), sharedLocal = localOrigin && registered?.localContext?.origin === localOrigin ? registered.localContext.connection : void 0, local2 = sharedLocal ?? (localOrigin ? appContext(localOrigin, () => active2) : void 0), subscription, stopDisposal, owned = (context) => {
5234
5316
  let signal = AbortSignal.any([context.signal, installation.signal]);
5235
5317
  return {
5236
5318
  ...context,
@@ -5268,15 +5350,33 @@ function init({ auth: input }) {
5268
5350
  let expiresAt = (session.expires_at ?? 0) * 1e3;
5269
5351
  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now() || !session.user.id)
5270
5352
  throw new Error("Hosted Data context unavailable.");
5271
- if (person = session.user.id, registered && await registered.checkWorkspaceAccess(), !active2 || globalThis.location.origin !== endpoint || started !== revision || person !== session.user.id)
5353
+ if (person = session.user.id, updateCredentials({ accessToken: session.access_token, expiresAt }), registered)
5354
+ try {
5355
+ await registered.checkWorkspaceAccess();
5356
+ } catch (error2) {
5357
+ throw error2 instanceof WorkspaceAccessError && error2.status !== 503 && started === revision && (revision++, hostedAuthority.abort(), hostedAuthority = new AbortController()), error2;
5358
+ }
5359
+ if (!active2 || globalThis.location.origin !== endpoint || started !== revision || person !== session.user.id)
5272
5360
  throw new Error("Hosted Data context unavailable.");
5273
- let isCurrent = () => active2 && globalThis.location.origin === endpoint && revision === started && person === session.user.id && expiresAt > Date.now();
5361
+ let isCurrent = () => active2 && globalThis.location.origin === endpoint && revision === started && person === session.user.id && expiresAt > Date.now(), snapshotCurrent = () => active2 && globalThis.location.origin === endpoint && revision === started && person === session.user.id;
5274
5362
  return {
5275
5363
  workspace,
5276
5364
  endpoint,
5277
5365
  accessToken: session.access_token,
5278
5366
  expiresAt,
5279
5367
  isCurrent,
5368
+ snapshot: {
5369
+ isCurrent: snapshotCurrent,
5370
+ credentials: () => ({
5371
+ ...credentials,
5372
+ expiresAt: Math.min(credentials.expiresAt, registered?.accessExpiresAt?.() ?? credentials.expiresAt)
5373
+ }),
5374
+ subscribe(listener) {
5375
+ return credentialListeners.add(listener), () => {
5376
+ credentialListeners.delete(listener);
5377
+ };
5378
+ }
5379
+ },
5280
5380
  memberId: session.user.id,
5281
5381
  binding,
5282
5382
  signal: AbortSignal.any([installation.signal, hostedAuthority.signal])
@@ -5292,7 +5392,7 @@ function init({ auth: input }) {
5292
5392
  installedDispose = dispose, stopDisposal = registered?.onDispose(dispose), active2 && (sharedLocal || (subscription = auth2.onAuthStateChange((event, session) => {
5293
5393
  if (registered && event === "INITIAL_SESSION" && !session) return;
5294
5394
  let next = session?.user.id ?? null;
5295
- (event === "SIGNED_OUT" || person !== void 0 && next !== person || person !== void 0 && event === "SIGNED_IN" && token !== session?.access_token) && (revision++, hostedAuthority.abort(), hostedAuthority = new AbortController(), local2?.invalidate()), person = next, token = session?.access_token;
5395
+ (event === "SIGNED_OUT" || person !== void 0 && next !== person || person !== void 0 && event === "SIGNED_IN" && token !== session?.access_token) && (revision++, hostedAuthority.abort(), hostedAuthority = new AbortController(), local2?.invalidate()), person = next, token = session?.access_token, session && updateCredentials({ accessToken: session.access_token, expiresAt: (session.expires_at ?? 0) * 1e3 });
5296
5396
  }).data.subscription), sharedLocal || local2?.start());
5297
5397
  }
5298
5398
  var os = { init };
@@ -5781,6 +5881,7 @@ function createBrowserAuth(runtime) {
5781
5881
  }
5782
5882
  });
5783
5883
  return registerBrowserAuth(handle2, {
5884
+ accessExpiresAt: () => active2 && coordinator.session && validSession(coordinator.session) ? coordinator.session.expires_at * 1e3 : 0,
5784
5885
  async ready() {
5785
5886
  assertActive(), await ready(coordinator), assertActive();
5786
5887
  },