@drakkar.software/starfish-client 1.6.0 → 1.11.0

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.
@@ -0,0 +1,19 @@
1
+ import type { StoreApi } from "zustand/vanilla";
2
+ import type { StarfishStore } from "./zustand.js";
3
+ /**
4
+ * Syncs a Zustand Starfish store across browser tabs using BroadcastChannel.
5
+ * Returns a cleanup function that closes the channel.
6
+ */
7
+ export declare function setupBroadcastSync(store: StoreApi<StarfishStore>, name: string): () => void;
8
+ /**
9
+ * Syncs a Zustand Starfish store across browser tabs using storage events.
10
+ * Fallback for environments without BroadcastChannel.
11
+ * Returns a cleanup function.
12
+ */
13
+ export declare function setupStorageFallback(store: StoreApi<StarfishStore>, name: string): () => void;
14
+ /**
15
+ * Auto-detects the best cross-tab sync mechanism and sets it up.
16
+ * Uses BroadcastChannel when available, falls back to storage events.
17
+ * Returns a cleanup function.
18
+ */
19
+ export declare function setupCrossTabSync(store: StoreApi<StarfishStore>, name: string): () => void;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Syncs a Zustand Starfish store across browser tabs using BroadcastChannel.
3
+ * Returns a cleanup function that closes the channel.
4
+ */
5
+ export function setupBroadcastSync(store, name) {
6
+ const channel = new BroadcastChannel(`starfish-${name}`);
7
+ let lastReceivedData = null;
8
+ channel.onmessage = (event) => {
9
+ lastReceivedData = event.data.data;
10
+ store.setState({ data: event.data.data, dirty: event.data.dirty });
11
+ };
12
+ const unsub = store.subscribe((state, prev) => {
13
+ if (state.data === lastReceivedData)
14
+ return;
15
+ if (state.data !== prev.data || state.dirty !== prev.dirty) {
16
+ channel.postMessage({ data: state.data, dirty: state.dirty });
17
+ }
18
+ });
19
+ return () => {
20
+ unsub();
21
+ channel.close();
22
+ };
23
+ }
24
+ /**
25
+ * Syncs a Zustand Starfish store across browser tabs using storage events.
26
+ * Fallback for environments without BroadcastChannel.
27
+ * Returns a cleanup function.
28
+ */
29
+ export function setupStorageFallback(store, name) {
30
+ const storageKey = `starfish-broadcast-${name}`;
31
+ let lastReceivedData = null;
32
+ const onStorage = (e) => {
33
+ if (e.key !== storageKey || !e.newValue)
34
+ return;
35
+ const payload = JSON.parse(e.newValue);
36
+ lastReceivedData = payload.data;
37
+ store.setState({ data: payload.data, dirty: payload.dirty });
38
+ };
39
+ globalThis.addEventListener("storage", onStorage);
40
+ const unsub = store.subscribe((state, prev) => {
41
+ if (state.data === lastReceivedData)
42
+ return;
43
+ if (state.data !== prev.data || state.dirty !== prev.dirty) {
44
+ localStorage.setItem(storageKey, JSON.stringify({ data: state.data, dirty: state.dirty }));
45
+ }
46
+ });
47
+ return () => {
48
+ unsub();
49
+ globalThis.removeEventListener("storage", onStorage);
50
+ };
51
+ }
52
+ /**
53
+ * Auto-detects the best cross-tab sync mechanism and sets it up.
54
+ * Uses BroadcastChannel when available, falls back to storage events.
55
+ * Returns a cleanup function.
56
+ */
57
+ export function setupCrossTabSync(store, name) {
58
+ if (typeof BroadcastChannel !== "undefined") {
59
+ return setupBroadcastSync(store, name);
60
+ }
61
+ if (typeof globalThis.addEventListener === "function" && typeof localStorage !== "undefined") {
62
+ return setupStorageFallback(store, name);
63
+ }
64
+ return () => { };
65
+ }
@@ -0,0 +1,12 @@
1
+ import type { StoreApi } from "zustand/vanilla";
2
+ import type { StarfishStore, StarfishState } from "./zustand.js";
3
+ /** Derived sync status for UI display. */
4
+ export type SyncStatus = "synced" | "syncing" | "pending" | "error" | "offline";
5
+ /** Derive a single sync status from store state. */
6
+ export declare function deriveSyncStatus(state: StarfishState): SyncStatus;
7
+ /** Use the full Starfish store state and actions. */
8
+ export declare function useStarfish(store: StoreApi<StarfishStore>): StarfishStore;
9
+ /** Use only the synced data, with an optional selector for fine-grained subscriptions. */
10
+ export declare function useStarfishData<T = Record<string, unknown>>(store: StoreApi<StarfishStore>, selector?: (data: Record<string, unknown>) => T): T;
11
+ /** Use the derived sync status (synced | syncing | pending | error | offline). */
12
+ export declare function useSyncStatus(store: StoreApi<StarfishStore>): SyncStatus;
@@ -0,0 +1,25 @@
1
+ import { useStore } from "zustand";
2
+ /** Derive a single sync status from store state. */
3
+ export function deriveSyncStatus(state) {
4
+ if (!state.online)
5
+ return "offline";
6
+ if (state.error)
7
+ return "error";
8
+ if (state.syncing)
9
+ return "syncing";
10
+ if (state.dirty)
11
+ return "pending";
12
+ return "synced";
13
+ }
14
+ /** Use the full Starfish store state and actions. */
15
+ export function useStarfish(store) {
16
+ return useStore(store);
17
+ }
18
+ /** Use only the synced data, with an optional selector for fine-grained subscriptions. */
19
+ export function useStarfishData(store, selector) {
20
+ return useStore(store, (state) => selector ? selector(state.data) : state.data);
21
+ }
22
+ /** Use the derived sync status (synced | syncing | pending | error | offline). */
23
+ export function useSyncStatus(store) {
24
+ return useStore(store, deriveSyncStatus);
25
+ }
@@ -1,5 +1,6 @@
1
1
  import type { StoreApi } from "zustand/vanilla";
