@layers/amba-react-native 4.0.3 → 4.0.5

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/index.d.ts CHANGED
@@ -138,15 +138,66 @@ interface PushToken {
138
138
  bundle_id?: string | null;
139
139
  created_at: string;
140
140
  }
141
- type EntitlementSource = "revenue_cat" | "app_store" | "play_store" | "stripe" | "promo_code" | "manual";
141
+ /**
142
+ * Store an entitlement's purchase resolved from. `"web"` is the neutral bucket
143
+ * for any non-native checkout (it replaced the former `"stripe"` value).
144
+ */
145
+ type EntitlementStore = "app_store" | "play_store" | "web";
146
+ /** Lifecycle phase of the subscription period backing the entitlement. */
147
+ type EntitlementPeriodType = "trial" | "intro" | "normal";
148
+ /**
149
+ * A server-evaluated entitlement grant, mirroring the
150
+ * `GET /v1/client/entitlements` response field-for-field. `store` and
151
+ * `period_type` are nullable, CHECK-constrained text columns, typed
152
+ * loosely (`… | (string & {}) | null`) so an unexpected value from a newer
153
+ * server never breaks decoding while still autocompleting the known set.
154
+ */
142
155
  interface UserEntitlement {
143
- id: string;
144
- name: string;
156
+ /** Project-defined entitlement key (e.g. `"pro"`) — what `has()` checks. */
157
+ entitlement_id: string;
145
158
  is_active: boolean;
146
- source: EntitlementSource;
147
- expires_at?: string | null;
148
- granted_at?: string | null;
159
+ product_id?: string | null;
160
+ store?: EntitlementStore | (string & {}) | null;
161
+ purchase_date?: string | null;
162
+ expiration_date?: string | null;
163
+ period_type?: EntitlementPeriodType | (string & {}) | null;
164
+ }
165
+ /** Result of `entitlements.restore()` — the active set after a server re-sync. */
166
+ interface RestoreResult {
167
+ restored_count: number;
168
+ entitlements: UserEntitlement[];
169
+ }
170
+ /** A product behind an offering package (provider-neutral). */
171
+ interface OfferingProduct {
172
+ product_id: string;
173
+ display_name?: string | null;
174
+ description?: string | null;
175
+ product_type?: string | null;
176
+ /** Map of neutral store id → that store's product identifier. */
177
+ store_product_refs: Record<string, string>;
178
+ grants_entitlement_id?: string | null;
179
+ trial_period_days?: number | null;
180
+ duration?: string | null;
181
+ }
182
+ /** A package — one product at a position within an offering. */
183
+ interface OfferingPackage {
184
+ package_id: string;
185
+ position: number;
149
186
  metadata: Record<string, unknown>;
187
+ product: OfferingProduct | null;
188
+ }
189
+ interface Offering {
190
+ offering_id: string;
191
+ display_name?: string | null;
192
+ description?: string | null;
193
+ current: boolean;
194
+ metadata: Record<string, unknown>;
195
+ packages: OfferingPackage[];
196
+ }
197
+ /** The shape `offerings()` returns. */
198
+ interface OfferingsResult {
199
+ offerings: Offering[];
200
+ current_offering_id: string | null;
150
201
  }
