@tallyui/database 1.0.0 → 2.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Paul Kilmurray and TallyUI contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,60 @@
1
- import { RxDatabase, RxCollection, RxStorage } from 'rxdb';
2
- import { TallyConnector, ReplicationAdapter, SyncContext } from '@tallyui/core';
1
+ import { RxStorage, RxDatabase, RxCollection, RxJsonSchema, MigrationStrategies } from 'rxdb';
2
+ import { Observable } from 'rxjs';
3
+ import { TallyConnector, ReplicationAdapter, SyncContext, StockReconcileAdapter, IdReconcileAdapter, FingerprintReconcileAdapter } from '@tallyui/core';
4
+ export { STOCK_LEVELS_LAST_PASS } from '@tallyui/core';
3
5
  import { RxReplicationState } from 'rxdb/plugins/replication';
4
6
 
7
+ /** WCPOS's value (ADR-061): a write pending longer than this is flagged as stalled, never failed. */
8
+ declare const STORAGE_WRITE_STALL_MS = 10000;
9
+ /** WCPOS's value (ADR-061): two consecutive silent read windows of this length mean the worker is dead. */
10
+ declare const STORAGE_READ_WATCHDOG_MS = 30000;
11
+ interface StorageHealth {
12
+ /** 'ok'; 'stalled' while a write has been pending longer than writeStallMs; 'dead' after two silent read windows (reload to recover, ADR-061). */
13
+ status: 'ok' | 'stalled' | 'dead';
14
+ /** Writes pending longer than writeStallMs right now. */
15
+ stalledWrites: number;
16
+ /** When the oldest stalled write started (ms since epoch), if any. */
17
+ stalledSince?: number;
18
+ }
19
+ interface StorageWatchdogOptions {
20
+ writeStallMs?: number;
21
+ readWatchdogMs?: number;
22
+ /** Injectable clock, for tests. */
23
+ now?: () => number;
24
+ /** Injectable timer, for tests: runs `fn` once after `ms` and returns a cancel function. */
25
+ setTimer?: (fn: () => void, ms: number) => () => void;
26
+ }
27
+ /**
28
+ * True for `StorageWorkerStartError` (raised by `@tallyui/storage-sqlite/web`
29
+ * when the worker cannot open the opfs-sahpool pool), matched by `name` or by
30
+ * the substring `StorageWorkerStartError` anywhere in the message. RxDB's
31
+ * remote storage re-throws the worker's error serialised across the worker
32
+ * boundary as a plain `Error` whose message embeds the original name as JSON,
33
+ * so a substring match (`includes`, not `startsWith`) is needed to still
34
+ * recognise it.
35
+ *
36
+ * A worker that crashes mid-call never replies (RxDB `storage-remote`,
37
+ * 16.21.1), so that case surfaces through `health$` (`dead`), not an error.
38
+ */
39
+ declare function isStorageWorkerFailure(error: unknown): boolean;
40
+ /**
41
+ * Wraps a storage so its instances report health on `health$` (ADR-061,
42
+ * following WCPOS). No storage call is ever settled on a clock: a timed-out
43
+ * write may still commit, so a slow write is only flagged as `stalled`, and
44
+ * its promise stays pending until the worker answers. Reads are watched: two
45
+ * consecutive `readWatchdogMs` windows in which reads were pending and no
46
+ * call settled mark the worker `dead` (sticky; the recovery is reload).
47
+ * `createStorageInstance` has no deadline, because the worker and wasm can be
48
+ * slow to download.
49
+ *
50
+ * Instance methods are replaced in place, the way RxDB's own validator wraps
51
+ * `bulkWrite`, so a later wrapper that assigns over ours calls ours, not itself.
52
+ * The `tallyEngine` marker is kept.
53
+ */
54
+ declare function withStorageWatchdog(storage: RxStorage<any, any>, options?: StorageWatchdogOptions): RxStorage<any, any> & {
55
+ health$: Observable<StorageHealth>;
56
+ };
57
+
5
58
  /**
6
59
  * The shape of a Tally database — keyed by collection name.
7
60
  */