2
2
  import type { StarfishStore } from "./bindings/zustand.js";
3
+ import type { SyncManager } from "./sync.js";
3
4
  export interface DebouncedSyncOptions {
4
5
  /**
5
6
  * How long to wait after the last `notify()` call before pushing (default: 2000 ms).
@@ -44,6 +45,48 @@ export interface DebouncedSync {
44
45
  /** Cancel any pending debounced push. Does not affect an already-in-flight push. */
45
46
  cancel: () => void;
46
47
  }
48
+ export interface DebouncedPushOptions {
49
+ /**
50
+ * How long to wait after the last `notify()` call before pushing (default: 2000 ms).
51
+ */
52
+ delayMs?: number;
53
+ /**
54
+ * Required: provides the document to push when the debounce timer fires.
55
+ * Called inside the timer so it always captures the latest state.
56
+ */
57
+ serialize: () => Record<string, unknown>;
58
+ /**
59
+ * Emit a warning when the estimated encrypted payload exceeds this byte count (default: 900 KB).
60
+ * Set to `Infinity` to disable.
61
+ */
62
+ warnBytes?: number;
63
+ /**
64
+ * Block the push when the estimated encrypted payload exceeds this byte count (default: 1 MB).
65
+ * Set to `Infinity` to disable.
66
+ */
67
+ maxBytes?: number;
68
+ /**
69
+ * Called when the estimated payload size exceeds `warnBytes` but is below `maxBytes`.
70
+ */
71
+ onSizeWarning?: (estimatedBytes: number) => void;
72
+ /**
73
+ * Called when the estimated payload size exceeds `maxBytes`. The push is blocked.
74
+ * If omitted, a console error is printed.
75
+ */
76
+ onSizeExceeded?: (estimatedBytes: number) => void;
77
+ /**
78
+ * Called when `syncManager.push()` throws. Default: `console.warn`.
79
+ */
80
+ onError?: (err: unknown) => void;
81
+ }
82
+ export interface DebouncedPush {
83
+ /**
84
+ * Schedule a push. If called again within `delayMs`, the timer resets.
85
+ */
86
+ notify: () => void;
87
+ /** Cancel any pending debounced push. Does not affect an already-in-flight push. */
88
+ cancel: () => void;
89
+ }
47
90
  /**
48
91
  * Creates a debounced push helper that coalesces rapid mutations into a single sync.
49
92
  *
@@ -64,3 +107,25 @@ export interface DebouncedSync {
64
107
  * ```
65
108
  */
