@abloatai/humans 0.63.1 → 0.64.1

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.
Files changed (87) hide show
  1. package/dist/Ablo.d.ts +6 -0
  2. package/dist/client.d.ts +12 -32
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.js +1 -0
  5. package/dist/local/client/createModelOperations.d.ts +3 -3
  6. package/dist/local/client/createModelOperations.js +1 -1
  7. package/dist/local/client/reactiveEngine.js +7 -8
  8. package/dist/{react/useSyncStatus.d.ts → local/client/status.d.ts} +4 -3
  9. package/dist/local/client/status.js +14 -0
  10. package/dist/local/client/storeLifecycle.js +2 -2
  11. package/dist/local/mutators/defineMutators.d.ts +3 -48
  12. package/dist/local/mutators/defineMutators.js +0 -15
  13. package/dist/local/storeAccess.d.ts +7 -0
  14. package/dist/local/storeAccess.js +6 -0
  15. package/dist/local/storeContract.d.ts +3 -4
  16. package/dist/presence/index.d.ts +2 -2
  17. package/dist/presence/index.js +8 -4
  18. package/dist/react/AbloProvider.d.ts +57 -121
  19. package/dist/react/AbloProvider.js +55 -160
  20. package/dist/react/context.d.ts +6 -45
  21. package/dist/react/context.js +8 -20
  22. package/dist/react/createAbloReact.d.ts +13 -48
  23. package/dist/react/createAbloReact.js +8 -54
  24. package/dist/react/internalContext.d.ts +1 -27
  25. package/dist/react/snapshot.d.ts +4 -0
  26. package/dist/react/snapshot.js +75 -0
  27. package/dist/react/useAblo.d.ts +28 -92
  28. package/dist/react/useAblo.js +36 -93
  29. package/dist/react/useAbloClient.d.ts +5 -0
  30. package/dist/react/useAbloClient.js +9 -0
  31. package/dist/react/useMutationFailure.d.ts +6 -0
  32. package/dist/react/useMutationFailure.js +11 -0
  33. package/dist/react/useMutators.d.ts +22 -19
  34. package/dist/react/useMutators.js +3 -3
  35. package/dist/react/usePresence.d.ts +9 -9
  36. package/dist/react/usePresence.js +8 -11
  37. package/dist/react/useReactive.d.ts +12 -0
  38. package/dist/react/useReactive.js +57 -0
  39. package/dist/react/useUndoScope.d.ts +16 -30
  40. package/dist/react/useUndoScope.js +21 -4
  41. package/dist/react.d.ts +9 -19
  42. package/dist/react.js +9 -15
  43. package/dist/reactRuntime.d.ts +1 -1
  44. package/dist/reactRuntime.js +1 -1
  45. package/package.json +4 -3
  46. package/src/Ablo.ts +7 -0
  47. package/src/client.ts +13 -32
  48. package/src/index.ts +2 -0
  49. package/src/local/client/createModelOperations.ts +4 -4
  50. package/src/local/client/reactiveEngine.ts +7 -8
  51. package/src/local/client/status.ts +20 -0
  52. package/src/local/client/storeLifecycle.ts +2 -2
  53. package/src/local/mutators/defineMutators.ts +3 -51
  54. package/src/local/storeAccess.ts +10 -0
  55. package/src/local/storeContract.ts +3 -4
  56. package/src/presence/index.ts +10 -5
  57. package/src/react/AbloProvider.tsx +88 -263
  58. package/src/react/context.ts +10 -61
  59. package/src/react/createAbloReact.ts +16 -125
  60. package/src/react/internalContext.ts +1 -27
  61. package/src/react/snapshot.ts +67 -0
  62. package/src/react/useAblo.ts +73 -209
  63. package/src/react/useAbloClient.ts +14 -0
  64. package/src/react/useMutationFailure.ts +17 -0
  65. package/src/react/useMutators.ts +36 -32
  66. package/src/react/usePresence.ts +22 -27
  67. package/src/react/useReactive.ts +56 -0
  68. package/src/react/useUndoScope.ts +24 -20
  69. package/src/react.ts +9 -69
  70. package/src/reactRuntime.ts +2 -2
  71. package/dist/react/ClientSideSuspense.d.ts +0 -36
  72. package/dist/react/ClientSideSuspense.js +0 -17
  73. package/dist/react/useCurrentUserId.d.ts +0 -2
  74. package/dist/react/useCurrentUserId.js +0 -12
  75. package/dist/react/useErrorListener.d.ts +0 -2
  76. package/dist/react/useErrorListener.js +0 -14
  77. package/dist/react/useMutationFailureListener.d.ts +0 -8
  78. package/dist/react/useMutationFailureListener.js +0 -19
  79. package/dist/react/useSyncStatus.js +0 -48
  80. package/dist/useReactive.d.ts +0 -6
  81. package/dist/useReactive.js +0 -41
  82. package/src/react/ClientSideSuspense.tsx +0 -57
  83. package/src/react/useCurrentUserId.ts +0 -17
  84. package/src/react/useErrorListener.ts +0 -22
  85. package/src/react/useMutationFailureListener.ts +0 -34
  86. package/src/react/useSyncStatus.ts +0 -53
  87. package/src/useReactive.ts +0 -49
