@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.cjs +1050 -22
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +593 -22
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.ts +593 -22
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1047 -23
- package/dist/index.js.map +1 -1
- package/package.json +6 -2
package/dist/index.js
CHANGED
|
@@ -350,10 +350,806 @@ function freshSeed() {
|
|
|
350
350
|
};
|
|
351
351
|
}
|
|
352
352
|
|
|
353
|
+
//#endregion
|
|
354
|
+
//#region src/resilience.ts
|
|
355
|
+
/**
|
|
356
|
+
* Best-effort online probe. In a browser/RN runtime `navigator.onLine`
|
|
357
|
+
* exists; under Node / SSR it doesn't, so we treat "unknown" as online
|
|
358
|
+
* (the executor's own error handling then decides).
|
|
359
|
+
*/
|
|
360
|
+
function isOnline() {
|
|
361
|
+
const nav = typeof navigator !== "undefined" ? navigator : void 0;
|
|
362
|
+
if (nav && typeof nav.onLine === "boolean") return nav.onLine;
|
|
363
|
+
return true;
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Error codes the server raised deterministically — replaying them would fail
|
|
367
|
+
* identically, so they're NEVER queued even when the device reports offline.
|
|
368
|
+
* (A request can fail validation/auth/etc. while `navigator.onLine` is briefly
|
|
369
|
+
* false; we must not buffer-and-retry those forever.)
|
|
370
|
+
*/
|
|
371
|
+
const DETERMINISTIC_ERROR_CODES = new Set([
|
|
372
|
+
"VALIDATION_ERROR",
|
|
373
|
+
"INVALID_ARGUMENT",
|
|
374
|
+
"INVALID_INPUT",
|
|
375
|
+
"UNAUTHORIZED",
|
|
376
|
+
"FORBIDDEN",
|
|
377
|
+
"NOT_FOUND",
|
|
378
|
+
"CONFLICT",
|
|
379
|
+
"CONSENT_NOT_GRANTED",
|
|
380
|
+
"NOT_INITIALIZED"
|
|
381
|
+
]);
|
|
382
|
+
/**
|
|
383
|
+
* Is this a deterministic server rejection — a coded error the server would
|
|
384
|
+
* raise identically on every replay (bad input, auth, not-found, conflict)? A
|
|
385
|
+
* queued op that fails this way is poison: retrying it forever would wedge the
|
|
386
|
+
* queue, so the flush DROPS it. Everything else (transport failures, 5xx
|
|
387
|
+
* `HTTP_ERROR`, `RATE_LIMITED`, `CIRCUIT_OPEN`, anything uncoded) is treated as
|
|
388
|
+
* transient and RETAINED for a later attempt — favoring retain over data loss.
|
|
389
|
+
*/
|
|
390
|
+
function isDeterministicError(err) {
|
|
391
|
+
const code = err?.code;
|
|
392
|
+
return typeof code === "string" && DETERMINISTIC_ERROR_CODES.has(code);
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Heuristic: does a thrown value look like a transient offline / transport
|
|
396
|
+
* failure (vs a deterministic 4xx the server would reject again)? Used at
|
|
397
|
+
* ENQUEUE time to decide whether a failed write is worth buffering — a
|
|
398
|
+
* `VALIDATION_ERROR` will fail identically on replay, so it throws instead.
|
|
399
|
+
*
|
|
400
|
+
* A deterministic server error is excluded even when the device reports
|
|
401
|
+
* offline: the request clearly reached the server (it got a coded response),
|
|
402
|
+
* so retrying it on reconnect is pointless and would wedge the queue.
|
|
403
|
+
*
|
|
404
|
+
* NOTE: this is intentionally stricter than {@link isDeterministicError}'s
|
|
405
|
+
* inverse — at enqueue time we only buffer GENUINE connectivity failures (a
|
|
406
|
+
* non-offline 5xx/429 surfaces to the caller immediately rather than silently
|
|
407
|
+
* queueing). The flush drop-decision uses {@link isDeterministicError} so a
|
|
408
|
+
* transient 5xx/429 encountered DURING replay is retained, not dropped.
|
|
409
|
+
*/
|
|
410
|
+
function isOfflineError(err) {
|
|
411
|
+
const code = err?.code;
|
|
412
|
+
if (typeof code === "string" && DETERMINISTIC_ERROR_CODES.has(code)) return false;
|
|
413
|
+
if (code === "NETWORK_ERROR") return true;
|
|
414
|
+
const msg = err?.message;
|
|
415
|
+
if (typeof msg === "string" && /network (error|request failed)|failed to fetch|fetch failed|load failed/i.test(msg)) return true;
|
|
416
|
+
return !isOnline();
|
|
417
|
+
}
|
|
418
|
+
/** Generate a stable idempotency key for a queued op. */
|
|
419
|
+
function newIdempotencyKey() {
|
|
420
|
+
const c = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
|
|
421
|
+
if (c && typeof c.randomUUID === "function") return `amba_obx_${c.randomUUID()}`;
|
|
422
|
+
return `amba_obx_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Durable, ordered, idempotent offline outbox. Opt-in via `Amba.offline`.
|
|
426
|
+
* Single in-flight flush is enforced so concurrent reconnect signals don't
|
|
427
|
+
* double-replay.
|
|
428
|
+
*/
|
|
429
|
+
var OfflineQueue = class {
|
|
430
|
+
store;
|
|
431
|
+
executor;
|
|
432
|
+
storageKey;
|
|
433
|
+
/**
|
|
434
|
+
* Notified when a queued op is dropped because its replay failed
|
|
435
|
+
* deterministically (a poisoned op the server will always reject). Lets the
|
|
436
|
+
* SDK surface the loss (debug log) instead of silently discarding.
|
|
437
|
+
*/
|
|
438
|
+
onDropped;
|
|
439
|
+
flushing = null;
|
|
440
|
+
/**
|
|
441
|
+
* Serializes every read-modify-write of the persisted outbox. Each mutation
|
|
442
|
+
* chains onto the previous one's promise, so concurrent `enqueue`s — and an
|
|
443
|
+
* `enqueue` racing the per-op removal inside `flush` — can never read a stale
|
|
444
|
+
* snapshot and clobber each other's writes (the lost-update bug). All
|
|
445
|
+
* storage mutations funnel through `mutate()`; only `pendingCount`/`pending`
|
|
446
|
+
* read without taking the lock (a stale-by-one read is harmless).
|
|
447
|
+
*/
|
|
448
|
+
tail = Promise.resolve();
|
|
449
|
+
/** Detach function for the auto-flush `online` listener, if installed. */
|
|
450
|
+
detachOnline = null;
|
|
451
|
+
/**
|
|
452
|
+
* Set once `dispose()` is called (on teardown / reconfigure). A disposed
|
|
453
|
+
* queue refuses to mutate the persisted outbox, so an orphaned in-flight
|
|
454
|
+
* flush — or any late call against the old instance — can never race the new
|
|
455
|
+
* queue by reading/writing the same storage after it's been replaced.
|
|
456
|
+
*/
|
|
457
|
+
disposed = false;
|
|
458
|
+
constructor(opts) {
|
|
459
|
+
this.store = opts.store;
|
|
460
|
+
this.executor = opts.executor;
|
|
461
|
+
this.storageKey = opts.storageKey ?? "offline_outbox";
|
|
462
|
+
this.onDropped = opts.onDropped;
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* Run `fn` exclusively against the persisted outbox: it chains after every
|
|
466
|
+
* prior mutation and the next one waits for it. `fn` receives the current
|
|
467
|
+
* ops and returns the next ops to persist plus its own result.
|
|
468
|
+
*/
|
|
469
|
+
mutate(fn, opts) {
|
|
470
|
+
const run = this.tail.then(async () => {
|
|
471
|
+
if (this.disposed && opts?.rejectIfDisposed) throw new Error("amba offline queue was disposed (SDK reconfigured)");
|
|
472
|
+
const { next, result } = await fn(await this.load());
|
|
473
|
+
await this.save(next);
|
|
474
|
+
return result;
|
|
475
|
+
});
|
|
476
|
+
this.tail = run.catch(() => void 0);
|
|
477
|
+
return run;
|
|
478
|
+
}
|
|
479
|
+
async load() {
|
|
480
|
+
const raw = await this.store.get(this.storageKey);
|
|
481
|
+
if (!raw) return [];
|
|
482
|
+
try {
|
|
483
|
+
const parsed = JSON.parse(raw);
|
|
484
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
485
|
+
} catch {
|
|
486
|
+
return [];
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
async save(ops) {
|
|
490
|
+
if (this.disposed) return;
|
|
491
|
+
if (ops.length === 0) {
|
|
492
|
+
await this.store.delete(this.storageKey);
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
await this.store.set(this.storageKey, JSON.stringify(ops));
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* Permanently retire this queue. Detaches the auto-flush listener and marks
|
|
499
|
+
* it disposed so it can no longer mutate the persisted outbox. Returns once
|
|
500
|
+
* any in-flight flush + pending mutation chain has settled, so a caller (e.g.
|
|
501
|
+
* `configure()` teardown) can safely create a replacement queue knowing the
|
|
502
|
+
* old one will never touch storage again. Idempotent.
|
|
503
|
+
*/
|
|
504
|
+
async dispose() {
|
|
505
|
+
this.disposed = true;
|
|
506
|
+
if (this.detachOnline) {
|
|
507
|
+
this.detachOnline();
|
|
508
|
+
this.detachOnline = null;
|
|
509
|
+
}
|
|
510
|
+
try {
|
|
511
|
+
await this.flushing;
|
|
512
|
+
} catch {}
|
|
513
|
+
await this.tail.catch(() => void 0);
|
|
514
|
+
}
|
|
515
|
+
/** Whether this queue has been disposed. */
|
|
516
|
+
get isDisposed() {
|
|
517
|
+
return this.disposed;
|
|
518
|
+
}
|
|
519
|
+
/** Append an op to the durable outbox. Returns the persisted op. */
|
|
520
|
+
async enqueue(op) {
|
|
521
|
+
if (this.disposed) throw new Error("amba offline queue was disposed (SDK reconfigured)");
|
|
522
|
+
const full = {
|
|
523
|
+
...op,
|
|
524
|
+
idempotencyKey: op.idempotencyKey ?? newIdempotencyKey(),
|
|
525
|
+
enqueuedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
526
|
+
};
|
|
527
|
+
return this.mutate((ops) => ({
|
|
528
|
+
next: [...ops, full],
|
|
529
|
+
result: full
|
|
530
|
+
}), { rejectIfDisposed: true });
|
|
531
|
+
}
|
|
532
|
+
/** Number of ops awaiting replay. */
|
|
533
|
+
async pendingCount() {
|
|
534
|
+
return (await this.load()).length;
|
|
535
|
+
}
|
|
536
|
+
/** Snapshot the pending ops (a copy — mutating it does not affect the queue). */
|
|
537
|
+
async pending() {
|
|
538
|
+
return [...await this.load()];
|
|
539
|
+
}
|
|
540
|
+
/** Drop every queued op without replaying. */
|
|
541
|
+
async clear() {
|
|
542
|
+
await this.mutate(() => ({
|
|
543
|
+
next: [],
|
|
544
|
+
result: void 0
|
|
545
|
+
}));
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* Replay the outbox in FIFO order. Each op is removed only after it
|
|
549
|
+
* succeeds; the first failure stops the flush and retains the remainder
|
|
550
|
+
* (so order is preserved and nothing is dropped mid-batch). Concurrent
|
|
551
|
+
* calls share one in-flight flush.
|
|
552
|
+
*/
|
|
553
|
+
async flush() {
|
|
554
|
+
if (this.disposed) return {
|
|
555
|
+
flushed: 0,
|
|
556
|
+
dropped: 0,
|
|
557
|
+
remaining: 0
|
|
558
|
+
};
|
|
559
|
+
if (this.flushing) return this.flushing;
|
|
560
|
+
this.flushing = this.runFlush().finally(() => {
|
|
561
|
+
this.flushing = null;
|
|
562
|
+
});
|
|
563
|
+
return this.flushing;
|
|
564
|
+
}
|
|
565
|
+
async runFlush() {
|
|
566
|
+
let flushed = 0;
|
|
567
|
+
let dropped = 0;
|
|
568
|
+
for (;;) {
|
|
569
|
+
if (this.disposed) break;
|
|
570
|
+
const head = (await this.load())[0];
|
|
571
|
+
if (!head) break;
|
|
572
|
+
let replayError = void 0;
|
|
573
|
+
let ok = false;
|
|
574
|
+
try {
|
|
575
|
+
await this.executor(head);
|
|
576
|
+
ok = true;
|
|
577
|
+
} catch (err) {
|
|
578
|
+
replayError = err;
|
|
579
|
+
}
|
|
580
|
+
if (!ok && !isDeterministicError(replayError)) {
|
|
581
|
+
await this.mutate((ops) => {
|
|
582
|
+
return {
|
|
583
|
+
next: ops.some((o) => o.idempotencyKey === head.idempotencyKey) ? ops : [head, ...ops],
|
|
584
|
+
result: void 0
|
|
585
|
+
};
|
|
586
|
+
});
|
|
587
|
+
break;
|
|
588
|
+
}
|
|
589
|
+
if (!await this.mutate((ops) => {
|
|
590
|
+
const idx = ops.findIndex((o) => o.idempotencyKey === head.idempotencyKey);
|
|
591
|
+
if (idx === -1) return {
|
|
592
|
+
next: ops,
|
|
593
|
+
result: false
|
|
594
|
+
};
|
|
595
|
+
return {
|
|
596
|
+
next: ops.slice(0, idx).concat(ops.slice(idx + 1)),
|
|
597
|
+
result: true
|
|
598
|
+
};
|
|
599
|
+
})) break;
|
|
600
|
+
if (ok) flushed += 1;
|
|
601
|
+
else {
|
|
602
|
+
dropped += 1;
|
|
603
|
+
try {
|
|
604
|
+
this.onDropped?.(head, replayError);
|
|
605
|
+
} catch {}
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
const remaining = (await this.load()).length;
|
|
609
|
+
return {
|
|
610
|
+
flushed,
|
|
611
|
+
dropped,
|
|
612
|
+
remaining
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Install an auto-flush listener on the runtime's `online` event so the
|
|
617
|
+
* queue drains the moment connectivity returns. Idempotent — a second
|
|
618
|
+
* call is a no-op. Returns a detach function.
|
|
619
|
+
*/
|
|
620
|
+
startAutoFlush() {
|
|
621
|
+
if (this.detachOnline) return this.detachOnline;
|
|
622
|
+
const target = typeof globalThis !== "undefined" && typeof globalThis.addEventListener === "function" ? globalThis : null;
|
|
623
|
+
if (!target) {
|
|
624
|
+
this.detachOnline = () => {};
|
|
625
|
+
return this.detachOnline;
|
|
626
|
+
}
|
|
627
|
+
const handler = () => {
|
|
628
|
+
this.flush();
|
|
629
|
+
};
|
|
630
|
+
target.addEventListener("online", handler);
|
|
631
|
+
this.detachOnline = () => {
|
|
632
|
+
target.removeEventListener("online", handler);
|
|
633
|
+
this.detachOnline = null;
|
|
634
|
+
};
|
|
635
|
+
return this.detachOnline;
|
|
636
|
+
}
|
|
637
|
+
};
|
|
638
|
+
/**
|
|
639
|
+
* Apply a local change immediately, fire the real mutation, and roll the
|
|
640
|
+
* local change back if the mutation fails. Framework-agnostic: `apply` and
|
|
641
|
+
* `rollback` operate on whatever local view you hand them (a React state
|
|
642
|
+
* setter, a store, an in-memory cache).
|
|
643
|
+
*
|
|
644
|
+
* Resolves with the mutation's result on success. On failure it invokes
|
|
645
|
+
* `rollback` (with the value `apply` returned, so you can restore a captured
|
|
646
|
+
* snapshot) and rethrows the original error.
|
|
647
|
+
*
|
|
648
|
+
* @example
|
|
649
|
+
* await withOptimistic({
|
|
650
|
+
* apply: () => { const prev = todos; setTodos([...todos, draft]); return prev; },
|
|
651
|
+
* mutate: () => Amba.collections.insert("todos", draft),
|
|
652
|
+
* rollback: (prev) => setTodos(prev),
|
|
653
|
+
* });
|
|
654
|
+
*/
|
|
655
|
+
async function withOptimistic(spec) {
|
|
656
|
+
const applied = spec.apply();
|
|
657
|
+
try {
|
|
658
|
+
return await spec.mutate();
|
|
659
|
+
} catch (err) {
|
|
660
|
+
try {
|
|
661
|
+
spec.rollback(applied);
|
|
662
|
+
} catch {}
|
|
663
|
+
throw err;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
//#endregion
|
|
668
|
+
//#region src/push-rotation.ts
|
|
669
|
+
/**
|
|
670
|
+
* Wire a platform token-refresh subscription to the SDK's idempotent
|
|
671
|
+
* re-register path. On every rotation the fresh token is forwarded to
|
|
672
|
+
* `reRegister(token, platform)` — the same upsert the first `push.register`
|
|
673
|
+
* call used, so re-registering the same device is a no-op server-side.
|
|
674
|
+
*
|
|
675
|
+
* `platform` defaults to the conventional pick (`"apns"` on iOS, `"fcm"`
|
|
676
|
+
* elsewhere) supplied by the caller. Returns an unsubscribe function.
|
|
677
|
+
*
|
|
678
|
+
* @example
|
|
679
|
+
* // Expo:
|
|
680
|
+
* import * as Notifications from "expo-notifications";
|
|
681
|
+
* const detach = enableNativePushAutoRotation(
|
|
682
|
+
* (h) => Notifications.addPushTokenListener((t) => h(t.data)).remove,
|
|
683
|
+
* reRegister,
|
|
684
|
+
* "apns",
|
|
685
|
+
* );
|
|
686
|
+
*/
|
|
687
|
+
function enableNativePushAutoRotation(subscribe, reRegister, platform) {
|
|
688
|
+
const unsubscribe = subscribe((token) => {
|
|
689
|
+
if (!token) return;
|
|
690
|
+
(async () => {
|
|
691
|
+
try {
|
|
692
|
+
await reRegister(token, platform);
|
|
693
|
+
} catch (err) {
|
|
694
|
+
if (typeof console !== "undefined") console.error("[amba] push auto-rotation re-register failed", err);
|
|
695
|
+
}
|
|
696
|
+
})();
|
|
697
|
+
});
|
|
698
|
+
return typeof unsubscribe === "function" ? unsubscribe : () => {};
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
//#endregion
|
|
702
|
+
//#region src/local-notifications.ts
|
|
703
|
+
/**
|
|
704
|
+
* Marker key stamped into every Amba-scheduled notification's `data`. Lets
|
|
705
|
+
* `listScheduledLocal` distinguish OUR notifications from any other
|
|
706
|
+
* `expo-notifications` schedules the host app created — so foreign
|
|
707
|
+
* schedules never leak into the Amba list. Mirrors the web SDK's
|
|
708
|
+
* `__ambaLocalId` marker.
|
|
709
|
+
*/
|
|
710
|
+
const AMBA_LOCAL_ID_KEY = "__ambaLocalId";
|
|
711
|
+
/**
|
|
712
|
+
* Generate a stable local-notification id when the caller omits one.
|
|
713
|
+
*/
|
|
714
|
+
function genLocalId() {
|
|
715
|
+
const c = globalThis.crypto;
|
|
716
|
+
if (c?.randomUUID) return c.randomUUID();
|
|
717
|
+
return `amba_local_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
718
|
+
}
|
|
719
|
+
/**
|
|
720
|
+
* Resolve the id a schedule will be filed under. A caller may omit `id`
|
|
721
|
+
* (we mint one) but must not pass a BLANK/whitespace id: `cancelLocal`
|
|
722
|
+
* rejects blank ids, so returning one in the handle would make the
|
|
723
|
+
* notification uncancellable. Reject blank at schedule time so every
|
|
724
|
+
* returned handle id round-trips through `cancelLocal`. Mirrors the web SDK.
|
|
725
|
+
*/
|
|
726
|
+
function normalizeScheduleId(rawId) {
|
|
727
|
+
if (rawId === void 0) return genLocalId();
|
|
728
|
+
if (typeof rawId !== "string" || rawId.trim() === "") throw new AmbaApiError("INVALID_ARGUMENT", "Amba.notifications.scheduleLocal: id, when provided, must be a non-empty string");
|
|
729
|
+
return rawId;
|
|
730
|
+
}
|
|
731
|
+
async function loadExpoNotifications() {
|
|
732
|
+
try {
|
|
733
|
+
const mod = await import("expo-notifications");
|
|
734
|
+
return mod.default ?? mod;
|
|
735
|
+
} catch (err) {
|
|
736
|
+
throw new AmbaApiError("LOCAL_NOTIFICATIONS_UNAVAILABLE", "Amba.notifications requires the `expo-notifications` peer dependency. Install it with `npx expo install expo-notifications` (works in both Expo and bare React Native apps).", err);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
/**
|
|
740
|
+
* Translate Amba's platform-neutral trigger into the shape
|
|
741
|
+
* `expo-notifications` expects. We build object triggers keyed by the
|
|
742
|
+
* library's `SchedulableTriggerInputTypes` when present (SDK 0.27+),
|
|
743
|
+
* falling back to the legacy `{ date }` / `{ seconds }` shorthand the
|
|
744
|
+
* older API accepts — both forms remain supported by current releases.
|
|
745
|
+
*/
|
|
746
|
+
function buildExpoTrigger(input, Notifications) {
|
|
747
|
+
const types = Notifications.SchedulableTriggerInputTypes;
|
|
748
|
+
const trigger = input.trigger;
|
|
749
|
+
if (!trigger || typeof trigger !== "object") throw new AmbaApiError("INVALID_ARGUMENT", "Amba.notifications.scheduleLocal: trigger must be { at: Date } or { inSeconds: number, repeats?: boolean }");
|
|
750
|
+
if ("at" in trigger) {
|
|
751
|
+
const at = trigger.at instanceof Date ? trigger.at : new Date(trigger.at);
|
|
752
|
+
if (Number.isNaN(at.getTime())) throw new AmbaApiError("INVALID_ARGUMENT", "Amba.notifications.scheduleLocal: trigger.at must be a valid Date");
|
|
753
|
+
return types ? {
|
|
754
|
+
type: types.DATE,
|
|
755
|
+
date: at
|
|
756
|
+
} : { date: at };
|
|
757
|
+
}
|
|
758
|
+
if ("inSeconds" in trigger) {
|
|
759
|
+
const seconds = trigger.inSeconds;
|
|
760
|
+
if (!Number.isFinite(seconds) || seconds < 0) throw new AmbaApiError("INVALID_ARGUMENT", "Amba.notifications.scheduleLocal: trigger.inSeconds must be a non-negative number");
|
|
761
|
+
const repeats = "repeats" in trigger ? Boolean(trigger.repeats) : false;
|
|
762
|
+
return types ? {
|
|
763
|
+
type: types.TIME_INTERVAL,
|
|
764
|
+
seconds,
|
|
765
|
+
repeats
|
|
766
|
+
} : {
|
|
767
|
+
seconds,
|
|
768
|
+
repeats
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
throw new AmbaApiError("INVALID_ARGUMENT", "Amba.notifications.scheduleLocal: trigger must be { at: Date } or { inSeconds: number, repeats?: boolean }");
|
|
772
|
+
}
|
|
773
|
+
function validateContent(input) {
|
|
774
|
+
if (!input || typeof input.title !== "string" || input.title.trim() === "") throw new AmbaApiError("INVALID_ARGUMENT", "Amba.notifications.scheduleLocal: title is required");
|
|
775
|
+
if (typeof input.body !== "string") throw new AmbaApiError("INVALID_ARGUMENT", "Amba.notifications.scheduleLocal: body must be a string");
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* The `notifications` namespace. Shared by `@layers/amba-react-native`
|
|
779
|
+
* and (via re-export) `@layers/amba-expo`.
|
|
780
|
+
*/
|
|
781
|
+
const notifications = {
|
|
782
|
+
async scheduleLocal(input) {
|
|
783
|
+
validateContent(input);
|
|
784
|
+
const id = normalizeScheduleId(input.id);
|
|
785
|
+
const Notifications = await loadExpoNotifications();
|
|
786
|
+
const trigger = buildExpoTrigger(input, Notifications);
|
|
787
|
+
const existing = await Notifications.getPermissionsAsync();
|
|
788
|
+
let granted = existing.granted ?? existing.status === "granted";
|
|
789
|
+
if (!granted) {
|
|
790
|
+
const requested = await Notifications.requestPermissionsAsync();
|
|
791
|
+
granted = requested.granted ?? requested.status === "granted";
|
|
792
|
+
}
|
|
793
|
+
if (!granted) throw new AmbaApiError("LOCAL_NOTIFICATIONS_PERMISSION_DENIED", "user denied notification permission — local notifications cannot be scheduled");
|
|
794
|
+
return { id: await Notifications.scheduleNotificationAsync({
|
|
795
|
+
identifier: id,
|
|
796
|
+
content: {
|
|
797
|
+
title: input.title,
|
|
798
|
+
body: input.body,
|
|
799
|
+
data: {
|
|
800
|
+
...input.data,
|
|
801
|
+
[AMBA_LOCAL_ID_KEY]: id
|
|
802
|
+
}
|
|
803
|
+
},
|
|
804
|
+
trigger
|
|
805
|
+
}) || id };
|
|
806
|
+
},
|
|
807
|
+
async cancelLocal(id) {
|
|
808
|
+
if (typeof id !== "string" || id.trim() === "") throw new AmbaApiError("INVALID_ARGUMENT", "Amba.notifications.cancelLocal: id is required");
|
|
809
|
+
await (await loadExpoNotifications()).cancelScheduledNotificationAsync(id);
|
|
810
|
+
},
|
|
811
|
+
async listScheduledLocal() {
|
|
812
|
+
const scheduled = await (await loadExpoNotifications()).getAllScheduledNotificationsAsync();
|
|
813
|
+
const out = [];
|
|
814
|
+
for (const n of scheduled) {
|
|
815
|
+
const data = n.content?.data ?? {};
|
|
816
|
+
const markerId = data[AMBA_LOCAL_ID_KEY];
|
|
817
|
+
if (!markerId) continue;
|
|
818
|
+
out.push({
|
|
819
|
+
id: markerId,
|
|
820
|
+
title: n.content?.title ?? "",
|
|
821
|
+
body: n.content?.body ?? "",
|
|
822
|
+
data
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
return out;
|
|
826
|
+
}
|
|
827
|
+
};
|
|
828
|
+
|
|
829
|
+
//#endregion
|
|
830
|
+
//#region src/realtime.ts
|
|
831
|
+
const INITIAL_BACKOFF_MS = 500;
|
|
832
|
+
const MAX_BACKOFF_MS = 15e3;
|
|
833
|
+
const DEFAULT_API_URL = "https://api.amba.dev";
|
|
834
|
+
const DEFAULT_REALTIME_URL = "https://realtime.amba.host";
|
|
835
|
+
/**
|
|
836
|
+
* Resolve the base URL for live-update connections. Long-lived streams are
|
|
837
|
+
* served from a dedicated realtime host (no request-duration ceiling), so
|
|
838
|
+
* when the SDK points at the default production API the stream connects
|
|
839
|
+
* there instead. Any custom `apiUrl` (dev, staging, self-hosted, proxy)
|
|
840
|
+
* keeps live updates on that same origin — override semantics unchanged.
|
|
841
|
+
*/
|
|
842
|
+
function resolveRealtimeBaseUrl(baseUrl) {
|
|
843
|
+
return baseUrl.replace(/\/+$/, "") === DEFAULT_API_URL ? DEFAULT_REALTIME_URL : baseUrl;
|
|
844
|
+
}
|
|
845
|
+
/**
|
|
846
|
+
* Builder returned by `Amba.collection(name)`. Chain `.where(...)` to
|
|
847
|
+
* narrow, then `.subscribe(cb)` to start streaming.
|
|
848
|
+
*/
|
|
849
|
+
var CollectionSubscription = class {
|
|
850
|
+
filters = {};
|
|
851
|
+
constructor(ctx, name) {
|
|
852
|
+
this.ctx = ctx;
|
|
853
|
+
this.name = name;
|
|
854
|
+
}
|
|
855
|
+
/** Add an equality filter. Chainable. All filters must match (AND). */
|
|
856
|
+
where(column, value) {
|
|
857
|
+
this.filters[column] = value;
|
|
858
|
+
return this;
|
|
859
|
+
}
|
|
860
|
+
/**
|
|
861
|
+
* Start listening. `cb` fires once per matching row change. Returns an
|
|
862
|
+
* unsubscribe handle — call it to close the connection.
|
|
863
|
+
*/
|
|
864
|
+
subscribe(cb, options = {}) {
|
|
865
|
+
if (!this.ctx.authHeaders()) throw new Error("Amba.collection().subscribe() requires an authenticated session — call Amba.auth.signIn* first.");
|
|
866
|
+
const qs = Object.keys(this.filters).length > 0 ? `?where=${encodeURIComponent(JSON.stringify(this.filters))}` : "";
|
|
867
|
+
return openStream({
|
|
868
|
+
url: `${resolveRealtimeBaseUrl(this.ctx.baseUrl)}/v1/client/realtime/collections/${encodeURIComponent(this.name)}${qs}`,
|
|
869
|
+
authHeaders: this.ctx.authHeaders,
|
|
870
|
+
onChange: cb,
|
|
871
|
+
options,
|
|
872
|
+
parse: parseRowChangeFrame
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
};
|
|
876
|
+
/**
|
|
877
|
+
* Builder returned by `Amba.messaging.conversation(id)`. Call `.subscribe(cb)`
|
|
878
|
+
* to receive new messages live instead of polling.
|
|
879
|
+
*
|
|
880
|
+
* Delivery is scoped to conversation participants — you receive messages for
|
|
881
|
+
* a conversation only if your session is a member of it. Reconnects with the
|
|
882
|
+
* same exponential backoff as collection subscriptions.
|
|
883
|
+
*/
|
|
884
|
+
var ConversationSubscription = class {
|
|
885
|
+
constructor(ctx, conversationId) {
|
|
886
|
+
this.ctx = ctx;
|
|
887
|
+
this.conversationId = conversationId;
|
|
888
|
+
}
|
|
889
|
+
subscribe(cb, options = {}) {
|
|
890
|
+
if (!this.ctx.authHeaders()) throw new Error("Amba.messaging.conversation().subscribe() requires an authenticated session — call Amba.auth.signIn* first.");
|
|
891
|
+
return openStream({
|
|
892
|
+
url: `${resolveRealtimeBaseUrl(this.ctx.baseUrl)}/v1/client/realtime/conversations/${encodeURIComponent(this.conversationId)}`,
|
|
893
|
+
authHeaders: this.ctx.authHeaders,
|
|
894
|
+
onChange: cb,
|
|
895
|
+
options,
|
|
896
|
+
parse: parseRowChangeFrame
|
|
897
|
+
});
|
|
898
|
+
}
|
|
899
|
+
};
|
|
900
|
+
/**
|
|
901
|
+
* Builder returned by `Amba.gamification`. Call `.subscribe(cb)` to receive the
|
|
902
|
+
* signed-in user's xp / level / achievement / streak changes live instead of
|
|
903
|
+
* polling.
|
|
904
|
+
*
|
|
905
|
+
* Delivery is scoped to the signed-in user — you only ever receive your own
|
|
906
|
+
* gamification changes, never another user's. Reconnects with the same
|
|
907
|
+
* exponential backoff as collection subscriptions.
|
|
908
|
+
*/
|
|
909
|
+
var GamificationSubscription = class {
|
|
910
|
+
constructor(ctx) {
|
|
911
|
+
this.ctx = ctx;
|
|
912
|
+
}
|
|
913
|
+
subscribe(cb, options = {}) {
|
|
914
|
+
if (!this.ctx.authHeaders()) throw new Error("Amba.gamification.subscribe() requires an authenticated session — call Amba.auth.signIn* first.");
|
|
915
|
+
return openStream({
|
|
916
|
+
url: `${resolveRealtimeBaseUrl(this.ctx.baseUrl)}/v1/client/realtime/gamification`,
|
|
917
|
+
authHeaders: this.ctx.authHeaders,
|
|
918
|
+
onChange: cb,
|
|
919
|
+
options,
|
|
920
|
+
parse: parseGamificationFrame
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
};
|
|
924
|
+
/**
|
|
925
|
+
* Open a long-lived event stream and dispatch parsed events to `onChange`.
|
|
926
|
+
* Reconnects with exponential backoff until the returned unsubscribe handle
|
|
927
|
+
* is invoked. Chooses the XHR incremental-text transport (RN-native) when
|
|
928
|
+
* available, else the streamed-`fetch`-body transport (RN-for-web / Node).
|
|
929
|
+
*/
|
|
930
|
+
function openStream(args) {
|
|
931
|
+
let stopped = false;
|
|
932
|
+
let backoff = INITIAL_BACKOFF_MS;
|
|
933
|
+
let closeActive = null;
|
|
934
|
+
let settleActive = null;
|
|
935
|
+
const run = async () => {
|
|
936
|
+
while (!stopped) {
|
|
937
|
+
const headers = args.authHeaders();
|
|
938
|
+
if (!headers) {
|
|
939
|
+
args.options.onError?.(/* @__PURE__ */ new Error("no active session"));
|
|
940
|
+
break;
|
|
941
|
+
}
|
|
942
|
+
try {
|
|
943
|
+
await new Promise((resolve, reject) => {
|
|
944
|
+
settleActive = resolve;
|
|
945
|
+
const onFirstFrame = () => {
|
|
946
|
+
backoff = INITIAL_BACKOFF_MS;
|
|
947
|
+
args.options.onOpen?.();
|
|
948
|
+
};
|
|
949
|
+
closeActive = connectOnce({
|
|
950
|
+
url: args.url,
|
|
951
|
+
headers,
|
|
952
|
+
onFrame: (frame) => {
|
|
953
|
+
const ev = args.parse(frame);
|
|
954
|
+
if (ev !== null) args.onChange(ev);
|
|
955
|
+
},
|
|
956
|
+
onFirstFrame,
|
|
957
|
+
onDone: resolve,
|
|
958
|
+
onError: reject
|
|
959
|
+
});
|
|
960
|
+
});
|
|
961
|
+
} catch (err) {
|
|
962
|
+
if (stopped) break;
|
|
963
|
+
args.options.onError?.(err);
|
|
964
|
+
} finally {
|
|
965
|
+
closeActive?.();
|
|
966
|
+
closeActive = null;
|
|
967
|
+
settleActive = null;
|
|
968
|
+
}
|
|
969
|
+
if (stopped) break;
|
|
970
|
+
await delay(backoff);
|
|
971
|
+
backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
run();
|
|
975
|
+
return () => {
|
|
976
|
+
stopped = true;
|
|
977
|
+
closeActive?.();
|
|
978
|
+
settleActive?.();
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
/**
|
|
982
|
+
* Establish a single connection using the best available transport. Returns
|
|
983
|
+
* an abort function. The XHR transport is preferred on React Native; the
|
|
984
|
+
* fetch-stream transport covers RN-for-web and any runtime exposing a
|
|
985
|
+
* readable `response.body`.
|
|
986
|
+
*/
|
|
987
|
+
function connectOnce(args) {
|
|
988
|
+
if (typeof XMLHttpRequest !== "undefined") return connectXhr(args, XMLHttpRequest);
|
|
989
|
+
return connectFetchStream(args);
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* Incremental-`responseText` transport via XMLHttpRequest — the RN-native
|
|
993
|
+
* path. `onreadystatechange` fires at readyState 3 (LOADING) as bytes
|
|
994
|
+
* stream in; we track how much of `responseText` we've already parsed and
|
|
995
|
+
* extract any newly-completed `\n\n`-delimited frames.
|
|
996
|
+
*/
|
|
997
|
+
function connectXhr(args, XHR) {
|
|
998
|
+
const xhr = new XHR();
|
|
999
|
+
let consumed = 0;
|
|
1000
|
+
let buffer = "";
|
|
1001
|
+
let sawFrame = false;
|
|
1002
|
+
let aborted = false;
|
|
1003
|
+
const drain = () => {
|
|
1004
|
+
const text = xhr.responseText;
|
|
1005
|
+
if (text.length <= consumed) return;
|
|
1006
|
+
buffer += text.slice(consumed);
|
|
1007
|
+
consumed = text.length;
|
|
1008
|
+
let idx;
|
|
1009
|
+
while ((idx = buffer.indexOf("\n\n")) !== -1) {
|
|
1010
|
+
const frame = buffer.slice(0, idx);
|
|
1011
|
+
buffer = buffer.slice(idx + 2);
|
|
1012
|
+
if (!sawFrame) {
|
|
1013
|
+
sawFrame = true;
|
|
1014
|
+
args.onFirstFrame();
|
|
1015
|
+
}
|
|
1016
|
+
args.onFrame(frame);
|
|
1017
|
+
}
|
|
1018
|
+
};
|
|
1019
|
+
xhr.open("GET", args.url, true);
|
|
1020
|
+
for (const [k, v] of Object.entries(args.headers)) xhr.setRequestHeader(k, v);
|
|
1021
|
+
xhr.setRequestHeader("Accept", "text/event-stream");
|
|
1022
|
+
xhr.onreadystatechange = () => {
|
|
1023
|
+
if (aborted) return;
|
|
1024
|
+
if (xhr.readyState === 3) {
|
|
1025
|
+
if (xhr.status >= 400) return;
|
|
1026
|
+
drain();
|
|
1027
|
+
}
|
|
1028
|
+
};
|
|
1029
|
+
xhr.onload = () => {
|
|
1030
|
+
if (aborted) return;
|
|
1031
|
+
if (xhr.status >= 200 && xhr.status < 300) {
|
|
1032
|
+
drain();
|
|
1033
|
+
args.onDone();
|
|
1034
|
+
} else args.onError(/* @__PURE__ */ new Error(`realtime connect failed: HTTP ${xhr.status}`));
|
|
1035
|
+
};
|
|
1036
|
+
xhr.onerror = () => {
|
|
1037
|
+
if (aborted) return;
|
|
1038
|
+
args.onError(/* @__PURE__ */ new Error("realtime transport error"));
|
|
1039
|
+
};
|
|
1040
|
+
xhr.ontimeout = () => {
|
|
1041
|
+
if (aborted) return;
|
|
1042
|
+
args.onError(/* @__PURE__ */ new Error("realtime connection timed out"));
|
|
1043
|
+
};
|
|
1044
|
+
try {
|
|
1045
|
+
xhr.send();
|
|
1046
|
+
} catch (err) {
|
|
1047
|
+
args.onError(err);
|
|
1048
|
+
}
|
|
1049
|
+
return () => {
|
|
1050
|
+
aborted = true;
|
|
1051
|
+
try {
|
|
1052
|
+
xhr.abort();
|
|
1053
|
+
} catch {}
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
/**
|
|
1057
|
+
* Streamed-`fetch`-body transport — used when XHR isn't present (RN-for-web,
|
|
1058
|
+
* Node). Identical wire handling to web/node's `consume`.
|
|
1059
|
+
*/
|
|
1060
|
+
function connectFetchStream(args) {
|
|
1061
|
+
const controller = new AbortController();
|
|
1062
|
+
let aborted = false;
|
|
1063
|
+
(async () => {
|
|
1064
|
+
try {
|
|
1065
|
+
const resp = await fetch(args.url, {
|
|
1066
|
+
method: "GET",
|
|
1067
|
+
headers: {
|
|
1068
|
+
...args.headers,
|
|
1069
|
+
Accept: "text/event-stream"
|
|
1070
|
+
},
|
|
1071
|
+
signal: controller.signal
|
|
1072
|
+
});
|
|
1073
|
+
if (!resp.ok || !resp.body) throw new Error(`realtime connect failed: HTTP ${resp.status}`);
|
|
1074
|
+
const reader = resp.body.getReader();
|
|
1075
|
+
const decoder = new TextDecoder();
|
|
1076
|
+
let buffer = "";
|
|
1077
|
+
let sawFrame = false;
|
|
1078
|
+
for (;;) {
|
|
1079
|
+
const { done, value } = await reader.read();
|
|
1080
|
+
if (done) break;
|
|
1081
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1082
|
+
let idx;
|
|
1083
|
+
while ((idx = buffer.indexOf("\n\n")) !== -1) {
|
|
1084
|
+
const frame = buffer.slice(0, idx);
|
|
1085
|
+
buffer = buffer.slice(idx + 2);
|
|
1086
|
+
if (!sawFrame) {
|
|
1087
|
+
sawFrame = true;
|
|
1088
|
+
args.onFirstFrame();
|
|
1089
|
+
}
|
|
1090
|
+
args.onFrame(frame);
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
if (!aborted) args.onDone();
|
|
1094
|
+
} catch (err) {
|
|
1095
|
+
if (!aborted) args.onError(err);
|
|
1096
|
+
}
|
|
1097
|
+
})();
|
|
1098
|
+
return () => {
|
|
1099
|
+
aborted = true;
|
|
1100
|
+
controller.abort();
|
|
1101
|
+
};
|
|
1102
|
+
}
|
|
1103
|
+
/** Pull the `event:` name + joined `data:` lines out of one raw frame. */
|
|
1104
|
+
function readFrame(frame) {
|
|
1105
|
+
let event = "";
|
|
1106
|
+
const dataLines = [];
|
|
1107
|
+
for (const line of frame.split("\n")) {
|
|
1108
|
+
if (line.startsWith(":")) continue;
|
|
1109
|
+
if (line.startsWith("event:")) event = line.slice(6).trim();
|
|
1110
|
+
else if (line.startsWith("data:")) dataLines.push(line.slice(5).trim());
|
|
1111
|
+
}
|
|
1112
|
+
return {
|
|
1113
|
+
event,
|
|
1114
|
+
data: dataLines.join("\n")
|
|
1115
|
+
};
|
|
1116
|
+
}
|
|
1117
|
+
function parseRowChangeFrame(frame) {
|
|
1118
|
+
const { event, data } = readFrame(frame);
|
|
1119
|
+
if (event !== "change") return null;
|
|
1120
|
+
try {
|
|
1121
|
+
const payload = JSON.parse(data);
|
|
1122
|
+
return {
|
|
1123
|
+
op: payload.op,
|
|
1124
|
+
row: payload.row,
|
|
1125
|
+
truncated: payload.truncated
|
|
1126
|
+
};
|
|
1127
|
+
} catch {
|
|
1128
|
+
return null;
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
function parseGamificationFrame(frame) {
|
|
1132
|
+
const { event, data } = readFrame(frame);
|
|
1133
|
+
if (event !== "change") return null;
|
|
1134
|
+
try {
|
|
1135
|
+
const payload = JSON.parse(data);
|
|
1136
|
+
return {
|
|
1137
|
+
kind: payload.kind,
|
|
1138
|
+
data: payload.data,
|
|
1139
|
+
truncated: payload.truncated
|
|
1140
|
+
};
|
|
1141
|
+
} catch {
|
|
1142
|
+
return null;
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
function delay(ms) {
|
|
1146
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1147
|
+
}
|
|
1148
|
+
|
|
353
1149
|
//#endregion
|
|
354
1150
|
//#region src/index.ts
|
|
355
1151
|
/** SDK semver — burned in at build time. Bump alongside package.json. */
|
|
356
|
-
const SDK_VERSION = "4.0.
|
|
1152
|
+
const SDK_VERSION = "4.0.5";
|
|
357
1153
|
/**
|
|
358
1154
|
* Default host that serves deployed functions. `Amba.functions.invoke(name)`
|
|
359
1155
|
* targets `https://<projectId>.<DEFAULT_FUNCTIONS_HOST>/<name>` unless a
|
|
@@ -361,10 +1157,33 @@ const SDK_VERSION = "4.0.3";
|
|
|
361
1157
|
*/
|
|
362
1158
|
const DEFAULT_FUNCTIONS_HOST = "fn.amba.host";
|
|
363
1159
|
let state = null;
|
|
1160
|
+
/**
|
|
1161
|
+
* Monotonic token identifying the current offline activation. Bumped on every
|
|
1162
|
+
* `offline.enable()` AND every `configure()`, captured by each `enable()` into
|
|
1163
|
+
* its disable callback. A disabler only acts while the token still matches — so
|
|
1164
|
+
* a stale disabler (held across a re-`enable()` or a reconfigure) no-ops
|
|
1165
|
+
* instead of disabling the now-active outbox.
|
|
1166
|
+
*/
|
|
1167
|
+
let _offlineEnableToken = 0;
|
|
364
1168
|
function getState() {
|
|
365
1169
|
if (!state) throw new AmbaApiError("NOT_INITIALIZED", "@layers/amba-react-native: SDK not configured. Call Amba.configure({ projectId, clientKey }) at app start.");
|
|
366
1170
|
return state;
|
|
367
1171
|
}
|
|
1172
|
+
/**
|
|
1173
|
+
* Build the auth headers for a realtime subscribe connection, or `null`
|
|
1174
|
+
* when the SDK isn't configured or there's no live session. Read lazily at
|
|
1175
|
+
* connect time so reconnects pick up a rotated session token (the identity
|
|
1176
|
+
* store holds the canonical, auto-refreshed copy).
|
|
1177
|
+
*/
|
|
1178
|
+
function realtimeAuthHeaders() {
|
|
1179
|
+
if (!state) return null;
|
|
1180
|
+
const token = state.identity.getSessionToken();
|
|
1181
|
+
if (!token) return null;
|
|
1182
|
+
return {
|
|
1183
|
+
"X-Api-Key": state.clientKey,
|
|
1184
|
+
Authorization: `Bearer ${token}`
|
|
1185
|
+
};
|
|
1186
|
+
}
|
|
368
1187
|
const authSubscribers = /* @__PURE__ */ new Set();
|
|
369
1188
|
function snapshotSession(user) {
|
|
370
1189
|
if (!user) return null;
|
|
@@ -490,6 +1309,8 @@ const P = {
|
|
|
490
1309
|
pushSubscribe: "/v1/client/push/subscribe",
|
|
491
1310
|
pushUnsubscribe: "/v1/client/push/unsubscribe",
|
|
492
1311
|
entitlements: "/v1/client/entitlements",
|
|
1312
|
+
entitlementsRestore: "/v1/client/entitlements/restore",
|
|
1313
|
+
offerings: "/v1/client/offerings",
|
|
493
1314
|
aiAnthropic: "/v1/client/ai/anthropic/messages",
|
|
494
1315
|
config: "/v1/client/config",
|
|
495
1316
|
flags: "/v1/client/flags",
|
|
@@ -535,6 +1356,74 @@ async function resolveFunctionUrl(s, name) {
|
|
|
535
1356
|
return `https://${s.resolvedFunctionsProjectId}.${DEFAULT_FUNCTIONS_HOST}/${encodeURIComponent(name)}`;
|
|
536
1357
|
}
|
|
537
1358
|
/**
|
|
1359
|
+
* Bridge the AsyncStorage-backed persistence to the {@link KvStore} the
|
|
1360
|
+
* outbox persists through. Namespaced under the configured storage prefix so
|
|
1361
|
+
* multiple projects in one app don't collide.
|
|
1362
|
+
*/
|
|
1363
|
+
function offlineStore(s) {
|
|
1364
|
+
return {
|
|
1365
|
+
get: (key) => s.persistence.read(key),
|
|
1366
|
+
set: (key, value) => s.persistence.write(key, value),
|
|
1367
|
+
delete: (key) => s.persistence.delete(key)
|
|
1368
|
+
};
|
|
1369
|
+
}
|
|
1370
|
+
/**
|
|
1371
|
+
* Replay one queued mutation against the live API, forwarding the op's
|
|
1372
|
+
* idempotency key on collection inserts so a write that landed before the
|
|
1373
|
+
* connection dropped is never double-applied (API migration 056).
|
|
1374
|
+
*/
|
|
1375
|
+
async function replayOutboxOp(s, op) {
|
|
1376
|
+
switch (op.kind) {
|
|
1377
|
+
case "collection.insert":
|
|
1378
|
+
await s.http.post(`${P.collections}/${encodePathSegment(op.collection)}`, {
|
|
1379
|
+
...op.payload ?? {},
|
|
1380
|
+
idempotency_key: op.idempotencyKey
|
|
1381
|
+
});
|
|
1382
|
+
return;
|
|
1383
|
+
case "collection.update":
|
|
1384
|
+
await s.http.patch(`${P.collections}/${encodePathSegment(op.collection)}/${encodePathSegment(op.id)}`, { set: op.payload ?? {} });
|
|
1385
|
+
return;
|
|
1386
|
+
case "collection.delete":
|
|
1387
|
+
await s.http.delete(`${P.collections}/${encodePathSegment(op.collection)}/${encodePathSegment(op.id)}`);
|
|
1388
|
+
return;
|
|
1389
|
+
case "track":
|
|
1390
|
+
try {
|
|
1391
|
+
await s.http.post(P.events, {
|
|
1392
|
+
event: op.event,
|
|
1393
|
+
properties: op.properties ?? void 0,
|
|
1394
|
+
anonymous_id: s.identity.getAnonymousId(),
|
|
1395
|
+
timestamp: op.occurredAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
1396
|
+
...op.telemetry ? { telemetry: true } : {}
|
|
1397
|
+
});
|
|
1398
|
+
} catch (err) {
|
|
1399
|
+
const code = err?.code;
|
|
1400
|
+
if (code === "UNAUTHORIZED" || code === "FORBIDDEN") throw new AmbaApiError("NETWORK_ERROR", "track replay deferred: no valid session");
|
|
1401
|
+
throw err;
|
|
1402
|
+
}
|
|
1403
|
+
return;
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
function getOfflineQueue(s) {
|
|
1407
|
+
if (!s.offlineQueue) s.offlineQueue = new OfflineQueue({
|
|
1408
|
+
store: offlineStore(s),
|
|
1409
|
+
storageKey: `offline_outbox:${s.projectId}`,
|
|
1410
|
+
executor: (op) => replayOutboxOp(s, op),
|
|
1411
|
+
onDropped: (op, err) => {
|
|
1412
|
+
if (typeof console !== "undefined") console.warn(`[amba] dropped un-replayable offline ${op.kind} (${op.collection ?? op.event ?? "?"}):`, err);
|
|
1413
|
+
}
|
|
1414
|
+
});
|
|
1415
|
+
return s.offlineQueue;
|
|
1416
|
+
}
|
|
1417
|
+
async function insertDirect(s, name, row) {
|
|
1418
|
+
return (await s.http.post(`${P.collections}/${encodePathSegment(name)}`, row)).data;
|
|
1419
|
+
}
|
|
1420
|
+
async function updateDirect(s, name, id, set) {
|
|
1421
|
+
return (await s.http.patch(`${P.collections}/${encodePathSegment(name)}/${encodePathSegment(id)}`, { set })).data;
|
|
1422
|
+
}
|
|
1423
|
+
async function deleteDirect(s, name, id) {
|
|
1424
|
+
return await s.http.delete(`${P.collections}/${encodePathSegment(name)}/${encodePathSegment(id)}`) ?? { data: { deleted: true } };
|
|
1425
|
+
}
|
|
1426
|
+
/**
|
|
538
1427
|
* Top-level SDK namespace for React Native.
|
|
539
1428
|
*/
|
|
540
1429
|
const Amba = {
|
|
@@ -546,23 +1435,32 @@ const Amba = {
|
|
|
546
1435
|
const identity = await IdentityStore.create(persistence);
|
|
547
1436
|
const baseUrl = (config.apiUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
548
1437
|
const sdkVersionHeader = `amba-sdk/${SDK_VERSION} ${`amba-react-native/${SDK_VERSION}`}`;
|
|
1438
|
+
const http = new AmbaHttpClient({
|
|
1439
|
+
apiKey: config.clientKey,
|
|
1440
|
+
baseUrl,
|
|
1441
|
+
sdkPlatform: "react-native",
|
|
1442
|
+
sdkVersionHeader,
|
|
1443
|
+
identity,
|
|
1444
|
+
ensureSession: config.autoAnonymousSession === false ? void 0 : async (path) => {
|
|
1445
|
+
if (pathSkipsLazySession(path)) return;
|
|
1446
|
+
await ensureAnonymousSession(getState());
|
|
1447
|
+
}
|
|
1448
|
+
});
|
|
1449
|
+
const prior = state;
|
|
1450
|
+
_offlineEnableToken += 1;
|
|
1451
|
+
if (prior?.offlineQueue) await prior.offlineQueue.dispose();
|
|
549
1452
|
state = {
|
|
550
|
-
http
|
|
551
|
-
apiKey: config.clientKey,
|
|
552
|
-
baseUrl,
|
|
553
|
-
sdkPlatform: "react-native",
|
|
554
|
-
sdkVersionHeader,
|
|
555
|
-
identity,
|
|
556
|
-
ensureSession: config.autoAnonymousSession === false ? void 0 : async (path) => {
|
|
557
|
-
if (pathSkipsLazySession(path)) return;
|
|
558
|
-
await ensureAnonymousSession(getState());
|
|
559
|
-
}
|
|
560
|
-
}),
|
|
1453
|
+
http,
|
|
561
1454
|
identity,
|
|
562
1455
|
debug: config.debug ?? false,
|
|
563
1456
|
projectId: config.projectId,
|
|
1457
|
+
clientKey: config.clientKey,
|
|
1458
|
+
baseUrl,
|
|
564
1459
|
functionsBaseUrl: config.functionsBaseUrl ?? null,
|
|
565
|
-
resolvedFunctionsProjectId: null
|
|
1460
|
+
resolvedFunctionsProjectId: null,
|
|
1461
|
+
persistence,
|
|
1462
|
+
offlineEnabled: false,
|
|
1463
|
+
offlineQueue: null
|
|
566
1464
|
};
|
|
567
1465
|
},
|
|
568
1466
|
_reset: () => {
|
|
@@ -584,16 +1482,41 @@ const Amba = {
|
|
|
584
1482
|
setDebug: (enabled) => {
|
|
585
1483
|
getState().debug = enabled;
|
|
586
1484
|
},
|
|
1485
|
+
collection: (name) => new CollectionSubscription({
|
|
1486
|
+
baseUrl: getState().baseUrl,
|
|
1487
|
+
authHeaders: realtimeAuthHeaders
|
|
1488
|
+
}, name),
|
|
1489
|
+
get gamification() {
|
|
1490
|
+
return new GamificationSubscription({
|
|
1491
|
+
baseUrl: getState().baseUrl,
|
|
1492
|
+
authHeaders: realtimeAuthHeaders
|
|
1493
|
+
});
|
|
1494
|
+
},
|
|
587
1495
|
events: { track: async (event, properties, options) => {
|
|
588
1496
|
const s = getState();
|
|
1497
|
+
const occurredAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
589
1498
|
const body = {
|
|
590
1499
|
event,
|
|
591
1500
|
properties: properties ?? void 0,
|
|
592
1501
|
anonymous_id: s.identity.getAnonymousId(),
|
|
593
|
-
timestamp:
|
|
1502
|
+
timestamp: occurredAt
|
|
594
1503
|
};
|
|
595
1504
|
if (options?.telemetry) body["telemetry"] = true;
|
|
596
|
-
|
|
1505
|
+
try {
|
|
1506
|
+
await s.http.post(P.events, body);
|
|
1507
|
+
} catch (err) {
|
|
1508
|
+
if (s.offlineEnabled && isOfflineError(err)) {
|
|
1509
|
+
await getOfflineQueue(s).enqueue({
|
|
1510
|
+
kind: "track",
|
|
1511
|
+
event,
|
|
1512
|
+
properties,
|
|
1513
|
+
telemetry: options?.telemetry,
|
|
1514
|
+
occurredAt
|
|
1515
|
+
});
|
|
1516
|
+
return;
|
|
1517
|
+
}
|
|
1518
|
+
throw err;
|
|
1519
|
+
}
|
|
597
1520
|
} },
|
|
598
1521
|
auth: {
|
|
599
1522
|
signInAnonymously: async () => {
|
|
@@ -794,6 +1717,23 @@ const Amba = {
|
|
|
794
1717
|
return (await getState().http.get(P.sync, query)).data;
|
|
795
1718
|
}
|
|
796
1719
|
},
|
|
1720
|
+
offline: {
|
|
1721
|
+
enable: () => {
|
|
1722
|
+
const s = getState();
|
|
1723
|
+
s.offlineEnabled = true;
|
|
1724
|
+
_offlineEnableToken += 1;
|
|
1725
|
+
const token = _offlineEnableToken;
|
|
1726
|
+
return () => {
|
|
1727
|
+
if (_offlineEnableToken !== token || state !== s) return;
|
|
1728
|
+
s.offlineEnabled = false;
|
|
1729
|
+
};
|
|
1730
|
+
},
|
|
1731
|
+
isEnabled: () => getState().offlineEnabled,
|
|
1732
|
+
pendingCount: async () => getOfflineQueue(getState()).pendingCount(),
|
|
1733
|
+
pending: async () => getOfflineQueue(getState()).pending(),
|
|
1734
|
+
flush: async () => getOfflineQueue(getState()).flush(),
|
|
1735
|
+
clear: async () => getOfflineQueue(getState()).clear()
|
|
1736
|
+
},
|
|
797
1737
|
collections: {
|
|
798
1738
|
find: async (name, options = {}) => {
|
|
799
1739
|
return getState().http.post(`${P.collections}/${encodePathSegment(name)}/find`, options);
|
|
@@ -816,14 +1756,86 @@ const Amba = {
|
|
|
816
1756
|
return (await s.http.get(`${P.collections}/${encodePathSegment(name)}/count`, query)).data.count;
|
|
817
1757
|
},
|
|
818
1758
|
insert: async (name, row) => {
|
|
819
|
-
|
|
1759
|
+
const s = getState();
|
|
1760
|
+
if (s.offlineEnabled) {
|
|
1761
|
+
const idempotencyKey = (typeof row["idempotency_key"] === "string" ? row["idempotency_key"] : void 0) ?? newIdempotencyKey();
|
|
1762
|
+
try {
|
|
1763
|
+
return (await s.http.post(`${P.collections}/${encodePathSegment(name)}`, {
|
|
1764
|
+
...row,
|
|
1765
|
+
idempotency_key: idempotencyKey
|
|
1766
|
+
})).data;
|
|
1767
|
+
} catch (err) {
|
|
1768
|
+
if (isOfflineError(err)) {
|
|
1769
|
+
await getOfflineQueue(s).enqueue({
|
|
1770
|
+
kind: "collection.insert",
|
|
1771
|
+
collection: name,
|
|
1772
|
+
payload: row,
|
|
1773
|
+
idempotencyKey
|
|
1774
|
+
});
|
|
1775
|
+
return {
|
|
1776
|
+
...row,
|
|
1777
|
+
_amba_pending: true
|
|
1778
|
+
};
|
|
1779
|
+
}
|
|
1780
|
+
throw err;
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
return (await s.http.post(`${P.collections}/${encodePathSegment(name)}`, row)).data;
|
|
820
1784
|
},
|
|
821
1785
|
update: async (name, id, set) => {
|
|
822
|
-
|
|
1786
|
+
const s = getState();
|
|
1787
|
+
if (s.offlineEnabled) try {
|
|
1788
|
+
return (await s.http.patch(`${P.collections}/${encodePathSegment(name)}/${encodePathSegment(id)}`, { set })).data;
|
|
1789
|
+
} catch (err) {
|
|
1790
|
+
if (isOfflineError(err)) {
|
|
1791
|
+
await getOfflineQueue(s).enqueue({
|
|
1792
|
+
kind: "collection.update",
|
|
1793
|
+
collection: name,
|
|
1794
|
+
id,
|
|
1795
|
+
payload: set
|
|
1796
|
+
});
|
|
1797
|
+
return {
|
|
1798
|
+
id,
|
|
1799
|
+
...set,
|
|
1800
|
+
_amba_pending: true
|
|
1801
|
+
};
|
|
1802
|
+
}
|
|
1803
|
+
throw err;
|
|
1804
|
+
}
|
|
1805
|
+
return (await s.http.patch(`${P.collections}/${encodePathSegment(name)}/${encodePathSegment(id)}`, { set })).data;
|
|
823
1806
|
},
|
|
824
1807
|
delete: async (name, id) => {
|
|
825
|
-
|
|
826
|
-
|
|
1808
|
+
const s = getState();
|
|
1809
|
+
if (s.offlineEnabled) try {
|
|
1810
|
+
return await s.http.delete(`${P.collections}/${encodePathSegment(name)}/${encodePathSegment(id)}`) ?? { data: { deleted: true } };
|
|
1811
|
+
} catch (err) {
|
|
1812
|
+
if (isOfflineError(err)) {
|
|
1813
|
+
await getOfflineQueue(s).enqueue({
|
|
1814
|
+
kind: "collection.delete",
|
|
1815
|
+
collection: name,
|
|
1816
|
+
id
|
|
1817
|
+
});
|
|
1818
|
+
return { data: { deleted: true } };
|
|
1819
|
+
}
|
|
1820
|
+
throw err;
|
|
1821
|
+
}
|
|
1822
|
+
return await s.http.delete(`${P.collections}/${encodePathSegment(name)}/${encodePathSegment(id)}`) ?? { data: { deleted: true } };
|
|
1823
|
+
},
|
|
1824
|
+
optimisticInsert: async (name, row, view) => withOptimistic({
|
|
1825
|
+
apply: view.apply,
|
|
1826
|
+
mutate: () => insertDirect(getState(), name, row),
|
|
1827
|
+
rollback: view.rollback
|
|
1828
|
+
}),
|
|
1829
|
+
optimisticUpdate: async (name, id, set, view) => withOptimistic({
|
|
1830
|
+
apply: view.apply,
|
|
1831
|
+
mutate: () => updateDirect(getState(), name, id, set),
|
|
1832
|
+
rollback: view.rollback
|
|
1833
|
+
}),
|
|
1834
|
+
optimisticDelete: async (name, id, view) => withOptimistic({
|
|
1835
|
+
apply: view.apply,
|
|
1836
|
+
mutate: () => deleteDirect(getState(), name, id),
|
|
1837
|
+
rollback: view.rollback
|
|
1838
|
+
}),
|
|
827
1839
|
where: {
|
|
828
1840
|
eq: (column, value) => ({
|
|
829
1841
|
column,
|
|
@@ -951,16 +1963,24 @@ const Amba = {
|
|
|
951
1963
|
},
|
|
952
1964
|
unsubscribe: async (topic) => {
|
|
953
1965
|
await getState().http.post(P.pushUnsubscribe, { topic });
|
|
954
|
-
}
|
|
1966
|
+
},
|
|
1967
|
+
enableAutoRotation: (subscribe, platform = "fcm") => enableNativePushAutoRotation(subscribe, (token, p) => Amba.push.register(token, p), platform)
|
|
955
1968
|
},
|
|
1969
|
+
notifications,
|
|
956
1970
|
entitlements: {
|
|
957
1971
|
list: async () => {
|
|
958
1972
|
return (await getState().http.get(P.entitlements)).data;
|
|
959
1973
|
},
|
|
960
|
-
has: async (
|
|
961
|
-
return (await getState().http.get(P.entitlements, { active_only: "true" })).data.some((e) => e.
|
|
1974
|
+
has: async (entitlementId) => {
|
|
1975
|
+
return (await getState().http.get(P.entitlements, { active_only: "true" })).data.some((e) => e.entitlement_id === entitlementId && e.is_active);
|
|
1976
|
+
},
|
|
1977
|
+
restore: async () => {
|
|
1978
|
+
return (await getState().http.post(P.entitlementsRestore, {})).data;
|
|
962
1979
|
}
|
|
963
1980
|
},
|
|
1981
|
+
offerings: async (offeringId) => {
|
|
1982
|
+
return (await getState().http.get(P.offerings, offeringId ? { offering_id: offeringId } : void 0)).data;
|
|
1983
|
+
},
|
|
964
1984
|
ai: { anthropic: { messages: { create: async (request) => {
|
|
965
1985
|
const env = await getState().http.post(P.aiAnthropic, request);
|
|
966
1986
|
if (!env || typeof env !== "object" || env.data === void 0) throw new AmbaApiError("MALFORMED_RESPONSE", "AI response was not wrapped in the expected { data } envelope", env);
|
|
@@ -1206,6 +2226,10 @@ const Amba = {
|
|
|
1206
2226
|
}
|
|
1207
2227
|
},
|
|
1208
2228
|
messaging: {
|
|
2229
|
+
conversation: (conversationId) => new ConversationSubscription({
|
|
2230
|
+
baseUrl: getState().baseUrl,
|
|
2231
|
+
authHeaders: realtimeAuthHeaders
|
|
2232
|
+
}, conversationId),
|
|
1209
2233
|
createConversation: async (request) => {
|
|
1210
2234
|
return (await getState().http.post(`${P.messaging}/conversations`, request)).data;
|
|
1211
2235
|
},
|
|
@@ -1349,5 +2373,5 @@ const Amba = {
|
|
|
1349
2373
|
};
|
|
1350
2374
|
|
|
1351
2375
|
//#endregion
|
|
1352
|
-
export { Amba, AmbaApiError, SDK_VERSION };
|
|
2376
|
+
export { Amba, AmbaApiError, CollectionSubscription, ConversationSubscription, GamificationSubscription, SDK_VERSION, withOptimistic };
|
|
1353
2377
|
//# sourceMappingURL=index.js.map
|