66
109
  export declare function createDebouncedSync(store: StoreApi<StarfishStore>, options?: DebouncedSyncOptions): DebouncedSync;
110
+ /**
111
+ * Creates a debounced push helper that calls `syncManager.push()` directly,
112
+ * without requiring a Zustand store.
113
+ *
114
+ * Use this for one-way publishing workflows: public pages, derived snapshots,
115
+ * or any case where you want to push data without a full `createStarfishStore` setup.
116
+ *
117
+ * ```ts
118
+ * const syncManager = new SyncManager({ client, pullPath, pushPath })
119
+ *
120
+ * const { notify, cancel } = createDebouncedPush(syncManager, {
121
+ * serialize: () => buildPublicPageDocument(),
122
+ * })
123
+ *
124
+ * // Push after every relevant store mutation:
125
+ * planningStore.subscribe(() => notify())
126
+ *
127
+ * // Clean up on teardown:
128
+ * cancel()
129
+ * ```
130
+ */
131
+ export declare function createDebouncedPush(syncManager: SyncManager, options: DebouncedPushOptions): DebouncedPush;
@@ -2,6 +2,32 @@
2
2
  const DEFAULT_DELAY_MS = 2000;
3
3
  const DEFAULT_WARN_BYTES = 900 * 1024; // 900 KB
4
4
  const DEFAULT_MAX_BYTES = 1024 * 1024; // 1 MB