@@ -2,7 +2,6 @@
2
2
 
3
3
  import {
4
4
  useCallback,
5
- useContext,
6
5
  useEffect,
7
6
  useMemo,
8
7
  useRef,
@@ -12,15 +11,11 @@ import {
12
11
  } from 'react';
13
12
  import type { Schema, SchemaRecord } from '@abloatai/transaction/schema/schema';
14
13
  import type { AbloClient as Ablo } from '../client.js';
15
- import type { PresenceSession } from '@abloatai/transaction/presence';
16
- import type { GroupScope } from '../local/sync/scopeGroups.js';
17
- import { resolveScopeGroups } from '../local/sync/scopeGroups.js';
18
- import { SyncContext, type SyncStoreContract } from './context.js';
14
+ import { AbloStoreContext, type SyncStoreContract } from './context.js';
19
15
  import { AbloInternalContext, type AbloInternalContextValue } from './internalContext.js';
20
16
  import { AbloValidationError } from '@abloatai/transaction/errors';
21
- import { useSyncStatus } from './useSyncStatus.js';
17
+ import { useAblo } from './useAblo.js';
22
18
  import { DefaultFallback } from './DefaultFallback.js';
23
- import { presenceOfClient } from '../presence/index.js';
24
19
 
25
20
  /** Reactive binding over an application-owned client. Starts readiness,
26
21
  * forwards errors and gates bootstrap; the application owns client disposal.
@@ -46,107 +41,19 @@ import { presenceOfClient } from '../presence/index.js';
46
41
  * </AbloProvider>
47
42
  * ```
48
43
  *
49
- * That's it for most apps. `userId` is informational; the `fallback`,
44
+ * That's it for most apps. The `fallback`,
50
45
  * `preventUnsavedChanges`, and `on*` props are opt-in app glue; and the
51
46
  * block tagged "Optional DI (advanced)" below is escape-hatch wiring for
52
47
  * tests and platform builders — if you don't recognize a prop there, you
53
48
  * don't need it.
54
49
  */
55
- export interface AbloProviderProps<R extends SchemaRecord = SchemaRecord> {
56
- /**
57
- * A prebuilt {@link Ablo} client — **the only way to configure the engine.**
58
- * Construct it yourself with `Ablo({ schema, apiKey, ... })` and pass the
59
- * instance: the CLIENT owns auth, the credential lifecycle, transport, and
60
- * connection; this provider is the thin REACTIVE binding over it (context,
61
- * the bootstrap gate, error/​session forwarding).
62
- *
63
- * Memoize it (build it once, e.g. with `useMemo` or module scope) — a new
64
- * instance each render re-keys the bootstrap gate and tears down the socket.
65
- */
66
- client: Ablo<R>;
67
-
68
- /**
69
- * The app user id, surfaced via `useCurrentUserId()` for app-owned fields.
70
- * Purely informational for the React tree — sync identity is resolved by the
71
- * client from its auth, not from this. Optional.
72
- */
73
- userId?: string;
74
-
75
- /**
76
- * Block tab close while there are unsynced local writes (the standard
77
- * `beforeunload` prompt). Browsers ignore custom messages — don't pass one.
78
- */
79
- preventUnsavedChanges?: boolean;
80
-
81
- /**
82
- * Fired after the client has completed its terminal authentication cleanup
83
- * (or surfaced a cleanup failure). Use it for app side effects such as a
84
- * redirect to sign-in or clearing analytics identity.
85
- */
86
- onSessionExpired?: () => void | Promise<void>;
87
-
88
- /**
89
- * Fired on any error the provider surfaces (engine/WebSocket/bootstrap). For
90
- * Sentry/Datadog. React-only consumers can use `useErrorListener()` instead.
91
- */
92
- onError?: (error: Error) => void;
93
-
94
- /** @internal placeholder so the old WS-URL prop shape doesn't silently leak in. */
95
- url?: never;
96
-
97
- /**
98
- * Rendered in place of `children` during the *first* bootstrap pass —
99
- * while the engine is actively transitioning from `initial` →
100
- * `connected` and has never successfully connected before. Once the
101
- * engine reaches `connected` the gate latches open for the lifetime
102
- * of this provider instance; transient `reconnecting` / `needs-auth`
103
- * states do NOT re-show the fallback (the app's own UI handles those
104
- * by then).
105
- *
106
- * Defaults to `<DefaultFallback />` — a neutral theme-adaptive
107
- * spinner that uses `currentColor`, ships with zero design-system
108
- * dependencies, and self-centers in a full-parent container. Pass
109
- * your own `<Skeleton />` for a branded loading UX. Pass `null` to
110
- * render nothing during bootstrap. Pass the string literal
111
- * `"passthrough"` to opt out of the gate entirely — children render
112
- * immediately and consumers are responsible for their own gating
113
- * (`<ClientSideSuspense>` or manual `useSyncStatus()` checks).
114
- * Useful for pages that mount debug helpers, error boundaries, or
115
- * analytics that must run pre-ready.
116
- */
117
- fallback?: ReactNode | 'passthrough';
118
-
119
- children: ReactNode;
120
- }
121
-
122
50
  // ── Implementation ───────────────────────────────────────────────────
123
51
 
124
- /**
125
- * Lightweight event emitter for provider-level errors. Lives on the
126
- * provider instance (ref-based) so `useErrorListener` subscriptions
127
- * survive re-renders without thrashing.
128
- */
129
- function createErrorEmitter() {
130
- const listeners = new Set<(err: Error) => void>();
131
- return {
132
- subscribe(fn: (err: Error) => void): () => void {
133
- listeners.add(fn);
134
- return () => { listeners.delete(fn); };
135
- },
136
- emit(err: Error): void {
137
- for (const fn of listeners) {
138
- try { fn(err); } catch {}
139
- }
140
- },
141
- };
142
- }
143
-
144
52
  export function AbloProvider<R extends SchemaRecord = SchemaRecord>(
145
- props: AbloProviderProps<R>,
53
+ props: AbloProvider.Props<R>,
146
54
  ): React.ReactElement {
147
55
  const {
148
56
  client,
149
- userId,
150
57
  preventUnsavedChanges,
151
58
  onSessionExpired,
152
59
  onError,
@@ -168,20 +75,13 @@ export function AbloProvider<R extends SchemaRecord = SchemaRecord>(
168
75
  // resolves the identity from the client's auth.
169
76
  const [resolvedScope, setResolvedScope] = useState<{ engine: typeof engine; account: string | null } | null>(null);
170
77
 
171
- // ── Error emitter (provider-instance scoped) ─────────────────────
172
- const errorEmitterRef = useRef<ReturnType<typeof createErrorEmitter> | null>(null);
173
- if (!errorEmitterRef.current) {
174
- errorEmitterRef.current = createErrorEmitter();
175
- }
176
- const errorEmitter = errorEmitterRef.current;
177
-
178
78
  // Stash callbacks in refs so a new identity each render doesn't re-run the
179
79
  // start effect (the `useEventCallback` idiom).
180
80
  const onErrorRef = useRef(onError);
181
81
  onErrorRef.current = onError;
182
- useEffect(() => {
183
- return errorEmitter.subscribe((err) => onErrorRef.current?.(err));
184
- }, [errorEmitter]);
82
+ const reportError = useCallback((error: Error) => {
83
+ try { onErrorRef.current?.(error); } catch { /* Error reporting must not interrupt session cleanup. */ }
84
+ }, []);
185
85
  const onSessionExpiredRef = useRef(onSessionExpired);
186
86
  onSessionExpiredRef.current = onSessionExpired;
187
87
 
@@ -200,21 +100,21 @@ export function AbloProvider<R extends SchemaRecord = SchemaRecord>(
200
100
  // onSessionExpired. Credential cleanup lives in the CLIENT, so direct
201
101
  // consumers and React consumers have the same security boundary.
202
102
  // 2. Drive `ready()` (idempotent) so bootstrap starts on mount, then read the
203
- // resolved org scope for SyncContext.
103
+ // resolved org scope for the Ablo store context.
204
104
  // It does NOT dispose the client (consumer-owned) and does NOT touch auth.
205
105
  useEffect(() => {
206
106
  let stale = false;
207
107
 
208
108
  const unsubscribeSession = engine.onSessionError((err) => {
209
- errorEmitter.emit(err);
109
+ reportError(err);
210
110
  void (async () => {
211
111
  try {
212
112
  await onSessionExpiredRef.current?.();
213
113
  } catch (hookErr) {
214
- errorEmitter.emit(hookErr as Error);
114
+ reportError(hookErr as Error);
215
115
  }
216
116
  })().catch(() => {
217
- // Only a throwing errorEmitter subscriber can land here — it was
117
+ // This was
218
118
  // already the error-reporting path, so swallow rather than surface
219
119
  // an unhandled rejection loop.
220
120
  });
@@ -231,14 +131,14 @@ export function AbloProvider<R extends SchemaRecord = SchemaRecord>(
231
131
  })
232
132
  .catch((err) => {
233
133
  if (stale) return;
234
- errorEmitter.emit(err as Error);
134
+ reportError(err as Error);
235
135
  });
236
136
 
237
137
  return () => {
238
138
  stale = true;
239
139
  unsubscribeSession();
240
140
  };
241
- }, [engine, errorEmitter]);
141
+ }, [engine, reportError]);
242
142
 
243
143
  // ── beforeunload + preventUnsavedChanges ─────────────────────────
244
144
 
@@ -258,12 +158,12 @@ export function AbloProvider<R extends SchemaRecord = SchemaRecord>(
258
158
  return () => { window.removeEventListener('beforeunload', handler); };
259
159
  }, [engine, preventUnsavedChanges]);
260
160
 
261
- // ── SyncContext value (for useQuery/useOne/useMutate hooks) ──────
161
+ // ── Store context value (for Ablo data hooks) ────────────────────
262
162
  //
263
163
  // The engine is always present (it's the `client` prop), but its org scope is
264
- // unknown until `ready()` resolves identity — so `syncValue` is null until
164
+ // unknown until `ready()` resolves identity — so the store context is null until
265
165
  // then, which drives the initial fallback below.
266
- const syncValue = useMemo(() => {
166
+ const storeContextValue = useMemo(() => {
267
167
  const currentAccountScope =
268
168
  (resolvedScope?.engine === engine ? resolvedScope.account : null) ??
269
169
  (engine._store as SyncStoreContract & { orgId?: string }).orgId;
@@ -275,14 +175,11 @@ export function AbloProvider<R extends SchemaRecord = SchemaRecord>(
275
175
  };
276
176
  }, [engine, resolvedScope, schema]);
277
177
 
278
- // ── Internal context (currentUserId + error subscription) ────────
178
+ // The React tree holds the same client used by core code.
279
179
 
280
180
  const internalValue = useMemo<AbloInternalContextValue>(() => ({
281
- currentUserId: userId ?? null,
282
- subscribeError: errorEmitter.subscribe,
283
- emitError: errorEmitter.emit,
284
181
  engine: engine as Ablo<SchemaRecord>,
285
- }), [userId, errorEmitter, engine]);
182
+ }), [engine]);
286
183
 
287
184
  // ── Render ───────────────────────────────────────────────────────
288
185
  //
@@ -292,15 +189,15 @@ export function AbloProvider<R extends SchemaRecord = SchemaRecord>(
292
189
 
293
190
  return (
294
191
  <AbloInternalContext.Provider value={internalValue}>
295
- <SyncContext.Provider value={syncValue}>
192
+ <AbloStoreContext.Provider value={storeContextValue}>
296
193
  {passthrough ? (
297
194
  children
298
- ) : syncValue ? (
195
+ ) : storeContextValue ? (
299
196
  <BootstrapGate key={engineKey} fallback={fallback}>
300
197
  {children}
301
198
  </BootstrapGate>
302
199
  ) : fallback}
303
- </SyncContext.Provider>
200
+ </AbloStoreContext.Provider>
304
201
  </AbloInternalContext.Provider>
305
202
  );
306
203
  }
@@ -323,155 +220,83 @@ function BootstrapGate({
323
220
  readonly fallback: ReactNode;
324
221
  readonly children: ReactNode;
325
222
  }): ReactNode {
326
- const status = useSyncStatus();
223
+ const status = useAblo(ablo => ablo.status);
327
224
  const [everConnected, setEverConnected] = useState(false);
328
225
 
329
226
  useEffect(() => {
330
227
  if (
331
- status.name === 'connected' ||
332
- status.name === 'reconnecting' ||
333
- status.name === 'disconnected'
228
+ status?.name === 'connected' ||
229
+ status?.name === 'reconnecting' ||
230
+ status?.name === 'disconnected'
334
231
  ) {
335
232
  setEverConnected(true);
336
233
  }
337
- }, [status.name]);
234
+ }, [status?.name]);
338
235
 
339
- const showFallback = !everConnected && status.name === 'connecting';
236
+ const showFallback = !everConnected && status?.name === 'connecting';
340
237
  return <>{showFallback ? fallback : children}</>;
341
238
  }