151
202
  interface AiMessage {
152
203
  role: string;
@@ -588,8 +639,8 @@ interface UserPatch {
588
639
  /**
589
640
  * One row from `Amba.sessions.list` — a server-tracked customer-defined
590
641
  * app session row. Mirrors the `toSdkSession` projection in
591
- * `apps/api/src/routes/client/sessions.ts` and the Rust core's
592
- * `AppSession` struct (`sdks/core/src/sessions.rs`).
642
+ * `apps/api/src/routes/client/sessions.ts` and the SDK core's
643
+ * `AppSession` type.
593
644
  *
594
645
  * NOTE: this is NOT a device/auth session record — `/v1/client/sessions`
595
646
  * surfaces analytics-style `app_sessions` rows (open/background events).
@@ -611,7 +662,7 @@ interface SessionRecord {
611
662
  /**
612
663
  * One offline-replay change submitted to `Amba.sync.pushChanges`.
613
664
  * Mirrors `SyncPushInput.changes[]` in `apps/api/src/routes/client/sync.ts`
614
- * and the Rust core's `SyncChange` struct (`sdks/core/src/sync.rs`).
665
+ * and the SDK core's `SyncChange` type.
615
666
  * Server resolves conflicts server-wins.
616
667
  */
617
668
  interface SyncChange {
@@ -704,6 +755,315 @@ interface LeagueCohort {
704
755
  is_me?: boolean;
705
756
  }>;
706
757
  }
758
+ /**
759
+ * When a local notification should fire. Exactly one shape:
760
+ *
761
+ * - `{ at: Date }` — fire once at an absolute time.
762
+ * - `{ inSeconds, repeats? }` — fire after a relative delay; set
763
+ * `repeats: true` to re-fire on that interval (the OS enforces a
764
+ * minimum interval — typically ~60s on iOS for repeating triggers).
765
+ *
766
+ * Local notifications are scheduled and fired by the device itself, with
767
+ * no server involvement — distinct from remote push (`Amba.push.*`).
768
+ */
769
+ type LocalNotificationTrigger = {
770
+ at: Date | string;
771
+ } | {
772
+ inSeconds: number;
773
+ repeats?: boolean;
774
+ };
775
+ /** Input to `Amba.notifications.scheduleLocal`. */
776
+ interface ScheduleLocalNotificationInput {
777
+ /**
778
+ * Optional stable id. Supply your own to make scheduling idempotent
779
+ * and to control the value `cancelLocal` expects; omit to let the
780
+ * platform mint one (returned in the handle).
781
+ */
782
+ id?: string;
783
+ /** Notification title (required, non-empty). */
784
+ title: string;
785
+ /** Notification body text. */
786
+ body: string;
787
+ /** Arbitrary payload delivered to the app when the notification is tapped. */
788
+ data?: Record<string, unknown>;
789
+ /** When to fire it. */
790
+ trigger: LocalNotificationTrigger;
791
+ }
792
+ /** Handle returned by `scheduleLocal`; `id` is accepted by `cancelLocal`. */
793
+ interface LocalNotificationHandle {
794
+ id: string;
795
+ }
796
+ /** A pending local notification, as reported by `listScheduledLocal`. */
797
+ interface ScheduledLocalNotification {
798
+ id: string;
799
+ title: string;
800
+ body: string;
801
+ data?: Record<string, unknown>;
802
+ }
803
+ //#endregion
804
+ //#region src/resilience.d.ts
805
+ /**
806
+ * Offline mutation queue + optimistic-update helpers — framework-agnostic
807
+ * orchestration that sits ABOVE the collection / event write methods.
808
+ *
809
+ * Nothing here touches the SDK runtime directly: the queue is handed a
810
+ * small `KvStore` (durable key/value persistence) and a `WriteExecutor`
811
+ * (the function that actually performs a queued mutation against the API).
812
+ * That keeps the same code identical across every JS SDK target — only the
813
+ * adapters that supply storage + the executor differ per platform.
814
+ *
815
+ * Design:
816
+ * - A write that fails because the device is offline (a transport-level
817
+ * network error, or `navigator.onLine === false`) is appended to a
818
+ * durable outbox instead of throwing all the way up.
819
+ * - Each queued op carries a stable idempotency key. On replay the key is
820
+ * forwarded to the API's collection-write idempotency support so a
821
+ * mutation that actually reached the server before the connection
822
+ * dropped is never applied twice.
823
+ * - On reconnect (`online` event) the outbox is flushed in FIFO order;
824
+ * each op is removed only after it succeeds, so a mid-flush failure
825
+ * leaves the remainder intact for the next attempt.
826
+ */
827
+ /**
828
+ * Minimal durable key/value contract the outbox persists through. Both the
829
+ * browser `localStorage` adapter and the React Native AsyncStorage adapter
830
+ * satisfy this — the queue never assumes anything else.
831
+ */
832
+ interface KvStore {
833
+ get(key: string): Promise<string | null> | string | null;
834
+ set(key: string, value: string): Promise<void> | void;
835
+ delete(key: string): Promise<void> | void;
836
+ }
837
+ /** The kinds of mutation the outbox can durably replay. */
838
+ type OutboxOpKind = "collection.insert" | "collection.update" | "collection.delete" | "track";
839
+ /**
840
+ * A single durably-queued mutation. `idempotencyKey` is reused verbatim on
841
+ * every replay attempt so the server dedupes a COLLECTION write that landed
842
+ * before the connection dropped (the events `track` API has no idempotency
843
+ * channel, so `track` replays are at-least-once — a rare reconnect duplicate
844
+ * is acceptable for fire-and-forget analytics). `enqueuedAt` is an ISO
845
+ * timestamp for inspection.
846
+ */
847
+ interface OutboxOp {
848
+ /** Stable per-op id (the idempotency key for collection writes). */
849
+ idempotencyKey: string;
850
+ kind: OutboxOpKind;
851
+ /** Target collection name (absent for `track`). */
852
+ collection?: string;
853
+ /** Row id for update / delete. */
854
+ id?: string;
855
+ /** Insert row / update set payload. */
856
+ payload?: Record<string, unknown>;
857
+ /** Event name for `track`. */
858
+ event?: string;
859
+ /** Event properties for `track`. */
860
+ properties?: Record<string, unknown>;
861
+ /** Whether the tracked event was telemetry-tier. */
862
+ telemetry?: boolean;
863
+ /**
864
+ * ISO timestamp the `track` originally OCCURRED, captured at enqueue. Replayed
865
+ * as the events body `timestamp` (→ `occurred_at`) so a buffered event keeps
866
+ * its real time instead of being re-stamped at flush. (Attribution is by the
867
+ * session user at replay time — the events route has no body-id channel.)
868
+ */
869
+ occurredAt?: string;
870
+ enqueuedAt: string;
871
+ }
872
+ /** Result of a {@link OfflineQueue.flush}. */
873
+ interface FlushResult {
874
+ /** Ops successfully replayed and removed from the outbox. */
875
+ flushed: number;
876
+ /**
877
+ * Ops dropped because their replay failed deterministically (a coded server
878
+ * rejection like `VALIDATION_ERROR` / `NOT_FOUND` that would fail identically
879
+ * forever). Dropping them prevents one poisoned op from wedging the queue;
880
+ * the drain continues past it.
881
+ */
882
+ dropped: number;
883
+ /** Ops still pending after the flush (a replay failed and stopped it). */
884
+ remaining: number;
885
+ }
886
+ /**
887
+ * Apply a local change immediately, fire the real mutation, and roll the
888
+ * local change back if the mutation fails. Framework-agnostic: `apply` and
889
+ * `rollback` operate on whatever local view you hand them (a React state
890
+ * setter, a store, an in-memory cache).
891
+ *
892
+ * Resolves with the mutation's result on success. On failure it invokes
893
+ * `rollback` (with the value `apply` returned, so you can restore a captured
894
+ * snapshot) and rethrows the original error.
895
+ *
896
+ * @example
897
+ * await withOptimistic({
898
+ * apply: () => { const prev = todos; setTodos([...todos, draft]); return prev; },
899
+ * mutate: () => Amba.collections.insert("todos", draft),
900
+ * rollback: (prev) => setTodos(prev),
901
+ * });
902
+ */
903
+ declare function withOptimistic<TApply, TResult>(spec: {
904
+ /** Mutate the local view now. Return a snapshot for `rollback` to restore. */
905
+ apply: () => TApply;
906
+ /** The real async mutation against the API. */
907
+ mutate: () => Promise<TResult>;
908
+ /** Undo the local change. Receives whatever `apply` returned. */
909
+ rollback: (applied: TApply) => void;
910
+ }): Promise<TResult>;
911
+ //#endregion
912
+ //#region src/push-rotation.d.ts
913
+ /**
914
+ * A platform token-refresh subscription primitive. Given a handler that
915
+ * receives the new token string, it must invoke that handler on every rotation
916
+ * and return an unsubscribe function. `Notifications.addPushTokenListener`
917
+ * (Expo) adapts to this directly.
918
+ */
919
+ type TokenRefreshSubscribe = (handler: (token: string) => void) => () => void;
920
+ //#endregion
921
+ //#region src/realtime.d.ts
922
+ /**
923
+ * Live collection / messaging / gamification subscriptions for
924
+ * `@layers/amba-react-native`.
925
+ *
926
+ * Public surface is byte-for-byte identical to `@layers/amba-web` and
927
+ * `@layers/amba-node` so the docs are uniform across every JS SDK:
928
+ *
929
+ * const unsub = Amba.collection("messages")
930
+ * .where("circle_id", circleId)
931
+ * .subscribe((change) => {
932
+ * // change.op: "INSERT" | "UPDATE" | "DELETE"; change.row: the row
933
+ * });
934
+ * unsub(); // stop listening
935
+ *
936
+ * const unsub2 = Amba.messaging
937
+ * .conversation(conversationId)
938
+ * .subscribe((change) => { ... });
939
+ *
940
+ * const unsub3 = Amba.gamification.subscribe((change) => { ... });
941
+ *
942
+ * ── Why a different transport from web/node ─────────────────────────────
943
+ * The web/node SDKs read the streamed HTTP response body via
944
+ * `response.body.getReader()`. React Native's `fetch` (Hermes / RN's
945
+ * networking layer) resolves the Response only AFTER the body is fully
946
+ * received and does NOT expose a readable `body` stream — so the web
947
+ * transport silently never delivers a frame on a long-lived connection.
948
+ *
949
+ * Instead we drive the SAME server endpoint (an event stream) through
950
+ * `XMLHttpRequest`, which RN implements with INCREMENTAL `responseText`:
951
+ * `onreadystatechange` fires at `readyState === 3` (LOADING) as bytes
952
+ * arrive, so we parse the newly-appended slice frame-by-frame. This is the
953
+ * mechanism `react-native-sse` uses under the hood; we inline it to avoid a
954
+ * peer dependency (and to set the auth header in `Authorization`, keeping
955
+ * the session token out of the URL/query string where it would leak into
956
+ * access logs — `EventSource` can't set headers).
957
+ *
958
+ * If XHR is somehow unavailable in the host runtime, we fall back to the
959
+ * web-style `fetch` + streamed-body reader (works on RN-for-web / any
960
+ * runtime that does expose `response.body`). Both transports speak the
961
+ * exact same wire frames, so the public behaviour is identical.
962
+ *
963
+ * Reconnect/backoff and frame parsing match web/node exactly.
964
+ */
965
+ type RowChangeOp = "INSERT" | "UPDATE" | "DELETE";
966
+ interface RealtimeChange<T = unknown> {
967
+ /** Which kind of write happened. */
968
+ op: RowChangeOp;
969
+ /**
970
+ * The affected row. For deletes this is a partial row (at minimum `id`).
971
+ * If the row was too large to deliver inline, `truncated` is `true` and
972
+ * `row` carries just `id` — re-fetch with `Amba.collections.find()` /
973
+ * `findOne()` when you need the full body.
974
+ */
975
+ row: T;
976
+ truncated?: boolean;
977
+ }
978
+ interface SubscribeOptions {
979
+ /** Called once when the live connection is (re)established. */
980
+ onOpen?: () => void;
981
+ /** Called on a connection error before the SDK retries. */
982
+ onError?: (err: unknown) => void;
983
+ }
984
+ /** Unsubscribe handle returned by `.subscribe(...)`. Call it to stop. */
985
+ type Unsubscribe = () => void;
986
+ /**
987
+ * Auth + endpoint context for a subscription. `authHeaders` is read lazily
988
+ * at connect time so reconnects pick up a rotated session token. Returns
989
+ * `null` when there's no live session (subscribe throws).
990
+ */
991
+ interface RealtimeContext {
992
+ baseUrl: string;
993
+ authHeaders: () => Record<string, string> | null;
994
+ }
995
+ /**
996
+ * Builder returned by `Amba.collection(name)`. Chain `.where(...)` to
997
+ * narrow, then `.subscribe(cb)` to start streaming.
998
+ */
999
+ declare class CollectionSubscription<T = unknown> {
1000
+ private readonly ctx;
1001
+ private readonly name;
1002
+ private readonly filters;
1003
+ constructor(ctx: RealtimeContext, name: string);
1004
+ /** Add an equality filter. Chainable. All filters must match (AND). */
1005
+ where(column: string, value: unknown): this;
1006
+ /**
1007
+ * Start listening. `cb` fires once per matching row change. Returns an
1008
+ * unsubscribe handle — call it to close the connection.
1009
+ */
1010
+ subscribe(cb: (change: RealtimeChange<T>) => void, options?: SubscribeOptions): Unsubscribe;
1011
+ }
1012
+ /**
1013
+ * A live message change in a conversation. `op` is "INSERT" for a new
1014
+ * message; moderation removals arrive as "DELETE". For a delete (or when a
1015
+ * message was too large to deliver inline) `row` may be partial — re-fetch
1016
+ * with `Amba.messaging.listMessages(conversationId)` when you need the full
1017
+ * body.
1018
+ */
1019
+ type MessageChange<T = unknown> = RealtimeChange<T>;
1020
+ /**
1021
+ * Builder returned by `Amba.messaging.conversation(id)`. Call `.subscribe(cb)`
1022
+ * to receive new messages live instead of polling.
1023
+ *
1024
+ * Delivery is scoped to conversation participants — you receive messages for
1025
+ * a conversation only if your session is a member of it. Reconnects with the
1026
+ * same exponential backoff as collection subscriptions.
1027
+ */
1028
+ declare class ConversationSubscription<T = unknown> {
1029
+ private readonly ctx;
1030
+ private readonly conversationId;
1031
+ constructor(ctx: RealtimeContext, conversationId: string);
1032
+ subscribe(cb: (change: MessageChange<T>) => void, options?: SubscribeOptions): Unsubscribe;
1033
+ }
1034
+ /** Which slice of the signed-in user's gamification state changed. */
1035
+ type GamificationKind = "xp" | "level" | "achievement" | "streak";
1036
+ /**
1037
+ * A live change to the signed-in user's gamification state. `kind` says which
1038
+ * slice moved; `data` carries the new state inline so you can update without a
1039
+ * re-fetch:
1040
+ * - `xp` — `{ total_xp, level, delta }`
1041
+ * - `level` — `{ level, total_xp }`
1042
+ * - `achievement` — `{ achievement_id, unlocked }`
1043
+ * - `streak` — `{ streak_id, count, status, ... }`
1044
+ *
1045
+ * If a payload was too large to deliver inline, `truncated` is `true` and `data`
1046
+ * is empty — re-fetch with `Amba.xp.getBalance()` / `Amba.streaks.getAll()` etc.
1047
+ */
1048
+ interface GamificationChange<T = Record<string, unknown>> {
1049
+ kind: GamificationKind;
1050
+ data: T;
1051
+ truncated?: boolean;
1052
+ }
1053
+ /**
1054
+ * Builder returned by `Amba.gamification`. Call `.subscribe(cb)` to receive the
1055
+ * signed-in user's xp / level / achievement / streak changes live instead of
1056
+ * polling.
1057
+ *
1058
+ * Delivery is scoped to the signed-in user — you only ever receive your own
1059
+ * gamification changes, never another user's. Reconnects with the same
1060
+ * exponential backoff as collection subscriptions.
1061
+ */
1062
+ declare class GamificationSubscription {
1063
+ private readonly ctx;
1064
+ constructor(ctx: RealtimeContext);
1065
+ subscribe(cb: (change: GamificationChange) => void, options?: SubscribeOptions): Unsubscribe;
1066
+ }
707
1067
  //#endregion
708
1068
  //#region src/error.d.ts
709
1069
  /**
@@ -723,16 +1083,63 @@ interface LeagueCohort {
723
1083
  * `new AmbaApiError("MY_CODE", "...")` without coordinating with this
724
1084
  * package's TypeScript types.
725
1085
  */
726
- type AmbaApiErrorCode = "UNAUTHORIZED" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "RATE_LIMITED" | "VALIDATION_ERROR" | "NETWORK_ERROR" | "HTTP_ERROR" | "CIRCUIT_OPEN" | "CONSENT_NOT_GRANTED" | "NOT_INITIALIZED" | "INVALID_CONFIG" | "INVALID_ARGUMENT" | "PUSH_PERMISSION_DENIED" | "PUSH_REGISTRATION_FAILED" | "NOT_SANDBOX_TIER" | "UNKNOWN_ERROR" | (string & {});
1086
+ type AmbaApiErrorCode = "UNAUTHORIZED" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "RATE_LIMITED" | "VALIDATION_ERROR" | "NETWORK_ERROR" | "HTTP_ERROR" | "CIRCUIT_OPEN" | "CONSENT_NOT_GRANTED" | "NOT_INITIALIZED" | "INVALID_CONFIG" | "INVALID_ARGUMENT" | "PUSH_PERMISSION_DENIED" | "PUSH_REGISTRATION_FAILED" | "LOCAL_NOTIFICATIONS_UNAVAILABLE" | "LOCAL_NOTIFICATIONS_PERMISSION_DENIED" | "NOT_SANDBOX_TIER" | "UNKNOWN_ERROR" | (string & {});
727
1087
  declare class AmbaApiError extends Error {
728
1088
  readonly code: AmbaApiErrorCode;
729
1089
  readonly details?: unknown;
730
1090
  constructor(code: AmbaApiErrorCode, message: string, details?: unknown);
731
1091
  }
732
1092
  //#endregion
1093
+ //#region src/local-notifications.d.ts
1094
+ /**
1095
+ * The `notifications` namespace. Shared by `@layers/amba-react-native`
1096
+ * and (via re-export) `@layers/amba-expo`.
1097
+ */
1098
+ declare const notifications: {
1099
+ /**
1100
+ * Schedule a notification the device will fire locally — no server
1101
+ * round-trip. Requests the OS notification permission on first use.
1102
+ *
1103
+ * @returns a handle whose `id` can be passed to `cancelLocal`.
1104
+ * @throws `AmbaApiError`:
1105
+ * - `LOCAL_NOTIFICATIONS_UNAVAILABLE` — `expo-notifications` not installed.
1106
+ * - `LOCAL_NOTIFICATIONS_PERMISSION_DENIED` — user declined the prompt.
1107
+ * - `INVALID_ARGUMENT` — bad title / body / trigger.
1108
+ *
1109
+ * @example
1110
+ * const { id } = await Amba.notifications.scheduleLocal({
1111
+ * title: 'Keep your streak alive',
1112
+ * body: 'You have a lesson waiting.',
1113
+ * trigger: { inSeconds: 60 * 60 * 12 },
1114
+ * });
1115
+ */
1116
+ scheduleLocal(input: ScheduleLocalNotificationInput): Promise<LocalNotificationHandle>;
1117
+ /**
1118
+ * Cancel a previously scheduled local notification by id. No-throw if
1119
+ * the id is unknown (the device framework treats it as already-gone),
1120
+ * but still throws `LOCAL_NOTIFICATIONS_UNAVAILABLE` if the peer dep is
1121
+ * absent so callers learn about the missing integration.
1122
+ */
1123
+ cancelLocal(id: string): Promise<void>;
1124
+ /**
1125
+ * List the notifications Amba has scheduled to fire on this device.
1126
+ * Returns an empty array when none are pending.
1127
+ *
1128
+ * `getAllScheduledNotificationsAsync` returns EVERY pending
1129
+ * `expo-notifications` schedule in the app — including ones the host app
1130
+ * created directly. We filter to only entries carrying the Amba marker
1131
+ * (`data.__ambaLocalId`) so foreign schedules never leak into the Amba
1132
+ * list. (Mirrors the web SDK's marker filter.) These are pending by
1133
+ * definition — `getAllScheduledNotificationsAsync` does not return
1134
+ * already-delivered notifications.
1135
+ */
1136
+ listScheduledLocal(): Promise<ScheduledLocalNotification[]>;
1137
+ };
1138
+ type LocalNotificationsNamespace = typeof notifications;
1139
+ //#endregion
733
1140
  //#region src/index.d.ts
734
1141
  /** SDK semver — burned in at build time. Bump alongside package.json. */
735
- declare const SDK_VERSION = "4.0.3";
1142
+ declare const SDK_VERSION = "4.0.5";
736
1143
  /** Options for `Amba.functions.invoke`. */
737
1144
  interface InvokeOptions {
738
1145
  /** HTTP method. Defaults to `"POST"`. */
@@ -757,6 +1164,37 @@ declare const Amba: {
757
1164
  readonly isAuthenticated: boolean;
758
1165
  readonly projectId: string;
759
1166
  setDebug: (enabled: boolean) => void;
1167
+ /**
1168
+ * Live collection subscriptions. Returns a builder — chain `.where(...)`
1169
+ * to narrow, then `.subscribe(cb)` to start streaming row changes:
1170
+ *
1171
+ * const unsub = Amba.collection("messages")
1172
+ * .where("circle_id", circleId)
1173
+ * .subscribe((change) => {
1174
+ * // change.op: "INSERT" | "UPDATE" | "DELETE"; change.row: the row
1175
+ * });
1176
+ * unsub(); // stop listening
1177
+ *
1178
+ * Delivery mirrors `Amba.collections.find()` — you receive only rows your
1179
+ * session owns (plus shared/public rows), optionally narrowed by
1180
+ * `.where(...)`. Reconnects automatically with backoff if the connection
1181
+ * drops. Requires an authenticated session.
1182
+ */
1183
+ collection: <T = unknown>(name: string) => CollectionSubscription<T>;
1184
+ /**
1185
+ * Live gamification updates for the signed-in user. Call `.subscribe(cb)`
1186
+ * to receive xp / level / achievement / streak changes live:
1187
+ *
1188
+ * const unsub = Amba.gamification.subscribe((change) => {
1189
+ * // change.kind: "xp" | "level" | "achievement" | "streak"
1190
+ * // change.data: the new state
1191
+ * });
1192
+ * unsub(); // stop listening
1193
+ *
1194
+ * You only ever receive your own gamification changes — never another
1195
+ * user's. A getter so `baseUrl` is read at access time. Requires a session.
1196
+ */
1197
+ readonly gamification: GamificationSubscription;
760
1198
  events: {
761
1199
  /**
762
1200
  * Track an event.
@@ -933,8 +1371,8 @@ declare const Amba: {
933
1371
  };
934
1372
  /**
935
1373
  * Offline change replay. NEW in 4.0. Wraps `/v1/client/sync` per
936
- * `apps/api/src/routes/client/sync.ts` and the engine's
937
- * `SyncModule` (`sdks/core/src/sync.rs`).
1374
+ * `apps/api/src/routes/client/sync.ts` and the SDK core's
1375
+ * `SyncModule`.
938
1376
  *
939
1377
  * - `pushChanges(changes)` → `POST /v1/client/sync` with `{ changes }`.
940
1378
  * Server returns `{ applied, conflicts, checkpoint_token }`.
@@ -957,6 +1395,44 @@ declare const Amba: {
957
1395
  checkpoint_token?: string;
958
1396
  }) => Promise<SyncPullResult>;
959
1397
  };
1398
+ /**
1399
+ * Automatic offline mutation queue (opt-in).
1400
+ *
1401
+ * Once enabled, a collection write (`insert` / `update` / `delete`) or a
1402
+ * `track` that fails because the device is offline is buffered to a durable
1403
+ * on-device outbox (AsyncStorage) instead of throwing — then replayed in
1404
+ * order on the next {@link flush} (e.g. when your NetInfo listener detects
1405
+ * reconnect). Replays reuse a per-op idempotency key so a write that reached
1406
+ * the server before the connection dropped is never applied twice.
1407
+ *
1408
+ * This is distinct from `Amba.sync` (manual change replay): `offline` is the
1409
+ * automatic, fire-and-forget safety net for ordinary writes.
1410
+ *
1411
+ * @example
1412
+ * import NetInfo from "@react-native-community/netinfo";
1413
+ * Amba.offline.enable();
1414
+ * NetInfo.addEventListener((s) => { if (s.isConnected) Amba.offline.flush(); });
1415
+ * await Amba.collections.insert("todos", { title: "Buy milk" }); // queues if offline
1416
+ */
1417
+ offline: {
1418
+ /**
1419
+ * Turn the outbox on. Idempotent. Returns a disable function (queued ops
1420
+ * are NOT dropped — call `clear()` for that). Drive `flush()` from your own
1421
+ * connectivity listener (e.g. NetInfo) since React Native has no global
1422
+ * `online` event.
1423
+ */
1424
+ enable: () => (() => void);
1425
+ /** Whether the outbox is currently enabled. */
1426
+ isEnabled: () => boolean;
1427
+ /** Count of writes awaiting replay. */
1428
+ pendingCount: () => Promise<number>;
1429
+ /** Snapshot the pending ops (a copy — safe to inspect). */
1430
+ pending: () => Promise<OutboxOp[]>;
1431
+ /** Force a replay attempt now. Resolves with `{ flushed, dropped, remaining }` (dropped = poisoned ops the server rejects on replay, removed so they cannot wedge the queue). */
1432
+ flush: () => Promise<FlushResult>;
1433
+ /** Drop every queued write without replaying. */
1434
+ clear: () => Promise<void>;
1435
+ };
960
1436
  collections: {
961
1437
  find: <T = unknown>(name: string, options?: FindOptions) => Promise<FindResponse<T>>;
962
1438
  findOne: <T = unknown>(name: string, id: string) => Promise<T>;
@@ -982,8 +1458,7 @@ declare const Amba: {
982
1458
  *
983
1459
  * The server's `/count` route only honors `where` + `includeDeleted`
984
1460
  * — passing other knobs (`limit`, `cursor`, etc.) returns
985
- * `INVALID_QUERY_PARAM`. Mirrors the engine's `CollectionsModule::count`
986
- * (`sdks/core/src/collections.rs`).
1461
+ * `INVALID_QUERY_PARAM`. Mirrors the SDK core's `CollectionsModule::count`.
987
1462
  */
988
1463
  count: (name: string, where?: Filter) => Promise<number>;
989
1464
  insert: <T = unknown>(name: string, row: Record<string, unknown>) => Promise<T>;
@@ -993,6 +1468,36 @@ declare const Amba: {
993
1468
  deleted: boolean;
994
1469
  };
995
1470
  }>;
1471
+ /**
1472
+ * Optimistic insert — update a local view immediately, fire the real
1473
+ * insert, and roll the view back if it fails. Thin convenience over the
1474
+ * exported {@link withOptimistic}; for multi-step flows use that directly.
1475
+ *
1476
+ * Optimistic writes always hit the network directly — they are NOT diverted
1477
+ * to the offline outbox even when `Amba.offline` is enabled. Optimistic UI
1478
+ * needs an unambiguous outcome: this resolves only on a confirmed write and
1479
+ * rejects (running your `rollback`) on any failure including being offline.
1480
+ * To buffer-and-replay instead, use the plain `insert`/`update`/`delete`
1481
+ * with the outbox on.
1482
+ */
1483
+ optimisticInsert: <T = unknown, TApply = unknown>(name: string, row: Record<string, unknown>, view: {
1484
+ apply: () => TApply;
1485
+ rollback: (applied: TApply) => void;
1486
+ }) => Promise<T>;
1487
+ /** Optimistic update — see {@link optimisticInsert}. */
1488
+ optimisticUpdate: <T = unknown, TApply = unknown>(name: string, id: string, set: Record<string, unknown>, view: {
1489
+ apply: () => TApply;
1490
+ rollback: (applied: TApply) => void;
1491
+ }) => Promise<T>;
1492
+ /** Optimistic delete — see {@link optimisticInsert}. */
1493
+ optimisticDelete: <TApply = unknown>(name: string, id: string, view: {
1494
+ apply: () => TApply;
1495
+ rollback: (applied: TApply) => void;
1496
+ }) => Promise<{
1497
+ data: {
1498
+ deleted: boolean;
1499
+ };
1500
+ }>;
996
1501
  where: {
997
1502
  eq: (column: string, value: FilterValue) => Filter;
998
1503
  ne: (column: string, value: FilterValue) => Filter;
@@ -1053,9 +1558,8 @@ declare const Amba: {
1053
1558
  * Returns a `Blob` — RN's fetch surfaces blobs natively
1054
1559
  * (`response.blob()`). NEW in 4.0.
1055
1560
  *
1056
- * Mirrors the engine's `StorageModule::download` in
1057
- * `sdks/core/src/storage.rs:247` — there is no
1058
- * `/v1/client/media/download` route on the server; the CDN URL
1561
+ * Mirrors the SDK core's `StorageModule::download` — there is no
1562
+ * `/v1/client/media/download` route on the server; the asset URL
1059
1563
  * on the asset row is the canonical fetch target.
1060
1564
  */
1061
1565
  download: (assetId: string) => Promise<Blob>;
@@ -1066,11 +1570,63 @@ declare const Amba: {
1066
1570
  getTokens: () => Promise<PushToken[]>;
1067
1571
  subscribe: (topic: string) => Promise<void>;
1068
1572
  unsubscribe: (topic: string) => Promise<void>;
1573
+ /**
1574
+ * Auto re-register the device push token when the OS rotates it.
1575
+ *
1576
+ * The OS can roll a device's push token (reinstall, restore, key roll);
1577
+ * the new token must be re-registered or notifications stop arriving. Pass
1578
+ * your notification library's token-refresh subscription primitive — e.g.
1579
+ * `(h) => Notifications.addPushTokenListener((t) => h(t.data)).remove` on
1580
+ * Expo, or the bare-FCM `onTokenRefresh` callback — and the SDK forwards
1581
+ * each rotated token through the idempotent {@link register} path.
1582
+ *
1583
+ * Pass the token `platform` for your build — `"apns"` on iOS, `"fcm"` on
1584
+ * Android (defaults to `"fcm"` when omitted). The bare RN SDK never reads
1585
+ * `Platform.OS` itself (it's a pure-JS client that also loads under Node),
1586
+ * so the caller supplies it; the Expo wrapper's
1587
+ * `Amba.enablePushAutoRotation()` resolves it for you. Returns an
1588
+ * unsubscribe function.
1589
+ *
1590
+ * @example
1591
+ * import { Platform } from "react-native";
1592
+ * import * as Notifications from "expo-notifications";
1593
+ * const detach = Amba.push.enableAutoRotation(
1594
+ * (h) => Notifications.addPushTokenListener((t) => h(t.data)).remove,
1595
+ * Platform.OS === "ios" ? "apns" : "fcm",
1596
+ * );
1597
+ */
1598
+ enableAutoRotation: (subscribe: TokenRefreshSubscribe, platform?: "apns" | "fcm") => (() => void);
1599
+ };
1600
+ /**
1601
+ * On-device local notifications — `scheduleLocal` / `cancelLocal` /
1602
+ * `listScheduledLocal`. These schedule notifications the device fires
1603
+ * itself (reminders, streak nudges) with no server round-trip, distinct
1604
+ * from remote push (`Amba.push.*`). Backed by `expo-notifications`
1605
+ * (an optional peer dep that works in both Expo and bare RN apps),
1606
+ * loaded lazily; methods throw a clear `LOCAL_NOTIFICATIONS_UNAVAILABLE`
1607
+ * error if it isn't installed. See `./local-notifications.ts`.
1608
+ */
1609
+ notifications: {
1610
+ scheduleLocal(input: ScheduleLocalNotificationInput): Promise<LocalNotificationHandle>;
1611
+ cancelLocal(id: string): Promise<void>;
1612
+ listScheduledLocal(): Promise<ScheduledLocalNotification[]>;
1069
1613
  };
1070
1614
  entitlements: {
1071
1615
  list: () => Promise<UserEntitlement[]>;
1072
- has: (name: string) => Promise<boolean>;
1616
+ has: (entitlementId: string) => Promise<boolean>;
1617
+ /**
1618
+ * Restore purchases — re-sync the user's owned entitlements from the
1619
+ * server and return the active set. Required for App Store review (3.1.1);
1620
+ * wire it to a "Restore Purchases" button. Throws (access unchanged) if the
1621
+ * server can't reach the validation engine — show a retry message.
1622
+ */
1623
+ restore: () => Promise<RestoreResult>;
1073
1624
  };
1625
+ /**
1626
+ * Subscription offerings — the packages your paywall renders, provider-
1627
+ * neutral. Pass an `offeringId` for one offering; omit it for all.
1628
+ */
1629
+ offerings: (offeringId?: string) => Promise<OfferingsResult>;
1074
1630
  ai: {
1075
1631
  anthropic: {
1076
1632
  messages: {
@@ -1228,6 +1784,22 @@ declare const Amba: {
1228
1784
  * The real route is `/v1/client/messaging/conversations/:id/messages`.
1229
1785
  */
1230
1786
  messaging: {
1787
+ /**
1788
+ * Live conversation subscription. Returns a builder — call
1789
+ * `.subscribe(cb)` to receive new messages live instead of polling:
1790
+ *
1791
+ * const unsub = Amba.messaging
1792
+ * .conversation(conversationId)
1793
+ * .subscribe((change) => {
1794
+ * // change.op === "INSERT"; change.row is the new message
1795
+ * });
1796
+ * unsub(); // stop listening
1797
+ *
1798
+ * Delivery is scoped to conversation participants — you receive messages
1799
+ * only if your session is a member of the conversation. Reconnects
1800
+ * automatically with backoff. Requires an authenticated session.
1801
+ */
1802
+ conversation: <T = Message>(conversationId: string) => ConversationSubscription<T>;
1231
1803
  /**
1232
1804
  * `POST /v1/client/messaging/conversations` — create (or fetch
1233
1805
  * the existing direct) conversation. Idempotent for direct
@@ -1251,8 +1823,7 @@ declare const Amba: {
1251
1823
  * query filter (see `apps/api/src/routes/client/messaging.ts:358`,
1252
1824
  * which returns the full paginated page). We paginate forward
1253
1825
  * (newest-first, server page size 100) and find the matching id
1254
- * client-side, mirroring the engine's strategy in
1255
- * `sdks/core/src/messaging.rs:223`. Walks up to `MAX_PAGES`
1826
+ * client-side, mirroring the SDK core's strategy. Walks up to `MAX_PAGES`
1256
1827
  * (5,000 messages total) before giving up to avoid an unbounded
1257
1828
  * loop against a giant conversation; callers with longer histories
1258
1829
  * should keep a local index instead of relying on this helper as a
@@ -1337,5 +1908,5 @@ declare const Amba: {
1337
1908
  };
1338
1909
  };
1339
1910
  //#endregion
1340
- export { Achievement, AchievementProgress, AiMessage, AiMessageRequest, AiMessageResponse, AiUsage, Amba, AmbaApiError, type AmbaApiErrorCode, AmbaConfig, AndFilter, AuthResult, CatalogItem, Challenge, ChallengeProgress, ConditionFilter, ConfigBundle, ConsumeRequest, ContentItem, Conversation, ConversationType, CreateConversationRequest, CurrencyBalance, CurrencyTransaction, DeepLink, DeepLinkCreate, DiagnosticsEnvironment, EntitlementSource, FeedItem, FeedResponse, Filter, FilterValue, FindOptions, FindResponse, FlagAssignment, Friendship, FriendshipState, Group, GroupCreate, GroupMember, GroupUpdate, InventoryItem, InvokeOptions, Leaderboard, LeaderboardEntry, LeagueCohort, LeagueCohortRef, LeagueMembership, LeagueTier, LinkedIdentifier, ListMessagesOptions, MarkReadResult, MediaAsset, Message, MessageType, NotFilter, OnboardingStatus, OrFilter, OrderBy, PingResult, PresignData, PurchaseOption, PurchaseRequest, PurchaseResult, PushPlatform, PushToken, ReferralClaim, ReferralCode, Report, ReportRequest, Review, ReviewCreate, ReviewUpdate, Role, SDK_VERSION, SendMessageRequest, Session, SessionRecord, SocialProvider, Store, Streak, SyncChange, SyncConflict, SyncPullResult, SyncPullSince, SyncPushResult, User, UserEntitlement, UserPatch, XpBalance, XpTransaction };
1911
+ export { Achievement, AchievementProgress, AiMessage, AiMessageRequest, AiMessageResponse, AiUsage, Amba, AmbaApiError, type AmbaApiErrorCode, AmbaConfig, AndFilter, AuthResult, CatalogItem, Challenge, ChallengeProgress, CollectionSubscription, ConditionFilter, ConfigBundle, ConsumeRequest, ContentItem, Conversation, ConversationSubscription, ConversationType, CreateConversationRequest, CurrencyBalance, CurrencyTransaction, DeepLink, DeepLinkCreate, DiagnosticsEnvironment, EntitlementPeriodType, EntitlementStore, FeedItem, FeedResponse, Filter, FilterValue, FindOptions, FindResponse, FlagAssignment, type FlushResult, Friendship, FriendshipState, type GamificationChange, type GamificationKind, GamificationSubscription, Group, GroupCreate, GroupMember, GroupUpdate, InventoryItem, InvokeOptions, type KvStore, Leaderboard, LeaderboardEntry, LeagueCohort, LeagueCohortRef, LeagueMembership, LeagueTier, LinkedIdentifier, ListMessagesOptions, LocalNotificationHandle, LocalNotificationTrigger, type LocalNotificationsNamespace, MarkReadResult, MediaAsset, Message, type MessageChange, MessageType, NotFilter, Offering, OfferingPackage, OfferingProduct, OfferingsResult, OnboardingStatus, OrFilter, OrderBy, type OutboxOp, type OutboxOpKind, PingResult, PresignData, PurchaseOption, PurchaseRequest, PurchaseResult, PushPlatform, PushToken, type RealtimeChange, ReferralClaim, ReferralCode, Report, ReportRequest, RestoreResult, Review, ReviewCreate, ReviewUpdate, Role, type RowChangeOp, SDK_VERSION, ScheduleLocalNotificationInput, ScheduledLocalNotification, SendMessageRequest, Session, SessionRecord, SocialProvider, Store, Streak, type SubscribeOptions, SyncChange, SyncConflict, SyncPullResult, SyncPullSince, SyncPushResult, type TokenRefreshSubscribe, type Unsubscribe, User, UserEntitlement, UserPatch, XpBalance, XpTransaction, withOptimistic };
1341
1912
  //# sourceMappingURL=index.d.ts.map