5
+ /** Returns true if the push should be blocked. */
6
+ function checkPayloadSize(doc, opts) {
7
+ // Estimate encrypted payload size. AES-GCM output is similar to input size;
8
+ // base64 encoding adds ~33% overhead, plus a small IV/tag overhead.
9
+ const estimatedBytes = Math.ceil(JSON.stringify(doc).length * 1.34);
10
+ if (estimatedBytes > opts.maxBytes) {
11
+ if (opts.onSizeExceeded) {
12
+ opts.onSizeExceeded(estimatedBytes);
13
+ }
14
+ else {
15
+ console.error(`[starfish] Push blocked: estimated payload ${(estimatedBytes / 1024).toFixed(0)} KB ` +
16
+ `exceeds limit of ${(opts.maxBytes / 1024).toFixed(0)} KB. Prune your data before syncing.`);
17
+ }
18
+ return true;
19
+ }
20
+ if (estimatedBytes > opts.warnBytes) {
21
+ if (opts.onSizeWarning) {
22
+ opts.onSizeWarning(estimatedBytes);
23
+ }
24
+ else {
25
+ console.warn(`[starfish] Payload approaching limit: estimated ${(estimatedBytes / 1024).toFixed(0)} KB ` +
26
+ `(warn threshold: ${(opts.warnBytes / 1024).toFixed(0)} KB).`);
27
+ }
28
+ }
29
+ return false;
30
+ }
5
31
  /**
6
32
  * Creates a debounced push helper that coalesces rapid mutations into a single sync.
7
33
  *
@@ -36,29 +62,58 @@ export function createDebouncedSync(store, options = {}) {
36
62
  timer = null;
37
63
  const current = store.getState().data;
38
64
  const doc = serialize ? serialize(current) : current;
39
- // Estimate encrypted payload size. AES-GCM output is similar to input size;
40
- // base64 encoding adds ~33% overhead, plus a small IV/tag overhead.
41
- const estimatedBytes = Math.ceil(JSON.stringify(doc).length * 1.34);
42
- if (estimatedBytes > maxBytes) {
43
- if (onSizeExceeded) {
44
- onSizeExceeded(estimatedBytes);
45
- }
46
- else {
47
- console.error(`[starfish] Push blocked: estimated payload ${(estimatedBytes / 1024).toFixed(0)} KB ` +
48
- `exceeds limit of ${(maxBytes / 1024).toFixed(0)} KB. Prune your data before syncing.`);
49
- }
65
+ if (checkPayloadSize(doc, { warnBytes, maxBytes, onSizeWarning, onSizeExceeded }))
66
+ return;
67
+ store.getState().set(() => doc);
68
+ }, delayMs);
69
+ }
70
+ return { notify, cancel };
71
+ }
72
+ /**
73
+ * Creates a debounced push helper that calls `syncManager.push()` directly,
74
+ * without requiring a Zustand store.
75
+ *
76
+ * Use this for one-way publishing workflows: public pages, derived snapshots,
77
+ * or any case where you want to push data without a full `createStarfishStore` setup.
78
+ *
79
+ * ```ts
80
+ * const syncManager = new SyncManager({ client, pullPath, pushPath })
81
+ *
82
+ * const { notify, cancel } = createDebouncedPush(syncManager, {
83
+ * serialize: () => buildPublicPageDocument(),
84
+ * })
85
+ *
86
+ * // Push after every relevant store mutation:
87
+ * planningStore.subscribe(() => notify())
88
+ *
89
+ * // Clean up on teardown:
90
+ * cancel()
91
+ * ```
92
+ */
93
+ export function createDebouncedPush(syncManager, options) {
94
+ const { delayMs = DEFAULT_DELAY_MS, warnBytes = DEFAULT_WARN_BYTES, maxBytes = DEFAULT_MAX_BYTES, serialize, onSizeWarning, onSizeExceeded, onError, } = options;
95
+ let timer = null;
96
+ function cancel() {
97
+ if (timer !== null) {
98
+ clearTimeout(timer);
99
+ timer = null;
100
+ }
101
+ }
102
+ function notify() {
103
+ cancel();
104
+ timer = setTimeout(() => {
105
+ timer = null;
106
+ const doc = serialize();
107
+ if (checkPayloadSize(doc, { warnBytes, maxBytes, onSizeWarning, onSizeExceeded }))
50
108
  return;
51
- }
52
- if (estimatedBytes > warnBytes) {
53
- if (onSizeWarning) {
54
- onSizeWarning(estimatedBytes);
109
+ syncManager.push(doc).catch((err) => {
110
+ if (onError) {
111
+ onError(err);
55
112
  }
56
113
  else {
57
- console.warn(`[starfish] Payload approaching limit: estimated ${(estimatedBytes / 1024).toFixed(0)} KB ` +
58
- `(warn threshold: ${(warnBytes / 1024).toFixed(0)} KB).`);
114
+ console.warn("[starfish] Push failed:", err);
59
115
  }
60
- }
61
- store.getState().set(() => doc);
116
+ });
62
117
  }, delayMs);
63
118
  }
64
119
  return { notify, cancel };
package/dist/index.d.ts CHANGED
@@ -34,7 +34,9 @@ export type { BackgroundSyncOptions } from "./background-sync.js";
34
34
  export { isServiceWorkerSupported, registerServiceWorker, unregisterServiceWorkers } from "./service-worker.js";
35
35
  export type { ServiceWorkerOptions } from "./service-worker.js";
36
36
  export { createSuspenseResource } from "./bindings/suspense.js";
37
- export { createDebouncedSync } from "./debounced-sync.js";
38
- export type { DebouncedSyncOptions, DebouncedSync } from "./debounced-sync.js";
37
+ export { createDebouncedSync, createDebouncedPush } from "./debounced-sync.js";
38
+ export type { DebouncedSyncOptions, DebouncedSync, DebouncedPushOptions, DebouncedPush } from "./debounced-sync.js";
39
+ export { createMobileLifecycle } from "./mobile-lifecycle.js";
40
+ export type { AppStateModule, NetInfoModule, MobileLifecycleDeps, MobileLifecycleOptions } from "./mobile-lifecycle.js";
39
41
  export { createMultiStoreSync } from "./multi-store.js";
40
42
  export type { StoreSlice, BackupDocument, MultiStoreMigrationFn, MultiStoreSyncOptions, MultiStoreSync, } from "./multi-store.js";
package/dist/index.js CHANGED
@@ -17,5 +17,6 @@ export { exportData, importData, exportToBlob } from "./export.js";
17
17
  export { isBackgroundSyncSupported, registerBackgroundSync } from "./background-sync.js";
18
18
  export { isServiceWorkerSupported, registerServiceWorker, unregisterServiceWorkers } from "./service-worker.js";
19
19
  export { createSuspenseResource } from "./bindings/suspense.js";
20
- export { createDebouncedSync } from "./debounced-sync.js";
20
+ export { createDebouncedSync, createDebouncedPush } from "./debounced-sync.js";
21
+ export { createMobileLifecycle } from "./mobile-lifecycle.js";
21
22
  export { createMultiStoreSync } from "./multi-store.js";
@@ -0,0 +1,71 @@
1
+ import type { StoreApi } from "zustand/vanilla";
2
+ import type { StarfishStore } from "./bindings/zustand.js";
3
+ /**
4
+ * Minimal interface matching React Native's `AppState` module.
5
+ * Pass `AppState` from `react-native` directly.
6
+ */
7
+ export interface AppStateModule {
8
+ addEventListener: (type: "change", listener: (state: string) => void) => {
9
+ remove: () => void;
10
+ };
11
+ }
12
+ /**
13
+ * Minimal interface matching `@react-native-community/netinfo`'s default export.
14
+ * Pass `NetInfo` from `@react-native-community/netinfo` directly.
15
+ */
16
+ export interface NetInfoModule {
17
+ addEventListener: (listener: (state: {
18
+ isConnected: boolean | null;
19
+ }) => void) => () => void;
20
+ }
21
+ export interface MobileLifecycleDeps {
22
+ /** React Native `AppState` module. */
23
+ appState: AppStateModule;
24
+ /**
25
+ * Optional: NetInfo module from `@react-native-community/netinfo`.
26
+ * When provided, connectivity changes are forwarded to `store.getState().setOnline()`.
27
+ */
28
+ netInfo?: NetInfoModule;
29
+ }
30
+ export interface MobileLifecycleOptions {
31
+ /**
32
+ * Pull remote changes when the app returns to the foreground.
33
+ * Only pulls if the store is online and not already syncing.
34
+ * Default: `true`.
35
+ */
36
+ pullOnForeground?: boolean;
37
+ /**
38
+ * Flush dirty data when the app transitions to the background.
39
+ * Only flushes if the store has unsaved changes.
40
+ * Default: `true`.
41
+ */
42
+ flushOnBackground?: boolean;
43
+ }
44
+ /**
45
+ * Wires React Native app lifecycle events to a Starfish store.
46
+ *
47
+ * - **Background**: flushes pending changes before the OS suspends the app.
48
+ * - **Foreground**: pulls remote changes when the user returns to the app.
49
+ * - **NetInfo**: forwards connectivity changes to `store.getState().setOnline()`.
50
+ *
51
+ * Uses dependency injection so no `react-native` or `netinfo` imports are needed
52
+ * in this package. Pass the modules directly:
53
+ *
54
+ * ```ts
55
+ * import { AppState } from "react-native"
56
+ * import NetInfo from "@react-native-community/netinfo"
57
+ * import { createMobileLifecycle } from "@drakkar.software/starfish-client"
58
+ *
59
+ * // Call once, after the store is created:
60
+ * const cleanup = createMobileLifecycle(
61
+ * store,
62
+ * { appState: AppState, netInfo: NetInfo },
63
+ * )
64
+ *
65
+ * // In a React component (e.g. root layout):
66
+ * useEffect(() => cleanup, [])
67
+ * ```
68
+ *
69
+ * @returns A cleanup function that removes all event listeners.
70
+ */
71
+ export declare function createMobileLifecycle(store: StoreApi<StarfishStore>, deps: MobileLifecycleDeps, options?: MobileLifecycleOptions): () => void;
@@ -0,0 +1,55 @@
1
+ // ── Implementation ────────────────────────────────────────────────────────────
2
+ /**
3
+ * Wires React Native app lifecycle events to a Starfish store.
4
+ *
5
+ * - **Background**: flushes pending changes before the OS suspends the app.
6
+ * - **Foreground**: pulls remote changes when the user returns to the app.
7
+ * - **NetInfo**: forwards connectivity changes to `store.getState().setOnline()`.
8
+ *
9
+ * Uses dependency injection so no `react-native` or `netinfo` imports are needed
10
+ * in this package. Pass the modules directly:
11
+ *
12
+ * ```ts
13
+ * import { AppState } from "react-native"
14
+ * import NetInfo from "@react-native-community/netinfo"
15
+ * import { createMobileLifecycle } from "@drakkar.software/starfish-client"
16
+ *
17
+ * // Call once, after the store is created:
18
+ * const cleanup = createMobileLifecycle(
19
+ * store,
20
+ * { appState: AppState, netInfo: NetInfo },
21
+ * )
22
+ *
23
+ * // In a React component (e.g. root layout):
24
+ * useEffect(() => cleanup, [])
25
+ * ```
26
+ *
27
+ * @returns A cleanup function that removes all event listeners.
28
+ */
29
+ export function createMobileLifecycle(store, deps, options = {}) {
30
+ const { pullOnForeground = true, flushOnBackground = true } = options;
31
+ const appSub = deps.appState.addEventListener("change", (appState) => {
32
+ if (appState === "background" && flushOnBackground) {
33
+ if (store.getState().dirty) {
34
+ store.getState().flush().catch(() => { });
35
+ }
36
+ }
37
+ else if (appState === "active" && pullOnForeground) {
38
+ const { online, syncing } = store.getState();
39
+ if (online && !syncing) {
40
+ store.getState().pull().catch(() => { });
41
+ }
42
+ }
43
+ // "inactive" (iOS transition) and other states are intentionally ignored
44
+ });
45
+ let netUnsub = null;
46
+ if (deps.netInfo) {
47
+ netUnsub = deps.netInfo.addEventListener(({ isConnected }) => {
48
+ store.getState().setOnline(!!isConnected);
49
+ });
50
+ }
51
+ return () => {
52
+ appSub.remove();
53
+ netUnsub?.();
54
+ };
55
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drakkar.software/starfish-client",
3
- "version": "1.6.0",
3
+ "version": "1.11.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/Drakkar-Software/starfish.git",
@@ -64,7 +64,7 @@
64
64
  }
65
65
  },