342
239
 
343
-
344
- const EMPTY_PRESENCE: readonly PresenceSession[] = Object.freeze([]);
345
-
346
- export type { GroupScope };
347
-
348
- /**
349
- * Read-only presence: the other sessions currently visible to this
350
- * connection, bridged to React. This is a pure reader of the engine's
351
- * already-flowing presence stream; it does not mutate connection groups.
352
- *
353
- * Pass `scope` to narrow to the peers on that scope's sync group(s); omit
354
- * it to get everyone on the engine's groups. Membership is driven entirely
355
- * by the presence channel (set server-side on connect, independent of any
356
- * cursor/collaboration traffic), so reading it never affects what the
357
- * connection is subscribed to and can't deadlock against a gated channel.
358
- *
359
- * Use this to answer "is anyone else here?", for example to suppress
360
- * live-cursor broadcasts while alone.
361
- *
362
- * ```ts
363
- * const peers = usePeers({ reports: reportId });
364
- * const alone = !peers.some((p) => p.participantKind === 'user');
365
- * ```
366
- */
367
- export function usePeers(scope?: GroupScope): readonly PresenceSession[] {
368
- const ctx = useContext(AbloInternalContext);
369
- const engine = ctx?.engine ?? null;
370
-
371
- // Resolve scope → groups through the schema.
372
- // The stringified, sorted key is the stable effect dependency.
373
- const scopeKey = JSON.stringify(
374
- resolveScopeGroups(scope, engine?.schema).sort(),
375
- );
376
- const groups = useMemo(() => JSON.parse(scopeKey) as string[], [scopeKey]);
377
-
378
- const [peers, setPeers] = useState<readonly PresenceSession[]>(EMPTY_PRESENCE);
379
-
380
- useEffect(() => {
381
- if (!engine) {
382
- setPeers(EMPTY_PRESENCE);
383
- return;
384
- }
385
- const presence = presenceOfClient(engine);
386
- const compute = (): readonly PresenceSession[] =>
387
- groups.length === 0
388
- ? presence.others
389
- : presence.others.filter((session) =>
390
- session.activities.some(({ target }) =>
391
- target.id !== undefined && groups.includes(
392
- `${target.model.toLowerCase()}:${target.id}`,
393
- ),
394
- ),
395
- );
396
- // Plain useState + onChange — presence changes on connect/disconnect/activity
397
- // only (never on cursor traffic, a separate channel), so this fires
398
- // rarely; a frame of stale presence is harmless.
399
- setPeers(compute());
400
- return presence.onChange(() => { setPeers(compute()); });
401
- }, [engine, groups, scopeKey]);
402
-
403
- return peers;
404
- }
405
-
406
- // ── Escape-hatches: raw engine/store access ──────────────────────────
407
-
408
- /**
409
- * Returns the raw `SyncEngine` proxy. Typically you want the typed
410
- * hooks (`useQuery`, `useOne`, `useMutate`) — this is for rare cases
411
- * where you need direct access (e.g., `sync.items.onChange(cb)`).
412
- *
413
- * The generic parameter narrows the return type to your schema's
414
- * model record so call sites get typed `sync.items.findMany()` /
415
- * `sync.sections.create(...)` without a cast at the call site:
416
- *
417
- * ```ts
418
- * const sync = useSync<(typeof schema)['models']>();
419
- * ```
420
- *
421
- * The runtime value is the exact engine the provider constructed;
422
- * the generic just widens the compile-time type.
423
- */
424
- export function useSync<R extends SchemaRecord = SchemaRecord>(): Ablo<R> {
425
- const ctx = useContext(AbloInternalContext);
426
- if (!ctx) {
427
- throw new AbloValidationError(
428
- 'useSync: no <AbloProvider> mounted above this component.',
429
- { code: 'no_ablo_provider' },
430
- );
431
- }
432
- if (!ctx.engine) {
433
- throw new AbloValidationError(
434
- 'useSync: the sync engine has not yet initialized. Wrap your ' +
435
- 'consumer in <ClientSideSuspense> or guard on useSyncStatus().',
436
- { code: 'sync_not_ready' },
437
- );
438
- }
439
- return rebindProviderEngine(ctx.engine);
440
- }
441
-
442
- function rebindProviderEngine<R extends SchemaRecord>(
443
- engine: Ablo<SchemaRecord>,
444
- ): Ablo<R> {
445
- return engine as Ablo<R>;
446
- }
447
-
448
- /**
449
- * Returns the underlying `SyncStoreContract` (the BaseSyncedStore).
450
- * Most consumers should prefer the typed hooks (`useQuery` etc.); this
451
- * is for advanced cases like direct InstanceCache access or custom
452
- * reactive bridges. Throws if the provider hasn't mounted the store
453
- * yet — wrap consumers in `<ClientSideSuspense>` to gate correctly.
454
- *
455
- * The generic parameter lets consumers widen the return type to a
456
- * concrete `BaseSyncedStore<...>` subclass if they track one:
457
- *
458
- * ```ts
459
- * type AppStore = BaseSyncedStore<AppEvents, typeof schema>;
460
- * const store = useSyncStore<AppStore>(); // no cast needed at call site
461
- * ```
462
- *
463
- * The runtime value is always the concrete store the SDK constructed,
464
- * so widening the type is safe. The bounded generic (`T extends
465
- * SyncStoreContract`) keeps the widening honest.
466
- */
467
- export function useSyncStore<T extends SyncStoreContract = SyncStoreContract>(): T {
468
- const sync = useContext(SyncContext);
469
- if (!sync?.store) {
470
- throw new AbloValidationError(
471
- 'useSyncStore: the sync engine has not yet initialized. Wrap ' +
472
- 'consumers in <ClientSideSuspense> or guard on useSyncStatus().',
473
- { code: 'sync_not_ready' },
474
- );
240
+ /** Props for wrappers around the provider, using the same schema parameter. */
241
+ // eslint-disable-next-line @typescript-eslint/no-namespace
242
+ export namespace AbloProvider {
243
+ export interface Props<R extends SchemaRecord = SchemaRecord> {
244
+ /**
245
+ * A prebuilt {@link Ablo} client — **the only way to configure the engine.**
246
+ * Construct it yourself with `Ablo({ schema, apiKey, ... })` and pass the
247
+ * instance: the CLIENT owns auth, the credential lifecycle, transport, and
248
+ * connection; this provider is the thin REACTIVE binding over it (context,
249
+ * the bootstrap gate, error/​session forwarding).
250
+ *
251
+ * Memoize it (build it once, e.g. with `useMemo` or module scope) — a new
252
+ * instance each render re-keys the bootstrap gate and tears down the socket.
253
+ */
254
+ client: Ablo<R>;
255
+
256
+ /**
257
+ * Block tab close while there are unsynced local writes (the standard
258
+ * `beforeunload` prompt). Browsers ignore custom messages — don't pass one.
259
+ */
260
+ preventUnsavedChanges?: boolean;
261
+
262
+ /**
263
+ * Fired after the client has completed its terminal authentication cleanup
264
+ * (or surfaced a cleanup failure). Use it for app side effects such as a
265
+ * redirect to sign-in or clearing analytics identity.
266
+ */
267
+ onSessionExpired?: () => void | Promise<void>;
268
+
269
+ /**
270
+ * Fired on any error the provider surfaces (engine/WebSocket/bootstrap). For
271
+ * Sentry/Datadog or application error UI.
272
+ */
273
+ onError?: (error: Error) => void;
274
+
275
+ /** @internal placeholder so the old WS-URL prop shape doesn't silently leak in. */
276
+ url?: never;
277
+
278
+ /**
279
+ * Rendered in place of `children` during the *first* bootstrap pass —
280
+ * while the engine is actively transitioning from `initial` →
281
+ * `connected` and has never successfully connected before. Once the
282
+ * engine reaches `connected` the gate latches open for the lifetime
283
+ * of this provider instance; transient `reconnecting` / `needs-auth`
284
+ * states do NOT re-show the fallback (the app's own UI handles those
285
+ * by then).
286
+ *
287
+ * Defaults to `<DefaultFallback />` — a neutral theme-adaptive
288
+ * spinner that uses `currentColor`, ships with zero design-system
289
+ * dependencies, and self-centers in a full-parent container. Pass
290
+ * your own `<Skeleton />` for a branded loading UX. Pass `null` to
291
+ * render nothing during bootstrap. Pass the string literal
292
+ * `"passthrough"` to opt out of the gate entirely — children render
293
+ * immediately and consumers are responsible for their own gating
294
+ * (for example, `useAblo(ablo => ablo.status)` checks).
295
+ * Useful for pages that mount debug helpers, error boundaries, or
296
+ * analytics that must run pre-ready.
297
+ */
298
+ fallback?: ReactNode | 'passthrough';
299
+
300
+ children: ReactNode;
475
301
  }
476
- return sync.store as T;
477
302
  }
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
 
3
- import { createContext, createElement, useContext, type ReactNode } from 'react';
3
+ import { createContext, useContext } from 'react';
4
4
  import type { Schema } from '@abloatai/transaction/schema/schema';
5
5
  import type { SyncStoreContract } from '../local/storeContract.js';
6
6
  import { AbloValidationError } from '@abloatai/transaction/errors';
@@ -13,77 +13,26 @@ export type {
13
13
  LocalMutation,
14
14
  } from '../local/storeContract.js';
15
15
 
16
- export interface SyncReactContext {
16
+ export interface AbloStoreContextValue {
17
17
  store: SyncStoreContract;
18
18
  /** The organization id used as the default scope for reads and writes. */
19
19
  organizationId: string;
20
- /**
21
- * An optional schema. When provided, hooks that take a model by name (such as
22
- * `useQuery('items')`) read that model's metadata from this schema, so
23
- * callers don't pass a schema at every call site. When omitted, those hooks
24
- * require the schema as an argument instead.
25
- *
26
- * The field is loosely typed here because a single runtime context value is
27
- * shared by every hook. Precise per-model types come from your `Register`
28
- * module augmentation
29
- * (`declare module '@abloatai/ablo' { interface Register { Schema: typeof schema } }`),
30
- * not from this reference.
31
- */
20
+ /** Runtime schema used by ambient mutator overloads. */
32
21
  schema?: Schema;
33
22
  }
34
23
 
35
- export const SyncContext = createContext<SyncReactContext | null>(null);
24
+ export const AbloStoreContext = createContext<AbloStoreContextValue | null>(null);
36
25
 
37
26
  /**
38
- * Reads the sync store context from inside a provider subtree, throwing a clear
39
- * error when no provider is mounted above. `<AbloProvider>` supplies this
40
- * context by rendering the internal {@link SyncProvider}; you wire
41
- * `<AbloProvider client={ablo}>` rather than touching this directly.
27
+ * Reads the store scope owned by `<AbloProvider>`, throwing a clear error when
28
+ * no provider is mounted above it.
42
29
  */
43
- export function useSyncContext(): SyncReactContext {
44
- const ctx = useContext(SyncContext);
30
+ export function useAbloStoreContext(): AbloStoreContextValue {
31
+ const ctx = useContext(AbloStoreContext);
45
32
  if (!ctx) {
46
- throw new AbloValidationError('Sync hooks must be used within an <AbloProvider>.', {
47
- code: 'sync_context_missing_provider',
33
+ throw new AbloValidationError('Ablo hooks must be used within an <AbloProvider>.', {
34
+ code: 'ablo_context_missing_provider',
48
35
  });
49
36
  }
50
37
  return ctx;
51
38
  }
52
-
53
- /**
54
- * Props for SyncProvider.
55
- */
56
- export interface SyncProviderProps {
57
- /** The sync store, which must implement {@link SyncStoreContract}. */
58
- store: SyncStoreContract;
59
- /** The organization id used as the default scope for reads and writes. */
60
- organizationId: string;
61
- /**
62
- * An optional schema. Provide it to enable hooks that take a model by name
63
- * (such as `useQuery('items')`); the model types also narrow through your
64
- * `Register` augmentation. Omit it to pass the schema to those hooks directly
65
- * instead.
66
- */
67
- schema?: Schema;
68
- children?: ReactNode;
69
- }
70
-
71
- /**
72
- * A low-level provider that places a built sync store on React context so the
73
- * data hooks can reach it. This is an internal building block: it is not part
74
- * of the package's public entry point. Reach for `<AbloProvider>` instead,
75
- * which builds the store from your `Ablo({ schema, apiKey })` client and
76
- * renders this provider underneath.
77
- */
78
- export function SyncProvider({
79
- store,
80
- organizationId,
81
- schema,
82
- children,
83
- }: SyncProviderProps) {
84
- return createElement(
85
- SyncContext.Provider,
86
- { value: { store, organizationId, schema } },
87
- children
88
- );
89
- }