@drakkar.software/starfish-client 3.0.0-alpha.1 → 3.0.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -206,6 +206,33 @@ new SyncManager({
206
206
  - `signer.getSigner()` returns `{ devEdPubHex, sign(payload) }`. When set, every push attaches `authorPubkey = cap.sub` and `authorSignature = base64(Ed25519(payload))` over the encrypted payload (without the author fields).
207
207
  - `encryptor` is the only encryption option — the v2 single-secret `encryptionSecret`/`encryptionSalt` shorthand was removed in v3.
208
208
 
209
+ ## `AppendLogCursor`
210
+
211
+ Incremental, stateful cursor over an append-only collection — the log counterpart to `SyncManager`. It owns the accumulated array and pulls only what's new; the checkpoint is **derived from the last element it holds**, so it resumes from persisted data on a fresh page.
212
+
213
+ ```ts
214
+ const log = new AppendLogCursor({
215
+ client, pullPath: "/pull/events",
216
+ appendField, // default "items"
217
+ initialItems, // warm-start seed (raw {ts,data} envelopes) — or pass `since`
218
+ encryptor, // optional: decrypt each element's data (ts/author preserved)
219
+ verifyAuthor, // optional: true | { expectedAuthorPubkey?, alg? }
220
+ onElementError, // optional: "throw" (default) | "skip" — see below
221
+ persistEncrypted, // optional: keep ciphertext for E2EE-safe persistence — see below
222
+ })
223
+ const fresh = await log.pull() // only elements newer than the last held (safe to call concurrently)
224
+ log.getItems() // full accumulated log (ciphertext under persistEncrypted)
225
+ await log.getDecryptedItems() // full log decrypted — render warm-started history
226
+ log.getCheckpoint() // max ts held — persist, and restore via setCheckpoint()
227
+ ```
228
+
229
+ - Cold start (no seed) → first `pull()` fetches the whole collection; warm start (seeded) → resumes incrementally.
230
+ - `verifyAuthor` verifies each element's author signature over the stored (pre-decryption) data and throws `AppendAuthorError` atomically on any failure (nothing is appended, checkpoint unchanged).
231
+ - `onElementError: "skip"` drops an element that fails verify/decrypt **and advances the checkpoint past it** (never re-fetched), so one unreadable element in a multi-writer / E2EE log can't blank the whole log. Default `"throw"` keeps the atomic behavior. SECURITY: `"skip"` also drops author-verification failures silently — combine with `verifyAuthor.expectedAuthorPubkey` or a post-pull `authorPubkey` check for strict authorship.
232
+ - `persistEncrypted: true` (with an `encryptor`) stores each element's **ciphertext** so `getItems()` is safe to persist at rest for an E2EE log; `pull()` still returns decrypted, and `getDecryptedItems()` decrypts the full held log for warm-start rendering.
233
+ - `pull()` is safe to call concurrently — overlapping calls serialize internally so they never double-append a window.
234
+ - **Reactive bindings:** `createStarfishLog` (Zustand, `./zustand`) + hooks `useStarfishLog` / `useStarfishLogItems` / `useLogStatus` / `useLogConnectivity`; `createStarfishLogObservable` (Legend, `./legend`); `createAppendLogMobileLifecycle` (pull on app foreground). `startPolling` and `createSuspenseResource` work with `cursor.pull()` directly.
235
+
209
236
  ## Other utilities
210
237
 
211
238
  The package also re-exports the v2 ergonomics that survived intact: `consoleSyncLogger`, `noopSyncLogger`, `createMetricsCollector`, `createMigrator`, `createSchemaValidator`, `classifyError`, conflict resolvers (`createUnionMerge`, `createSoftDeleteResolver`, `timestampWinner`, `pruneTombstones`), `SnapshotHistory`, `startPolling`/`startAdaptivePolling`, `createDedupFetch`, `fetchServerConfig`, `pullEntitlements`, `createIndexedDBStorage`, `exportData`/`importData`, `createDebouncedSync`/`createDebouncedPush`, `createMultiStoreSync`, `createMobileLifecycle`, and the Zustand/Legend bindings via the `./zustand` and `./legend` subpaths.
@@ -0,0 +1,230 @@
1
+ import { type Alg, type Encryptor } from "@drakkar.software/starfish-protocol";
2
+ import type { StarfishClient } from "./client.js";
3
+ import type { SyncLogger } from "./logger.js";
4
+ /**
5
+ * A single stored element of an append-only collection, exactly as returned by
6
+ * `client.pull(path, { appendField })`. `ts` is the server-assigned, strictly
7
+ * increasing element timestamp; `data` is the payload (plaintext under the
8
+ * `"none"` encryption mode, the opaque encryptor wrapper under `"delegated"`).
9
+ *
10
+ * When an {@link AppendLogCursor} is given an `encryptor`, the elements it
11
+ * stores and returns carry the **decrypted** `data` while preserving `ts` and
12
+ * the author fields — so the shape is uniform and re-seedable. The exception is
13
+ * `persistEncrypted` mode (see {@link AppendLogCursorOptions.persistEncrypted}),
14
+ * where the stored elements keep their **ciphertext** `data` (E2EE-safe to
15
+ * persist) and decryption happens only on read via {@link AppendLogCursor.pull}
16
+ * and {@link AppendLogCursor.getDecryptedItems}.
17
+ */
18
+ export interface AppendElement {
19
+ ts: number;
20
+ data: Record<string, unknown>;
21
+ authorPubkey?: string;
22
+ authorSignature?: string;
23
+ }
24
+ /** Per-element author-signature verification policy for {@link AppendLogCursor}. */
25
+ export interface AuthorVerifier {
26
+ /** If set, every element's `authorPubkey` MUST equal this key (compared as
27
+ * case-insensitive hex), else the pull fails. Omit to accept any signing key
28
+ * (verify only that the signature is valid for the element's self-declared
29
+ * `authorPubkey` — see the `verifyAuthor` note on restricting authors). */
30
+ expectedAuthorPubkey?: string;
31
+ /** Signing suite the signatures were produced under. Defaults to `DEFAULT_ALG`. */
32
+ alg?: Alg;
33
+ }
34
+ /**
35
+ * What to do when a single element fails verification or decryption during a
36
+ * {@link AppendLogCursor.pull} (or {@link AppendLogCursor.getDecryptedItems}).
37
+ *
38
+ * - `"throw"` (default): the pull is **atomic** — the first bad element throws
39
+ * and NO state is mutated, so the checkpoint never advances past an element
40
+ * that could not be re-fetched. Use when every element must be readable.
41
+ * - `"skip"`: a bad element is dropped from the returned/decrypted batch and the
42
+ * checkpoint still **advances past it** (so it is never re-fetched), letting one
43
+ * poison element fail without blanking the whole log. Intended for tolerating
44
+ * **decrypt** failures in a multi-writer / E2EE log (keyring skew, a foreign or
45
+ * corrupt element). SECURITY NOTE: `"skip"` ALSO silently drops elements that
46
+ * fail *author* verification rather than failing loudly — so if you also need
47
+ * strict authorship, set `verifyAuthor.expectedAuthorPubkey` (single author) or
48
+ * check each element's `authorPubkey` against your authorized set after pull.
49
+ */
50
+ export type ElementErrorPolicy = "throw" | "skip";
51
+ export interface AppendLogCursorOptions {
52
+ client: StarfishClient;
53
+ /** Pull endpoint path, e.g. `"/pull/events"`. */
54
+ pullPath: string;
55
+ /** Array field name in the pulled document. Defaults to `"items"`. */
56
+ appendField?: string;
57
+ /**
58
+ * Warm-start seed: raw envelopes the caller persisted last session. The
59
+ * cursor adopts them verbatim and derives its initial checkpoint from their
60
+ * max `ts`. Under the default mode they are taken as already-decrypted (and
61
+ * never re-decrypted/re-verified); under `persistEncrypted` they are the
62
+ * persisted **ciphertext** and are decrypted on read (see `persistEncrypted`).
63
+ */
64
+ initialItems?: AppendElement[];
65
+ /**
66
+ * Explicit checkpoint-only seed (ms). Resume incrementally without
67
+ * rehydrating history. When given together with `initialItems`, it must be
68
+ * `>= max(ts of initialItems)` (a lower value would re-fetch held items).
69
+ */
70
+ since?: number;
71
+ /**
72
+ * When set, each freshly-pulled element's `.data` is decrypted via this
73
+ * encryptor (the `ts`/author fields are preserved). Author verification, when
74
+ * enabled, runs over the original (pre-decryption) `data`.
75
+ *
76
+ * Caveat (default mode): a returned / `getItems()` element then holds DECRYPTED
77
+ * `data` but an `authorSignature` computed over the stored CIPHERTEXT — they no
78
+ * longer match, so do NOT re-verify a decrypted element with `verifyAppendAuthor`.
79
+ * The cursor already verified it (over the ciphertext) at pull time when
80
+ * `verifyAuthor` is on; `authorPubkey` is retained for identity. (Under
81
+ * `persistEncrypted` the stored elements keep their ciphertext, so this caveat
82
+ * does not apply to `getItems()`.)
83
+ */
84
+ encryptor?: Encryptor;
85
+ /**
86
+ * Per-element failure policy for verification/decryption. Defaults to
87
+ * `"throw"` (atomic pull — preserves the pre-existing behavior). See
88
+ * {@link ElementErrorPolicy}.
89
+ */
90
+ onElementError?: ElementErrorPolicy;
91
+ /**
92
+ * Keep the **ciphertext** form of each element in the cursor's accumulated log
93
+ * instead of the decrypted form (requires `encryptor`; a no-op without one,
94
+ * since plaintext is already its own stored form). This makes
95
+ * {@link AppendLogCursor.getItems} return the persistable ciphertext — safe to
96
+ * write to disk for an end-to-end-encrypted log without leaking plaintext at
97
+ * rest — while {@link AppendLogCursor.pull} still returns the freshly-decrypted
98
+ * batch and {@link AppendLogCursor.getDecryptedItems} returns the full log
99
+ * decrypted (for warm-start rendering). Defaults to `false` (store decrypted).
100
+ */
101
+ persistEncrypted?: boolean;
102
+ /**
103
+ * `true` to verify every element's author signature, or a policy object.
104
+ *
105
+ * This verifies the signature is valid for the element's self-declared
106
+ * `authorPubkey` — it does NOT by itself restrict WHICH authors are accepted.
107
+ * To restrict authorship, set `expectedAuthorPubkey` (single author), or check
108
+ * each `el.authorPubkey` against your own authorization source (keyring /
109
+ * member list / cap allow-list) after pull — for a multi-writer log, the
110
+ * authorized set lives there and changes over time, not here.
111
+ *
112
+ * The signature covers `data` + the document key, but NOT `ts`: a malicious
113
+ * server cannot forge content, but can reorder or re-timestamp authentic
114
+ * elements, so trust `ts` only as far as you trust the server.
115
+ */
116
+ verifyAuthor?: boolean | AuthorVerifier;
117
+ /** Structured logger for pull events. */
118
+ logger?: SyncLogger;
119
+ /** Name passed to logger methods (default: derived from `pullPath`). */
120
+ loggerName?: string;
121
+ }
122
+ /** Thrown when an append element's author signature fails verification. */
123
+ export declare class AppendAuthorError extends Error {
124
+ readonly ts: number;
125
+ constructor(ts: number);
126
+ }
127
+ /** Largest `ts` among `items`, or `0` when empty. The checkpoint for an
128
+ * append-only log is exactly this — the server returns elements with
129
+ * `ts > checkpoint`, and element timestamps are strictly increasing. */
130
+ export declare function checkpointOf(items: readonly {
131
+ ts: number;
132
+ }[]): number;
133
+ /**
134
+ * A stateful cursor over an append-only collection. It owns the accumulated
135
+ * array of elements and pulls only what is new: each {@link pull} derives the
136
+ * checkpoint from the last element it holds and asks the server for elements
137
+ * with a greater `ts`.
138
+ *
139
+ * This is the incremental, stateful counterpart to the deliberately stateless
140
+ * `client.pull(path, { appendField, since })`, and the sibling of
141
+ * {@link SyncManager} for append-only logs (no merge / push-conflict
142
+ * machinery — a log only grows).
143
+ *
144
+ * The cursor accumulates every pulled element in memory; for an unboundedly
145
+ * large log, pull a bounded window with raw `client.pull(path, { last })` instead.
146
+ *
147
+ * Cold start (nothing persisted) — first `pull()` fetches the whole collection:
148
+ * ```ts
149
+ * const log = new AppendLogCursor({ client, pullPath: "/pull/events" })
150
+ * const all = await log.pull()
151
+ * ```
152
+ * Warm start (resume from persisted data) — first `pull()` fetches only newer
153
+ * elements; persistence is a round-trip of `getItems()`:
154
+ * ```ts
155
+ * const log = new AppendLogCursor({ client, pullPath: "/pull/events",
156
+ * initialItems: await store.load() })
157
+ * const fresh = await log.pull()
158
+ * await store.save(log.getItems())
159
+ * ```
160
+ * Warm start for an **E2EE** log — persist ciphertext, render decrypted:
161
+ * ```ts
162
+ * const log = new AppendLogCursor({ client, pullPath: "/pull/streamchat",
163
+ * encryptor, persistEncrypted: true, onElementError: "skip",
164
+ * initialItems: await store.load() }) // ciphertext from disk
165
+ * const history = await log.getDecryptedItems() // render persisted history
166
+ * const fresh = await log.pull() // decrypted delta
167
+ * await store.save(log.getItems()) // ciphertext back to disk
168
+ * ```
169
+ */
170
+ export declare class AppendLogCursor {
171
+ private readonly client;
172
+ private readonly pullPath;
173
+ private readonly appendField;
174
+ private readonly encryptor?;
175
+ private readonly verifyAuthor?;
176
+ private readonly onElementError;
177
+ private readonly persistEncrypted;
178
+ private readonly documentKey;
179
+ private readonly logger?;
180
+ private readonly loggerName;
181
+ private readonly items;
182
+ private lastCheckpoint;
183
+ /** Tail of the serialized pull chain. Concurrent `pull()` calls queue behind
184
+ * it so each runs against the checkpoint the previous one advanced — no two
185
+ * overlapping fetches read the same checkpoint and double-append a window. */
186
+ private pullChain;
187
+ constructor(options: AppendLogCursorOptions);
188
+ /**
189
+ * Fetch elements newer than the current checkpoint, verify + decrypt them,
190
+ * append them to the local log, and return ONLY the newly-fetched batch
191
+ * (decrypted when an `encryptor` is set).
192
+ *
193
+ * Atomic under `onElementError: "throw"` (the default): the batch is fully
194
+ * verified and decrypted into a local before any state mutation, so a
195
+ * verify/decrypt failure throws without advancing the checkpoint past elements
196
+ * that could never be re-fetched. Under `"skip"`, a failing element is dropped
197
+ * from the returned batch but the checkpoint still advances past it.
198
+ *
199
+ * Safe to call concurrently: overlapping calls are serialized internally, so
200
+ * each runs against the checkpoint the previous one advanced (no double-fetch
201
+ * of the same window). The next pull after one completes will pick up anything
202
+ * that arrived in between.
203
+ */
204
+ pull(): Promise<AppendElement[]>;
205
+ private doPull;
206
+ /** Verify a single element's author signature over its RAW (pre-decryption)
207
+ * `data`. Throws {@link AppendAuthorError} on any failure. No-op when
208
+ * verification is disabled. */
209
+ private verifyOne;
210
+ /** The full accumulated log (a shallow copy), in `ts` order. Under
211
+ * `persistEncrypted` these carry CIPHERTEXT `data` (persist them as-is, then
212
+ * re-seed via `initialItems`); otherwise they carry decrypted/plaintext data. */
213
+ getItems(): AppendElement[];
214
+ /**
215
+ * The full accumulated log, DECRYPTED — for rendering warm-started history in
216
+ * `persistEncrypted` mode (where {@link getItems} holds ciphertext). Honors
217
+ * `onElementError` (a `"skip"` cursor drops elements it cannot read). When the
218
+ * cursor has no `encryptor`, or is not in `persistEncrypted` mode, the held
219
+ * elements are already plaintext/decrypted and are returned as-is.
220
+ */
221
+ getDecryptedItems(): Promise<AppendElement[]>;
222
+ /** The current checkpoint: the max `ts` held (the next pull's `since`). `0`
223
+ * when nothing has been pulled or seeded. */
224
+ getCheckpoint(): number;
225
+ /** Restore the checkpoint without seeding items — for persistence layers that
226
+ * store only the checkpoint. Used to resume incrementally across restarts.
227
+ * Rejects a value below the max `ts` already held: rewinding would make the
228
+ * next pull re-deliver, and duplicate, elements the cursor already has. */
229
+ setCheckpoint(ts: number): void;
230
+ }
@@ -1,5 +1,6 @@
1
1
  import type { Observable } from "@legendapp/state";
2
2
  import type { SyncManager } from "../sync.js";
3
+ import type { AppendLogCursor, AppendElement } from "../append-log.js";
3
4
  export interface StarfishLegendState {
4
5
  data: Record<string, unknown>;
5
6
  syncing: boolean;
@@ -23,3 +24,25 @@ export interface CreateStarfishObservableOptions {
23
24
  produce?: <T>(base: T, recipe: (draft: T) => T | void) => T;
24
25
  }
25
26
  export declare function createStarfishObservable(options: CreateStarfishObservableOptions): StarfishLegendStore;
27
+ export interface StarfishLogObservableState {
28
+ /** The full accumulated log, newest appended last. */
29
+ items: AppendElement[];
30
+ /** A `pull()` is in flight. */
31
+ loading: boolean;
32
+ online: boolean;
33
+ error: string | null;
34
+ /** The cursor's checkpoint (max `ts` held). */
35
+ checkpoint: number;
36
+ }
37
+ export interface StarfishLogObservableStore {
38
+ /** The observable state tree — read fields with `.get()` inside `observer` components. */
39
+ state: Observable<StarfishLogObservableState>;
40
+ /** Pull elements newer than the checkpoint, append them, return the new batch.
41
+ * Errors are captured into `state.error`. */
42
+ pull: () => Promise<AppendElement[]>;
43
+ setOnline: (online: boolean) => void;
44
+ }
45
+ export interface CreateStarfishLogObservableOptions {
46
+ cursor: AppendLogCursor;
47
+ }
48
+ export declare function createStarfishLogObservable(options: CreateStarfishLogObservableOptions): StarfishLogObservableStore;
@@ -57,7 +57,39 @@ function createStarfishObservable(options) {
57
57
  };
58
58
  return { state, pull, set, flush, setOnline };
59
59
  }
60
+ function createStarfishLogObservable(options) {
61
+ const { cursor } = options;
62
+ const state = observable({
63
+ // Seed from the cursor so a warm-started cursor's items show immediately.
64
+ items: cursor.getItems(),
65
+ loading: false,
66
+ online: true,
67
+ error: null,
68
+ checkpoint: cursor.getCheckpoint()
69
+ });
70
+ const pull = async () => {
71
+ if (state.loading.get()) return [];
72
+ state.loading.set(true);
73
+ state.error.set(null);
74
+ try {
75
+ const batch = await cursor.pull();
76
+ state.items.set(cursor.getItems());
77
+ state.checkpoint.set(cursor.getCheckpoint());
78
+ return batch;
79
+ } catch (err) {
80
+ state.error.set(err instanceof Error ? err.message : String(err));
81
+ return [];
82
+ } finally {
83
+ state.loading.set(false);
84
+ }
85
+ };
86
+ const setOnline = (online) => {
87
+ state.online.set(online);
88
+ };
89
+ return { state, pull, setOnline };
90
+ }
60
91
  export {
92
+ createStarfishLogObservable,
61
93
  createStarfishObservable
62
94
  };
63
95
  //# sourceMappingURL=legend.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/bindings/legend.ts"],
4
- "sourcesContent": ["import { observable } from \"@legendapp/state\"\nimport type { Observable } from \"@legendapp/state\"\nimport type { SyncManager } from \"../sync.js\"\n\nexport interface StarfishLegendState {\n data: Record<string, unknown>\n syncing: boolean\n online: boolean\n dirty: boolean\n error: string | null\n}\n\nexport interface StarfishLegendStore {\n /** The observable state tree \u2014 read fields with `.get()` inside `observer` components. */\n state: Observable<StarfishLegendState>\n pull: () => Promise<void>\n set: (modifier: (current: Record<string, unknown>) => Record<string, unknown>) => void\n flush: () => Promise<void>\n setOnline: (online: boolean) => void\n}\n\nexport interface CreateStarfishObservableOptions {\n /** Unique name for this collection (used for persistence keys when applicable). */\n name: string\n syncManager: SyncManager\n /** Pass `produce` from `immer` to enable draft-based mutations in `set()`. */\n produce?: <T>(base: T, recipe: (draft: T) => T | void) => T\n}\n\nexport function createStarfishObservable(\n options: CreateStarfishObservableOptions,\n): StarfishLegendStore {\n const state = observable<StarfishLegendState>({\n data: {},\n syncing: false,\n online: true,\n dirty: false,\n error: null,\n })\n\n const flush = async (): Promise<void> => {\n if (state.syncing.get() || !state.dirty.get()) return\n state.syncing.set(true)\n state.error.set(null)\n try {\n await options.syncManager.push(state.data.get())\n state.data.set(options.syncManager.getData())\n state.dirty.set(false)\n } catch (err) {\n state.error.set(err instanceof Error ? err.message : String(err))\n } finally {\n state.syncing.set(false)\n }\n }\n\n const pull = async (): Promise<void> => {\n state.syncing.set(true)\n state.error.set(null)\n try {\n await options.syncManager.pull()\n state.data.set(options.syncManager.getData())\n } catch (err) {\n state.error.set(err instanceof Error ? err.message : String(err))\n } finally {\n state.syncing.set(false)\n }\n }\n\n const set = (\n modifier: (current: Record<string, unknown>) => Record<string, unknown>,\n ): void => {\n try {\n const current = state.data.get()\n const next = options.produce\n ? options.produce(\n current,\n modifier as (draft: Record<string, unknown>) => Record<string, unknown> | void,\n )\n : modifier(current)\n state.data.set(next)\n state.dirty.set(true)\n state.error.set(null)\n if (state.online.get()) flush().catch(() => {})\n } catch (err) {\n state.error.set(err instanceof Error ? err.message : String(err))\n }\n }\n\n const setOnline = (online: boolean): void => {\n state.online.set(online)\n if (online && state.dirty.get()) flush().catch(() => {})\n }\n\n return { state, pull, set, flush, setOnline }\n}\n"],
5
- "mappings": ";AAAA,SAAS,kBAAkB;AA6BpB,SAAS,yBACd,SACqB;AACrB,QAAM,QAAQ,WAAgC;AAAA,IAC5C,MAAM,CAAC;AAAA,IACP,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,OAAO;AAAA,EACT,CAAC;AAED,QAAM,QAAQ,YAA2B;AACvC,QAAI,MAAM,QAAQ,IAAI,KAAK,CAAC,MAAM,MAAM,IAAI,EAAG;AAC/C,UAAM,QAAQ,IAAI,IAAI;AACtB,UAAM,MAAM,IAAI,IAAI;AACpB,QAAI;AACF,YAAM,QAAQ,YAAY,KAAK,MAAM,KAAK,IAAI,CAAC;AAC/C,YAAM,KAAK,IAAI,QAAQ,YAAY,QAAQ,CAAC;AAC5C,YAAM,MAAM,IAAI,KAAK;AAAA,IACvB,SAAS,KAAK;AACZ,YAAM,MAAM,IAAI,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,IAClE,UAAE;AACA,YAAM,QAAQ,IAAI,KAAK;AAAA,IACzB;AAAA,EACF;AAEA,QAAM,OAAO,YAA2B;AACtC,UAAM,QAAQ,IAAI,IAAI;AACtB,UAAM,MAAM,IAAI,IAAI;AACpB,QAAI;AACF,YAAM,QAAQ,YAAY,KAAK;AAC/B,YAAM,KAAK,IAAI,QAAQ,YAAY,QAAQ,CAAC;AAAA,IAC9C,SAAS,KAAK;AACZ,YAAM,MAAM,IAAI,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,IAClE,UAAE;AACA,YAAM,QAAQ,IAAI,KAAK;AAAA,IACzB;AAAA,EACF;AAEA,QAAM,MAAM,CACV,aACS;AACT,QAAI;AACF,YAAM,UAAU,MAAM,KAAK,IAAI;AAC/B,YAAM,OAAO,QAAQ,UACjB,QAAQ;AAAA,QACN;AAAA,QACA;AAAA,MACF,IACA,SAAS,OAAO;AACpB,YAAM,KAAK,IAAI,IAAI;AACnB,YAAM,MAAM,IAAI,IAAI;AACpB,YAAM,MAAM,IAAI,IAAI;AACpB,UAAI,MAAM,OAAO,IAAI,EAAG,OAAM,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAAA,IAChD,SAAS,KAAK;AACZ,YAAM,MAAM,IAAI,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,IAClE;AAAA,EACF;AAEA,QAAM,YAAY,CAAC,WAA0B;AAC3C,UAAM,OAAO,IAAI,MAAM;AACvB,QAAI,UAAU,MAAM,MAAM,IAAI,EAAG,OAAM,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAAA,EACzD;AAEA,SAAO,EAAE,OAAO,MAAM,KAAK,OAAO,UAAU;AAC9C;",
4
+ "sourcesContent": ["import { observable } from \"@legendapp/state\"\nimport type { Observable } from \"@legendapp/state\"\nimport type { SyncManager } from \"../sync.js\"\nimport type { AppendLogCursor, AppendElement } from \"../append-log.js\"\n\nexport interface StarfishLegendState {\n data: Record<string, unknown>\n syncing: boolean\n online: boolean\n dirty: boolean\n error: string | null\n}\n\nexport interface StarfishLegendStore {\n /** The observable state tree \u2014 read fields with `.get()` inside `observer` components. */\n state: Observable<StarfishLegendState>\n pull: () => Promise<void>\n set: (modifier: (current: Record<string, unknown>) => Record<string, unknown>) => void\n flush: () => Promise<void>\n setOnline: (online: boolean) => void\n}\n\nexport interface CreateStarfishObservableOptions {\n /** Unique name for this collection (used for persistence keys when applicable). */\n name: string\n syncManager: SyncManager\n /** Pass `produce` from `immer` to enable draft-based mutations in `set()`. */\n produce?: <T>(base: T, recipe: (draft: T) => T | void) => T\n}\n\nexport function createStarfishObservable(\n options: CreateStarfishObservableOptions,\n): StarfishLegendStore {\n const state = observable<StarfishLegendState>({\n data: {},\n syncing: false,\n online: true,\n dirty: false,\n error: null,\n })\n\n const flush = async (): Promise<void> => {\n if (state.syncing.get() || !state.dirty.get()) return\n state.syncing.set(true)\n state.error.set(null)\n try {\n await options.syncManager.push(state.data.get())\n state.data.set(options.syncManager.getData())\n state.dirty.set(false)\n } catch (err) {\n state.error.set(err instanceof Error ? err.message : String(err))\n } finally {\n state.syncing.set(false)\n }\n }\n\n const pull = async (): Promise<void> => {\n state.syncing.set(true)\n state.error.set(null)\n try {\n await options.syncManager.pull()\n state.data.set(options.syncManager.getData())\n } catch (err) {\n state.error.set(err instanceof Error ? err.message : String(err))\n } finally {\n state.syncing.set(false)\n }\n }\n\n const set = (\n modifier: (current: Record<string, unknown>) => Record<string, unknown>,\n ): void => {\n try {\n const current = state.data.get()\n const next = options.produce\n ? options.produce(\n current,\n modifier as (draft: Record<string, unknown>) => Record<string, unknown> | void,\n )\n : modifier(current)\n state.data.set(next)\n state.dirty.set(true)\n state.error.set(null)\n if (state.online.get()) flush().catch(() => {})\n } catch (err) {\n state.error.set(err instanceof Error ? err.message : String(err))\n }\n }\n\n const setOnline = (online: boolean): void => {\n state.online.set(online)\n if (online && state.dirty.get()) flush().catch(() => {})\n }\n\n return { state, pull, set, flush, setOnline }\n}\n\n// \u2500\u2500 Append-only log binding \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// The reactive counterpart for an append-only collection, backed by an\n// `AppendLogCursor`. Read-only (a log only grows): no `set`/`flush`/`dirty`.\n// The cursor owns the items + checkpoint; persist via `getItems()` and\n// rehydrate by constructing the cursor with `initialItems`.\n//\n// The store assumes it is the SOLE driver of its cursor (it seeds from\n// `cursor.getItems()` at construction and updates only via its own `pull()`);\n// don't also call `cursor.pull()` directly, or the observable will go stale.\n\nexport interface StarfishLogObservableState {\n /** The full accumulated log, newest appended last. */\n items: AppendElement[]\n /** A `pull()` is in flight. */\n loading: boolean\n online: boolean\n error: string | null\n /** The cursor's checkpoint (max `ts` held). */\n checkpoint: number\n}\n\nexport interface StarfishLogObservableStore {\n /** The observable state tree \u2014 read fields with `.get()` inside `observer` components. */\n state: Observable<StarfishLogObservableState>\n /** Pull elements newer than the checkpoint, append them, return the new batch.\n * Errors are captured into `state.error`. */\n pull: () => Promise<AppendElement[]>\n setOnline: (online: boolean) => void\n}\n\nexport interface CreateStarfishLogObservableOptions {\n cursor: AppendLogCursor\n}\n\nexport function createStarfishLogObservable(\n options: CreateStarfishLogObservableOptions,\n): StarfishLogObservableStore {\n const { cursor } = options\n const state = observable<StarfishLogObservableState>({\n // Seed from the cursor so a warm-started cursor's items show immediately.\n items: cursor.getItems(),\n loading: false,\n online: true,\n error: null,\n checkpoint: cursor.getCheckpoint(),\n })\n\n const pull = async (): Promise<AppendElement[]> => {\n if (state.loading.get()) return []\n state.loading.set(true)\n state.error.set(null)\n try {\n const batch = await cursor.pull()\n state.items.set(cursor.getItems())\n state.checkpoint.set(cursor.getCheckpoint())\n return batch\n } catch (err) {\n state.error.set(err instanceof Error ? err.message : String(err))\n return []\n } finally {\n state.loading.set(false)\n }\n }\n\n const setOnline = (online: boolean): void => {\n state.online.set(online)\n }\n\n return { state, pull, setOnline }\n}\n"],
5
+ "mappings": "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",
6
6
  "names": []
7
7
  }
@@ -3,6 +3,7 @@ import { type StateStorage } from "zustand/middleware";
3
3
  import type { DevtoolsOptions } from "zustand/middleware";
4
4
  import type { Encryptor } from "@drakkar.software/starfish-protocol";
5
5
  import { SyncManager } from "../sync.js";
6
+ import { AppendLogCursor, type AppendElement } from "../append-log.js";
6
7
  import type { StarfishCapProvider, ConflictResolver } from "../types.js";
7
8
  import type { SyncLogger } from "../logger.js";
8
9
  import type { Validator } from "../validate.js";
@@ -104,6 +105,13 @@ export declare function useConnectivity(store: StoreApi<StarfishStore>): void;
104
105
  export declare function useLastSynced(store: StoreApi<StarfishStore>): string;
105
106
  export interface SyncInitConfig {
106
107
  serverUrl: string;
108
+ /**
109
+ * Optional server namespace, forwarded to the underlying {@link StarfishClient}
110
+ * so `pullPath`/`pushPath` are rewritten to `/v1/<namespace>/…` (signed AND sent).
111
+ * Leave unset for a root-mounted server. Pass the bare name (e.g. `"octochat"`),
112
+ * not `/v1/octochat` — the `/v1/` is added by the client.
113
+ */
114
+ namespace?: string;
107
115
  capProvider?: StarfishCapProvider;
108
116
  pullPath: string;
109
117
  pushPath: string;
@@ -128,3 +136,40 @@ export interface SyncInitConfig {
128
136
  * Pass `null` to disable sync (returns `null`).
129
137
  */
130
138
  export declare function useSyncInit(config: SyncInitConfig | null): StoreApi<StarfishStore> | null;
139
+ export interface StarfishLogState {
140
+ /** The full accumulated log, newest appended last. */
141
+ items: AppendElement[];
142
+ /** A `pull()` is in flight. */
143
+ loading: boolean;
144
+ online: boolean;
145
+ error: string | null;
146
+ /** The cursor's checkpoint (max `ts` held). */
147
+ checkpoint: number;
148
+ }
149
+ export interface StarfishLogActions {
150
+ /** Pull elements newer than the checkpoint, append them, and return the new
151
+ * batch. Errors are captured into `error` (mirroring the SyncManager store). */
152
+ pull: () => Promise<AppendElement[]>;
153
+ setOnline: (online: boolean) => void;
154
+ }
155
+ export type StarfishLogStore = StarfishLogState & StarfishLogActions;
156
+ export interface CreateStarfishLogOptions {
157
+ cursor: AppendLogCursor;
158
+ devtools?: (storeCreator: any) => any;
159
+ }
160
+ export declare function createStarfishLog(options: CreateStarfishLogOptions): StoreApi<StarfishLogStore>;
161
+ /** Derived status for an append-log store. */
162
+ export type LogStatus = "idle" | "loading" | "error" | "offline";
163
+ /** Derive a single status from log store state. */
164
+ export declare function deriveLogStatus(state: StarfishLogState): LogStatus;
165
+ /** Use the full append-log store state and actions. */
166
+ export declare function useStarfishLog(store: StoreApi<StarfishLogStore>): StarfishLogStore;
167
+ /** Use only the accumulated items, with an optional selector for fine-grained subscriptions. */
168
+ export declare function useStarfishLogItems<T = AppendElement[]>(store: StoreApi<StarfishLogStore>, selector?: (items: AppendElement[]) => T): T;
169
+ /** Use the derived log status (idle | loading | error | offline). */
170
+ export declare function useLogStatus(store: StoreApi<StarfishLogStore>): LogStatus;
171
+ /** Subscribe to log status changes outside of React. Invoked immediately with the
172
+ * current status, then on every change. Returns an unsubscribe function. */
173
+ export declare function subscribeLogStatus(store: StoreApi<StarfishLogStore>, callback: (status: LogStatus) => void): () => void;
174
+ /** Binds browser online/offline events to the log store's setOnline action. Cleans up on unmount. */
175
+ export declare function useLogConnectivity(store: StoreApi<StarfishLogStore>): void;