66
66
  "dependencies": {
67
- "@drakkar.software/starfish-protocol": "1.5.0"
67
+ "@drakkar.software/starfish-protocol": "1.11.0"
68
68
  },
69
69
  "devDependencies": {
70
70
  "@legendapp/state": "^2.0.0",
package/dist/hash.d.ts DELETED
@@ -1,10 +0,0 @@
1
- /**
2
- * Deterministic JSON serialization with sorted keys (recursive).
3
- * Must produce identical output to the server's stableStringify.
4
- */
5
- export declare function stableStringify(value: unknown): string;
6
- /**
7
- * Compute SHA-256 hex digest of the stable-stringified data.
8
- * Works in both browser (crypto.subtle) and Node.js environments.
9
- */
10
- export declare function computeHash(data: Record<string, unknown>): Promise<string>;
package/dist/hash.js DELETED
@@ -1,34 +0,0 @@
1
- import { getCrypto } from "./platform.js";
2
- /**
3
- * Deterministic JSON serialization with sorted keys (recursive).
4
- * Must produce identical output to the server's stableStringify.
5
- */
6
- export function stableStringify(value) {
7
- if (value === null || value === undefined)
8
- return "null";
9
- if (typeof value === "boolean" || typeof value === "number")
10
- return JSON.stringify(value);
11
- if (typeof value === "string")
12
- return JSON.stringify(value);
13
- if (Array.isArray(value)) {
14
- return "[" + value.map(v => stableStringify(v)).join(",") + "]";
15
- }
16
- if (typeof value === "object") {
17
- const obj = value;
18
- const keys = Object.keys(obj).sort();
19
- const pairs = keys.map(k => JSON.stringify(k) + ":" + stableStringify(obj[k]));
20
- return "{" + pairs.join(",") + "}";
21
- }
22
- return "null";
23
- }
24
- /**
25
- * Compute SHA-256 hex digest of the stable-stringified data.
26
- * Works in both browser (crypto.subtle) and Node.js environments.
27
- */
28
- export async function computeHash(data) {
29
- const encoded = new TextEncoder().encode(stableStringify(data));
30
- const buf = await getCrypto().subtle.digest("SHA-256", encoded);
31
- return Array.from(new Uint8Array(buf))
32
- .map(b => b.toString(16).padStart(2, "0"))
33
- .join("");
34
- }
@@ -1,52 +0,0 @@
1
- /**
2
- * Platform abstraction for crypto and base64 operations.
3
- *
4
- * Browser and Node.js >= 15 work with zero configuration (globalThis.crypto).
5
- * React Native users must call configurePlatform() before using the SDK.
6
- */
7
- /** Minimal crypto interface required by the SDK (subset of Web Crypto API). */
8
- export interface CryptoProvider {
9
- subtle: {
10
- digest(algorithm: string, data: BufferSource): Promise<ArrayBuffer>;
11
- importKey(format: "raw", keyData: BufferSource, algorithm: string | Algorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
12
- deriveKey(algorithm: HkdfParams, baseKey: CryptoKey, derivedKeyType: AesKeyGenParams, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
13
- encrypt(algorithm: AesGcmParams, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>;
14
- decrypt(algorithm: AesGcmParams, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>;
15
- };
16
- getRandomValues<T extends ArrayBufferView>(array: T): T;
17
- }
18
- /** Base64 encode/decode for Uint8Array <-> string. */
19
- export interface Base64Provider {
20
- encode(data: Uint8Array): string;
21
- decode(encoded: string): Uint8Array;
22
- }
23
- export interface PlatformConfig {
24
- crypto?: CryptoProvider;
25
- base64?: Base64Provider;
26
- }
27
- /**
28
- * Configure platform-specific providers for environments
29
- * that lack the Web Crypto API (e.g., React Native).
30
- *
31
- * Call once at app startup, before using any SDK functions.
32
- * Not needed for browser or Node.js >= 15.
33
- *
34
- * @example
35
- * ```ts
36
- * import { configurePlatform } from "@satellite/client"
37
- * import QuickCrypto from "react-native-quick-crypto"
38
- *
39
- * configurePlatform({
40
- * crypto: QuickCrypto,
41
- * base64: {
42
- * encode: (data) => Buffer.from(data).toString("base64"),
43
- * decode: (str) => new Uint8Array(Buffer.from(str, "base64")),
44
- * },
45
- * })
46
- * ```
47
- */
48
- export declare function configurePlatform(config: PlatformConfig): void;
49
- /** Resolve the active crypto provider. */
50
- export declare function getCrypto(): CryptoProvider;
51
- /** Resolve the active base64 provider. */
52
- export declare function getBase64(): Base64Provider;
package/dist/platform.js DELETED
@@ -1,62 +0,0 @@
1
- /**
2
- * Platform abstraction for crypto and base64 operations.
3
- *
4
- * Browser and Node.js >= 15 work with zero configuration (globalThis.crypto).
5
- * React Native users must call configurePlatform() before using the SDK.
6
- */
7
- let _crypto;
8
- let _base64;
9
- /**
10
- * Configure platform-specific providers for environments
11
- * that lack the Web Crypto API (e.g., React Native).
12
- *
13
- * Call once at app startup, before using any SDK functions.
14
- * Not needed for browser or Node.js >= 15.
15
- *
16
- * @example
17
- * ```ts
18
- * import { configurePlatform } from "@satellite/client"
19
- * import QuickCrypto from "react-native-quick-crypto"
20
- *
21
- * configurePlatform({
22
- * crypto: QuickCrypto,
23
- * base64: {
24
- * encode: (data) => Buffer.from(data).toString("base64"),
25
- * decode: (str) => new Uint8Array(Buffer.from(str, "base64")),
26
- * },
27
- * })
28
- * ```
29
- */
30
- export function configurePlatform(config) {
31
- if (config.crypto)
32
- _crypto = config.crypto;
33
- if (config.base64)
34
- _base64 = config.base64;
35
- }
36
- /** Resolve the active crypto provider. */
37
- export function getCrypto() {
38
- if (_crypto)
39
- return _crypto;
40
- if (typeof globalThis !== "undefined" && globalThis.crypto?.subtle) {
41
- return globalThis.crypto;
42
- }
43
- throw new Error("@satellite/client: No crypto provider available. " +
44
- "In React Native, call configurePlatform({ crypto: ... }) before using the SDK.");
45
- }
46
- /** Resolve the active base64 provider. */
47
- export function getBase64() {
48
- if (_base64)
49
- return _base64;
50
- if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
51
- return {
52
- encode(data) {
53
- return btoa(String.fromCharCode(...data));
54
- },
55
- decode(encoded) {
56
- return Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0));
57
- },
58
- };
59
- }
60
- throw new Error("@satellite/client: No base64 provider available. " +
61
- "In React Native, call configurePlatform({ base64: ... }) before using the SDK.");
62
- }