@@ -20,7 +73,8 @@ interface CreateDatabaseOptions {
20
73
  * Create an RxDB database from a connector's schemas.
21
74
  *
22
75
  * This is the main entry point — give it a connector and it builds
23
- * the database with the right collections and schemas.
76
+ * the database with the right collections and schemas. A connector with
77
+ * `reconcile.stock` also gets the `stock_levels` overlay collection.
24
78
  *
25
79
  * ```ts
26
80
  * import { woocommerceConnector } from '@tallyui/connector-woocommerce';
@@ -31,11 +85,34 @@ interface CreateDatabaseOptions {
31
85
  * ```
32
86
  */
33
87
  declare function createTallyDatabase(options: CreateDatabaseOptions): Promise<TallyDatabase>;
88
+ /**
89
+ * The storage health of a database on the web engine (ADR-061), so an app can
90
+ * show "saving is slow…" (`stalled`) or "storage stopped, reload" (`dead`).
91
+ * `undefined` for any other storage, which has no watchdog.
92
+ */
93
+ declare function getStorageHealth(db: TallyDatabase): Observable<StorageHealth> | undefined;
94
+
95
+ /**
96
+ * The collection config for a connector schema: the schema plus a `v => null`
97
+ * strategy for every version from 1 to N (`{}` at version 0), so a version
98
+ * bump drops the documents and replication resyncs them (see ConnectorSchemas).
99
+ *
100
+ * Use this for any connector collection created outside `createTallyDatabase`
101
+ * (tests, an app's own database). A connector schema above version 0 needs
102
+ * these strategies and the migration plugin, or RxDB throws COL12 or
103
+ * "plugin missing". Never for local-only collections (`stock_levels`,
104
+ * `pos_orders`): a drop would lose local data.
105
+ */
106
+ declare function connectorCollection<T>(schema: RxJsonSchema<T>): {
107
+ schema: RxJsonSchema<T>;
108
+ migrationStrategies: MigrationStrategies;
109
+ };
34
110
 
35
111
  /**
36
112
  * Returns the appropriate RxDB storage adapter for the current platform.
37
113
  *
38
- * - Web browser: Dexie (IndexedDB)
114
+ * - Web browser: throws with guidance to pass the SQLite-wasm storage
115
+ * explicitly (ADR-061) — there is no default web storage any more.
39
116
  * - React Native: throws with guidance to provide SQLite storage explicitly
40
117
  * - Node/SSR/test: In-memory
41
118
  *
@@ -43,6 +120,13 @@ declare function createTallyDatabase(options: CreateDatabaseOptions): Promise<Ta
43
120
  */
44
121
  declare function getStorage(): RxStorage<any, any>;
45
122
 
123
+ /** ADR-061: the web runs premium SQLite on sqlite-wasm opfs-sahpool; one live tab. */
124
+ declare const WEB_STORAGE_ENGINE: "sqlite-sahpool";
125
+ /** multiInstance each web engine requires: opfs-sahpool holds exclusive OPFS handles, so a second instance cannot exist. */
126
+ declare const REQUIRED_MULTI_INSTANCE_BY_ENGINE: {
127
+ readonly 'sqlite-sahpool': false;
128
+ };
129
+
46
130
  interface StartReplicationOptions<RxDocType, CheckpointType = any> {
47
131
  collection: RxCollection<RxDocType>;
48
132
  adapter: ReplicationAdapter<RxDocType, CheckpointType>;
@@ -62,4 +146,219 @@ interface StartReplicationOptions<RxDocType, CheckpointType = any> {
62
146
  */
63
147
  declare function startReplication<RxDocType, CheckpointType = any>({ collection, adapter, context, live, retryTime, autoStart, }: StartReplicationOptions<RxDocType, CheckpointType>): RxReplicationState<RxDocType, CheckpointType>;
64
148
 
65
- export { type CreateDatabaseOptions, type StartReplicationOptions, type TallyDatabase, createTallyDatabase, getStorage, startReplication };
149
+ /**
150
+ * ADR-061: exactly one live tab per store, and a second tab never opens
151
+ * storage. `acquiring` while a hand-over is in flight, `live` while this tab
152
+ * holds the lock, `parked` after handing over, `blocked` when the live tab
153
+ * never answered and the user must close it.
154
+ */
155
+ type LiveTabState = 'acquiring' | 'live' | 'parked' | 'blocked';
156
+ type LiveTabChannel = Pick<BroadcastChannel, 'postMessage' | 'close'> & {
157
+ onmessage: ((event: {
158
+ data: unknown;
159
+ }) => void) | null;
160
+ };
161
+ interface LiveTabOptions {
162
+ /** Store scope; the lock and channel are named `tally-live-tab:<scope>`. */
163
+ scope: string;
164
+ /** Called on the live tab before it hands over: close the database, stop workers. Awaited. */
165
+ onPark: () => void | Promise<void>;
166
+ /** True while a sale, payment or storage write is in flight; the hand-over waits for false. */
167
+ isBusy?: () => boolean;
168
+ /** Longest the live tab defers a hand-over while busy (default 10_000 ms). */
169
+ maxDeferMs?: number;
170
+ /** How long a new tab waits for the live tab to acknowledge (default 3_000 ms). */
171
+ ackTimeoutMs?: number;
172
+ /** Injection for tests and non-browser hosts; default globalThis.navigator?.locks and globalThis.BroadcastChannel. */
173
+ locks?: Pick<LockManager, 'request'>;
174
+ createChannel?: (name: string) => LiveTabChannel;
175
+ /** Injection for tests; default globalThis. Source of `pagehide`/`pageshow`. */
176
+ events?: Pick<EventTarget, 'addEventListener' | 'removeEventListener'>;
177
+ /** Injection for tests; default Date.now. Wall clock for the busy-defer cap below. */
178
+ now?: () => number;
179
+ }
180
+ interface LiveTabHandle {
181
+ state$: Observable<LiveTabState>;
182
+ /** Ask the live tab to hand over, and take the lock. Used on start and by the parked screen's "Use here" button. */
183
+ takeOver(): Promise<LiveTabState>;
184
+ /** Release the lock and close the channel (sign-out, unmount). */
185
+ stop(): void;
186
+ }
187
+ /**
188
+ * Coordinates one live tab per store (ADR-061) over a Web Lock and a
189
+ * BroadcastChannel, both named `tally-live-tab:<scope>`.
190
+ *
191
+ * On platforms without Web Locks (React Native, Node, tests: `locks` is
192
+ * undefined) a tab is simply live at once, since native and Electron have
193
+ * one window per store.
194
+ */
195
+ declare function startLiveTab(options: LiveTabOptions): LiveTabHandle;
196
+
197
+ /** Collection holding the stock reconcile overlay (ADR-060). Local only: never replicated. */
198
+ declare const STOCK_LEVELS_COLLECTION = "stock_levels";
199
+
200
+ /** One overlay row: the connector's stock value for one key (Vendure variant id, Medusa inventory item id). */
201
+ interface StockLevelRow {
202
+ id: string;
203
+ /** The value `fetchPages` gave for this key, stored as is. */
204
+ value: unknown;
205
+ /** ISO 8601 time of the pass that wrote the row. */
206
+ updatedAt: string;
207
+ }
208
+ declare const stockLevelsSchema: RxJsonSchema<StockLevelRow>;
209
+ /** Use this whenever you create `stock_levels` yourself: the runner stores its last pass in local documents. */
210
+ declare const stockLevelsCollection: {
211
+ readonly schema: RxJsonSchema<StockLevelRow>;
212
+ readonly localDocuments: true;
213
+ };
214
+
215
+ interface StartStockReconcileOptions {
216
+ /** The `stock_levels` collection. The runner writes nothing else. */
217
+ collection: RxCollection<StockLevelRow>;
218
+ adapter: StockReconcileAdapter;
219
+ context: SyncContext;
220
+ /** Time between passes in ms (default: 300000, 5 minutes) */
221
+ intervalMs?: number;
222
+ /** Most pages one pass reads; beyond it the pass is truncated (default: 100) */
223
+ maxPages?: number;
224
+ }
225
+ interface StockReconcileResult {
226
+ pages: number;
227
+ /** Rows inserted or changed */
228
+ written: number;
229
+ /** Rows whose key the backend no longer returns */
230
+ removed: number;
231
+ truncated: boolean;
232
+ /** ISO time of a successful pass; also stored in the `last-pass` local document. */
233
+ completedAt?: string;
234
+ }
235
+ /** The runner's state. `lastCompletedAt` survives restarts; the rest is in memory. */
236
+ interface StockReconcileState {
237
+ lastCompletedAt?: string;
238
+ running: boolean;
239
+ truncated: boolean;
240
+ lastError?: unknown;
241
+ }
242
+ /**
243
+ * Periodically re-read stock into the `stock_levels` overlay collection (ADR-060).
244
+ *
245
+ * Replicated product documents are never written: a local write there makes
246
+ * RxDB's downstream skip the next pulled version of that document.
247
+ *
248
+ * The first pass waits for the interval; the app calls reconcileStock() after
249
+ * first paint and on foreground or resume. A call during a pass queues one
250
+ * follow-up pass (later calls share it), so a change made after the pass
251
+ * read is picked up straight after, not at the next interval. stop() clears
252
+ * the timer and aborts a running pass.
253
+ */
254
+ declare function startStockReconcile({ collection, adapter, context, intervalMs, maxPages, }: StartStockReconcileOptions): {
255
+ reconcileStock(): Promise<StockReconcileResult>;
256
+ stop(): void;
257
+ state$: Observable<StockReconcileState>;
258
+ };
259
+
260
+ interface StartIdReconcileOptions<Doc> {
261
+ /** The replicated products collection. Read only. */
262
+ collection: RxCollection<Doc>;
263
+ adapter: IdReconcileAdapter<Doc>;
264
+ context: SyncContext;
265
+ /** The app's `() => replication.reSync()`. */
266
+ reSync: () => void;
267
+ /** Delay before the first pass (default 5000); `null` skips it. */
268
+ startDelayMs?: number | null;
269
+ /** Time between passes in ms (default 86400000, 24 hours). */
270
+ intervalMs?: number;
271
+ /** Pages read before a pass is truncated (default 100). */
272
+ maxPages?: number;
273
+ /**
274
+ * The brake applies once would-be tombstones exceed this share of local
275
+ * products (default 0.2), unless `allowMassDelete` is set.
276
+ */
277
+ maxDeleteShare?: number;
278
+ /** Explicit override for a genuine purge; disables the mass-delete brake. */
279
+ allowMassDelete?: boolean;
280
+ }
281
+ interface IdReconcileResult {
282
+ pages: number;
283
+ queued: number;
284
+ truncated: boolean;
285
+ braked: boolean;
286
+ }
287
+ /**
288
+ * Compares live product/variant ids against the local `products` collection
289
+ * and queues disagreeing documents for the collection's pull (ADR-060). Only
290
+ * reads `collection`. A throw, abort, truncation or the mass-delete brake
291
+ * (below) queues nothing and skips `reSync`; only a complete, un-braked pass
292
+ * acts. One pass runs `startDelayMs` after start, then every `intervalMs`. A
293
+ * call during a pass queues one follow-up pass (later calls share it), so a
294
+ * change made after the pass read is picked up straight after, not at the
295
+ * next interval.
296
+ */
297
+ declare function startIdReconcile<Doc>({ collection, adapter, context, reSync, startDelayMs, intervalMs, maxPages, maxDeleteShare, allowMassDelete, }: StartIdReconcileOptions<Doc>): {
298
+ reconcileIds(): Promise<IdReconcileResult>;
299
+ stop(): void;
300
+ };
301
+
302
+ interface StartFingerprintReconcileOptions<Doc> {
303
+ /** The replicated collection. Read only. */
304
+ collection: RxCollection<Doc>;
305
+ adapter: FingerprintReconcileAdapter<Doc>;
306
+ context: SyncContext;
307
+ /** The app's `() => replication.reSync()`. */
308
+ reSync: () => void;
309
+ /** Delay before the first pass; `null` (default) skips it, since this runner is meant as a nightly backstop. */
310
+ startDelayMs?: number | null;
311
+ /** Time between passes in ms (default 86400000, 24 hours). */
312
+ intervalMs?: number;
313
+ /** Pages read before a pass is truncated (default 100). */
314
+ maxPages?: number;
315
+ /** Injection for tests; default Date.now. Stamps `lastResultAt`/`lastErrorAt`. */
316
+ now?: () => number;
317
+ }
318
+ interface FingerprintReconcileResult {
319
+ pages: number;
320
+ compared: number;
321
+ queued: number;
322
+ truncated: boolean;
323
+ /**
324
+ * Local products the remote side did not report in a complete pass (they are skipped); 0 on a truncated or failed
325
+ * pass, and 0 when the adapter yielded no pages at all (e.g. base-only mode, no pricing context) -- that is not
326
+ * the same as everything being unsellable. A channel that lists nothing still reads one empty page, so it
327
+ * correctly reports everything as unreported.
328
+ * For `calculatedPrices`, the products the sales channel does not list, which are not sellable here. A channel
329
+ * misconfiguration shows up as a large number, not a silent empty till.
330
+ */
331
+ unreported: number;
332
+ }
333
+ /**
334
+ * The runner's state; entirely in memory. The result is current only when
335
+ * `lastResultAt > (lastErrorAt ?? 0)`; show `unreported` from a stale result
336
+ * as stale. See `isFingerprintResultCurrent`.
337
+ */
338
+ interface FingerprintReconcileState {
339
+ running: boolean;
340
+ lastResult?: FingerprintReconcileResult;
341
+ lastResultAt?: number;
342
+ lastError?: unknown;
343
+ lastErrorAt?: number;
344
+ }
345
+ /** True when `state.lastResult` is current, i.e. newer than the last failure, if any. */
346
+ declare function isFingerprintResultCurrent(state: FingerprintReconcileState): boolean;
347
+ /**
348
+ * Compares a remote fingerprint per product against the local `collection`
349
+ * and queues disagreeing products for the collection's pull (ADR-060). Only
350
+ * reads `collection`. A throw, abort or truncation queues nothing and skips
351
+ * `reSync`; only a complete pass acts. Products the remote side doesn't
352
+ * report are left alone -- deletions are the id reconcile's job. No pass
353
+ * runs at start by default (`startDelayMs: null`); the app may still call
354
+ * `reconcile()` on demand. A call during a pass queues one follow-up pass
355
+ * (later calls share it), so a change made after the pass read is picked up
356
+ * straight after, not at the next interval.
357
+ */
358
+ declare function startFingerprintReconcile<Doc>({ collection, adapter, context, reSync, startDelayMs, intervalMs, maxPages, now, }: StartFingerprintReconcileOptions<Doc>): {
359
+ reconcile(): Promise<FingerprintReconcileResult>;
360
+ stop(): void;
361
+ state$: Observable<FingerprintReconcileState>;
362
+ };
363
+
364
+ export { type CreateDatabaseOptions, type FingerprintReconcileResult, type FingerprintReconcileState, type IdReconcileResult, type LiveTabHandle, type LiveTabOptions, type LiveTabState, REQUIRED_MULTI_INSTANCE_BY_ENGINE, STOCK_LEVELS_COLLECTION, STORAGE_READ_WATCHDOG_MS, STORAGE_WRITE_STALL_MS, type StartFingerprintReconcileOptions, type StartIdReconcileOptions, type StartReplicationOptions, type StartStockReconcileOptions, type StockLevelRow, type StockReconcileResult, type StockReconcileState, type StorageHealth, type StorageWatchdogOptions, type TallyDatabase, WEB_STORAGE_ENGINE, connectorCollection, createTallyDatabase, getStorage, getStorageHealth, isFingerprintResultCurrent, isStorageWorkerFailure, startFingerprintReconcile, startIdReconcile, startLiveTab, startReplication, startStockReconcile, stockLevelsCollection, stockLevelsSchema, withStorageWatchdog };