@bitclaw/outbox 0.0.0-stage → 0.1.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 Daniel Chavez
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/README.md CHANGED
@@ -1,3 +1,102 @@
1
- # Temporary Holding Version
1
+ # @bitclaw/outbox
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Offline-first outbox. Save each event locally the moment it happens, then deliver it when the network allows, with backoff, idempotency keys and a dead-letter state. Built for field apps that lose signal: a technician taps "start job" in a basement, and the start time reaches the server when the phone is back online.
4
+
5
+ > Part of [Warpkit](https://warpkit.dev/?utm_source=github&utm_medium=readme), my TypeScript SaaS starter.
6
+ > I'm open for consulting on this kind of work: [bitclaw.com/hire](https://bitclaw.com/hire?utm_source=github&utm_medium=readme).
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ npm install @bitclaw/outbox
12
+ ```
13
+
14
+ ## Use it with expo-sqlite
15
+
16
+ `createSqliteStore` takes any database with `execAsync`, `runAsync` and `getAllAsync`, which is expo-sqlite's `SQLiteDatabase` as-is. No Expo dependency in this package.
17
+
18
+ ```ts
19
+ import { createOutbox, createSqliteStore } from '@bitclaw/outbox';
20
+ import { randomUUID } from 'expo-crypto';
21
+ import { openDatabaseAsync } from 'expo-sqlite';
22
+
23
+ const db = await openDatabaseAsync('app.db');
24
+
25
+ const outbox = createOutbox({
26
+ store: await createSqliteStore(db),
27
+ newId: randomUUID,
28
+ send: async entry => {
29
+ try {
30
+ const res = await fetch(`${API_URL}/v1/events`, {
31
+ method: 'POST',
32
+ headers: { 'content-type': 'application/json', 'idempotency-key': entry.id },
33
+ body: JSON.stringify({ type: entry.type, payload: entry.payload })
34
+ });
35
+ if (res.ok) return { status: 'sent' };
36
+ if (res.status >= 500 || res.status === 429) return { status: 'retry', error: `${res.status}` };
37
+ return { status: 'reject', error: `${res.status}` };
38
+ } catch {
39
+ return { status: 'retry', error: 'no signal' };
40
+ }
41
+ }
42
+ });
43
+
44
+ await outbox.enqueue('job.started', { jobId, at: Date.now(), location });
45
+ void outbox.flush();
46
+ ```
47
+
48
+ Call `flush()` when it is likely to work: after `enqueue`, when the app comes to the foreground, when connectivity returns.
49
+
50
+ ## How delivery works
51
+
52
+ | `send` returns | What happens |
53
+ |---|---|
54
+ | `{ status: 'sent' }` | The entry is removed. |
55
+ | `{ status: 'retry', error }` | Temporary failure (no signal, 5xx, timeout). Retried later with exponential backoff and jitter. The flush stops here by default: with no signal, the rest would fail too. |
56
+ | `{ status: 'reject', error }` | Permanent failure (validation, 4xx). The entry is dead-lettered at once instead of retried forever. |
57
+ | throws | Treated as `retry`, so one bad release cannot dead-letter the queue. |
58
+
59
+ After `maxAttempts` (default 10) a retried entry is dead-lettered too. Dead entries stay in the store; `retryDead()` puts them back, and `counts()` reports `{ pending, dead }` for a sync indicator.
60
+
61
+ ## The server must deduplicate
62
+
63
+ Delivery is at least once: a request can reach the server and the phone can lose signal before the response arrives. The next flush sends the same entry again. Every entry has an `id` (a UUID); send it as an idempotency key and have the server ignore an id it has already processed.
64
+
65
+ ## Guarantees
66
+
67
+ - `flush()` calls run one at a time. A flush that starts while another runs waits for it, then sends whatever is still due. An entry is never sent twice by overlapping flushes.
68
+ - Each store method is one atomic statement. No transaction is held across a network call.
69
+ - Enqueueing an id that already exists keeps the first entry.
70
+ - Entries are delivered oldest first.
71
+
72
+ ## Options
73
+
74
+ | Option | Default |
75
+ |---|---|
76
+ | `store` | required: `createSqliteStore(db)` or `createMemoryStore()` (tests) |
77
+ | `send` | required |
78
+ | `newId` | `crypto.randomUUID`; on React Native pass `expo-crypto`'s `randomUUID` |
79
+ | `maxAttempts` | `10` |
80
+ | `baseDelayMs`, `maxDelayMs` | `2000`, `300000` (5 minutes) |
81
+ | `batchSize` | `50` per flush |
82
+ | `stopOnRetry` | `true` |
83
+ | `now`, `random` | `Date.now`, `Math.random`; inject them to test without waiting |
84
+
85
+ ## Other drivers
86
+
87
+ Wrap a synchronous driver in three async methods. For `bun:sqlite`:
88
+
89
+ ```ts
90
+ import { Database } from 'bun:sqlite';
91
+
92
+ const db = new Database('app.db');
93
+ const store = await createSqliteStore({
94
+ execAsync: async sql => void db.exec(sql),
95
+ runAsync: async (sql, params) => db.query(sql).run(...params),
96
+ getAllAsync: async (sql, params) => db.query(sql).all(...params)
97
+ });
98
+ ```
99
+
100
+ ## License
101
+
102
+ MIT
@@ -0,0 +1,5 @@
1
+ export { createMemoryStore } from './memory-store.js';
2
+ export { createOutbox, type Outbox, type OutboxOptions } from './outbox.js';
3
+ export { createSqliteStore, type SqliteDatabase } from './sqlite-store.js';
4
+ export type { FlushReport, OutboxCounts, OutboxEntry, OutboxStatus, OutboxStore, SendOutcome } from './types.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,KAAK,MAAM,EAAE,KAAK,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5E,OAAO,EAAE,iBAAiB,EAAE,KAAK,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAC3E,YAAY,EACV,WAAW,EACX,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,WAAW,EACX,WAAW,EACZ,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { createMemoryStore } from './memory-store.js';
2
+ export { createOutbox } from './outbox.js';
3
+ export { createSqliteStore } from './sqlite-store.js';
@@ -0,0 +1,4 @@
1
+ import type { OutboxStore } from './types.js';
2
+ /** An in-memory store for tests and demos. Nothing survives a restart. */
3
+ export declare function createMemoryStore(): OutboxStore;
4
+ //# sourceMappingURL=memory-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory-store.d.ts","sourceRoot":"","sources":["../src/memory-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA6B,WAAW,EAAE,MAAM,YAAY,CAAC;AAEzE,0EAA0E;AAC1E,wBAAgB,iBAAiB,IAAI,WAAW,CAmD/C"}
@@ -0,0 +1,56 @@
1
+ /** An in-memory store for tests and demos. Nothing survives a restart. */
2
+ export function createMemoryStore() {
3
+ const entries = new Map();
4
+ const update = (id, change) => {
5
+ const entry = entries.get(id);
6
+ if (entry)
7
+ entries.set(id, { ...entry, ...change });
8
+ };
9
+ return {
10
+ async insert(entry) {
11
+ if (!entries.has(entry.id))
12
+ entries.set(entry.id, entry);
13
+ },
14
+ async due(now, limit) {
15
+ return [...entries.values()]
16
+ .filter(e => e.status === 'pending' && e.nextAttemptAt <= now)
17
+ .sort((a, b) => a.createdAt - b.createdAt)
18
+ .slice(0, limit);
19
+ },
20
+ async remove(id) {
21
+ entries.delete(id);
22
+ },
23
+ async reschedule(id, attempts, nextAttemptAt, lastError) {
24
+ update(id, { attempts, nextAttemptAt, lastError });
25
+ },
26
+ async markDead(id, attempts, lastError) {
27
+ update(id, { attempts, lastError, status: 'dead' });
28
+ },
29
+ async revive(now) {
30
+ let revived = 0;
31
+ for (const entry of entries.values()) {
32
+ if (entry.status !== 'dead')
33
+ continue;
34
+ entries.set(entry.id, {
35
+ ...entry,
36
+ status: 'pending',
37
+ attempts: 0,
38
+ nextAttemptAt: now
39
+ });
40
+ revived++;
41
+ }
42
+ return revived;
43
+ },
44
+ async counts() {
45
+ let pending = 0;
46
+ let dead = 0;
47
+ for (const entry of entries.values()) {
48
+ if (entry.status === 'dead')
49
+ dead++;
50
+ else
51
+ pending++;
52
+ }
53
+ return { pending, dead };
54
+ }
55
+ };
56
+ }
@@ -0,0 +1,38 @@
1
+ import type { FlushReport, OutboxCounts, OutboxEntry, OutboxStore, SendOutcome } from './types.js';
2
+ export type OutboxOptions = {
3
+ readonly store: OutboxStore;
4
+ /** Deliver one entry. Must not throw for a network failure: return retry. */
5
+ readonly send: (entry: OutboxEntry) => Promise<SendOutcome>;
6
+ /** Attempts before an entry is dead-lettered. Default 10. */
7
+ readonly maxAttempts?: number;
8
+ /** Backoff base and cap in ms. Defaults 2000 and 300000 (5 minutes). */
9
+ readonly baseDelayMs?: number;
10
+ readonly maxDelayMs?: number;
11
+ /** Entries per flush. Default 50. */
12
+ readonly batchSize?: number;
13
+ /**
14
+ * Stop the flush at the first `retry`. Default true: with no signal, every
15
+ * later send fails too, and trying them only burns battery.
16
+ */
17
+ readonly stopOnRetry?: boolean;
18
+ /** UUID source. Default crypto.randomUUID; on React Native pass expo-crypto's. */
19
+ readonly newId?: () => string;
20
+ readonly now?: () => number;
21
+ readonly random?: () => number;
22
+ };
23
+ export type Outbox = {
24
+ /** Save an event locally. Returns its id, the idempotency key. */
25
+ enqueue(type: string, payload: unknown, options?: {
26
+ readonly id?: string;
27
+ }): Promise<string>;
28
+ /**
29
+ * Send what is due. Calls run one at a time: a flush that starts while
30
+ * another runs waits for it, then sends whatever is still due.
31
+ */
32
+ flush(): Promise<FlushReport>;
33
+ /** Move dead entries back to pending, e.g. from a "retry failed" button. */
34
+ retryDead(): Promise<number>;
35
+ counts(): Promise<OutboxCounts>;
36
+ };
37
+ export declare function createOutbox(options: OutboxOptions): Outbox;
38
+ //# sourceMappingURL=outbox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outbox.d.ts","sourceRoot":"","sources":["../src/outbox.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,WAAW,EACX,YAAY,EACZ,WAAW,EACX,WAAW,EACX,WAAW,EACZ,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC;IAC5B,6EAA6E;IAC7E,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,OAAO,CAAC,WAAW,CAAC,CAAC;IAC5D,6DAA6D;IAC7D,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,wEAAwE;IACxE,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,qCAAqC;IACrC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC;IAC/B,kFAAkF;IAClF,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,MAAM,CAAC;IAC9B,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IAC5B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,MAAM,CAAC;CAChC,CAAC;AAEF,MAAM,MAAM,MAAM,GAAG;IACnB,kEAAkE;IAClE,OAAO,CACL,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,CAAC,EAAE,MAAM,CAAA;KAAE,GACjC,OAAO,CAAC,MAAM,CAAC,CAAC;IACnB;;;OAGG;IACH,KAAK,IAAI,OAAO,CAAC,WAAW,CAAC,CAAC;IAC9B,4EAA4E;IAC5E,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IAC7B,MAAM,IAAI,OAAO,CAAC,YAAY,CAAC,CAAC;CACjC,CAAC;AAeF,wBAAgB,YAAY,CAAC,OAAO,EAAE,aAAa,GAAG,MAAM,CA8E3D"}
package/dist/outbox.js ADDED
@@ -0,0 +1,74 @@
1
+ import { backoffDelay, WriteMutex } from '@bitclaw/mutex';
2
+ function defaultNewId() {
3
+ const uuid = globalThis.crypto?.randomUUID;
4
+ if (!uuid) {
5
+ throw new Error('crypto.randomUUID is unavailable here; pass newId (on React Native, expo-crypto randomUUID)');
6
+ }
7
+ return uuid.call(globalThis.crypto);
8
+ }
9
+ const describe = (error) => error instanceof Error ? error.message : String(error);
10
+ export function createOutbox(options) {
11
+ const { store, send, maxAttempts = 10, baseDelayMs = 2000, maxDelayMs = 300_000, batchSize = 50, stopOnRetry = true, newId = defaultNewId, now = Date.now, random = Math.random } = options;
12
+ const flushing = new WriteMutex();
13
+ async function deliver(entry) {
14
+ let outcome;
15
+ try {
16
+ outcome = await send(entry);
17
+ }
18
+ catch (error) {
19
+ // A throwing send is a bug or an unexpected failure; treat it as
20
+ // temporary so one bad deploy cannot dead-letter the whole queue.
21
+ outcome = { status: 'retry', error: describe(error) };
22
+ }
23
+ if (outcome.status === 'sent') {
24
+ await store.remove(entry.id);
25
+ return 'sent';
26
+ }
27
+ const attempts = entry.attempts + 1;
28
+ if (outcome.status === 'reject' || attempts >= maxAttempts) {
29
+ await store.markDead(entry.id, attempts, outcome.error);
30
+ return 'dead';
31
+ }
32
+ const delay = backoffDelay(attempts - 1, baseDelayMs, maxDelayMs, random);
33
+ await store.reschedule(entry.id, attempts, now() + delay, outcome.error);
34
+ return 'retried';
35
+ }
36
+ async function drain() {
37
+ let sent = 0;
38
+ let retried = 0;
39
+ let dead = 0;
40
+ for (const entry of await store.due(now(), batchSize)) {
41
+ const result = await deliver(entry);
42
+ if (result === 'sent')
43
+ sent++;
44
+ else if (result === 'dead')
45
+ dead++;
46
+ else {
47
+ retried++;
48
+ if (stopOnRetry)
49
+ return { sent, retried, dead, stopped: true };
50
+ }
51
+ }
52
+ return { sent, retried, dead, stopped: false };
53
+ }
54
+ return {
55
+ async enqueue(type, payload, enqueueOptions) {
56
+ const id = enqueueOptions?.id ?? newId();
57
+ const at = now();
58
+ await store.insert({
59
+ id,
60
+ type,
61
+ payload,
62
+ createdAt: at,
63
+ attempts: 0,
64
+ nextAttemptAt: at,
65
+ lastError: null,
66
+ status: 'pending'
67
+ });
68
+ return id;
69
+ },
70
+ flush: () => flushing.acquire(drain),
71
+ retryDead: () => store.revive(now()),
72
+ counts: () => store.counts()
73
+ };
74
+ }
@@ -0,0 +1,22 @@
1
+ import type { OutboxStore } from './types.js';
2
+ type BindValue = string | number | null;
3
+ /**
4
+ * The async SQLite surface the store needs. expo-sqlite's SQLiteDatabase
5
+ * (openDatabaseAsync) has these methods as-is; another driver needs a
6
+ * thin wrapper.
7
+ */
8
+ export type SqliteDatabase = {
9
+ execAsync(source: string): Promise<void>;
10
+ runAsync(source: string, params: BindValue[]): Promise<unknown>;
11
+ getAllAsync<T>(source: string, params: BindValue[]): Promise<T[]>;
12
+ };
13
+ /**
14
+ * A store in one SQLite table, created if missing. Turns on WAL so reads
15
+ * never wait on a write. Each method is a single statement, so each is
16
+ * atomic without an explicit transaction.
17
+ */
18
+ export declare function createSqliteStore(db: SqliteDatabase, options?: {
19
+ readonly table?: string;
20
+ }): Promise<OutboxStore>;
21
+ export {};
22
+ //# sourceMappingURL=sqlite-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite-store.d.ts","sourceRoot":"","sources":["../src/sqlite-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA6B,WAAW,EAAE,MAAM,YAAY,CAAC;AAEzE,KAAK,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;AAExC;;;;GAIG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACzC,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAChE,WAAW,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;CACnE,CAAC;AA0BF;;;;GAIG;AACH,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,cAAc,EAClB,OAAO,GAAE;IAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAO,GACxC,OAAO,CAAC,WAAW,CAAC,CAoFtB"}
@@ -0,0 +1,78 @@
1
+ const TABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
2
+ const toEntry = (row) => ({
3
+ id: row.id,
4
+ type: row.type,
5
+ payload: JSON.parse(row.payload),
6
+ createdAt: row.created_at,
7
+ attempts: row.attempts,
8
+ nextAttemptAt: row.next_attempt_at,
9
+ lastError: row.last_error,
10
+ status: row.status
11
+ });
12
+ /**
13
+ * A store in one SQLite table, created if missing. Turns on WAL so reads
14
+ * never wait on a write. Each method is a single statement, so each is
15
+ * atomic without an explicit transaction.
16
+ */
17
+ export async function createSqliteStore(db, options = {}) {
18
+ const table = options.table ?? 'outbox';
19
+ if (!TABLE_NAME.test(table))
20
+ throw new Error(`Invalid table name: ${table}`);
21
+ await db.execAsync(`
22
+ PRAGMA journal_mode = WAL;
23
+ CREATE TABLE IF NOT EXISTS ${table} (
24
+ id TEXT PRIMARY KEY NOT NULL,
25
+ type TEXT NOT NULL,
26
+ payload TEXT NOT NULL,
27
+ created_at INTEGER NOT NULL,
28
+ attempts INTEGER NOT NULL DEFAULT 0,
29
+ next_attempt_at INTEGER NOT NULL,
30
+ last_error TEXT,
31
+ status TEXT NOT NULL DEFAULT 'pending'
32
+ );
33
+ CREATE INDEX IF NOT EXISTS ${table}_due ON ${table} (status, next_attempt_at);
34
+ `);
35
+ return {
36
+ async insert(entry) {
37
+ // OR IGNORE: enqueueing the same id twice keeps the first, so a
38
+ // caller that retries enqueue cannot create a duplicate.
39
+ await db.runAsync(`INSERT OR IGNORE INTO ${table}
40
+ (id, type, payload, created_at, attempts, next_attempt_at, last_error, status)
41
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, [
42
+ entry.id,
43
+ entry.type,
44
+ JSON.stringify(entry.payload),
45
+ entry.createdAt,
46
+ entry.attempts,
47
+ entry.nextAttemptAt,
48
+ entry.lastError,
49
+ entry.status
50
+ ]);
51
+ },
52
+ async due(now, limit) {
53
+ const rows = await db.getAllAsync(`SELECT * FROM ${table}
54
+ WHERE status = 'pending' AND next_attempt_at <= ?
55
+ ORDER BY created_at, rowid LIMIT ?`, [now, limit]);
56
+ return rows.map(toEntry);
57
+ },
58
+ async remove(id) {
59
+ await db.runAsync(`DELETE FROM ${table} WHERE id = ?`, [id]);
60
+ },
61
+ async reschedule(id, attempts, nextAttemptAt, lastError) {
62
+ await db.runAsync(`UPDATE ${table} SET attempts = ?, next_attempt_at = ?, last_error = ? WHERE id = ?`, [attempts, nextAttemptAt, lastError, id]);
63
+ },
64
+ async markDead(id, attempts, lastError) {
65
+ await db.runAsync(`UPDATE ${table} SET attempts = ?, last_error = ?, status = 'dead' WHERE id = ?`, [attempts, lastError, id]);
66
+ },
67
+ async revive(now) {
68
+ const dead = await db.getAllAsync(`SELECT COUNT(*) AS n FROM ${table} WHERE status = 'dead'`, []);
69
+ await db.runAsync(`UPDATE ${table} SET status = 'pending', attempts = 0, next_attempt_at = ? WHERE status = 'dead'`, [now]);
70
+ return dead[0]?.n ?? 0;
71
+ },
72
+ async counts() {
73
+ const rows = await db.getAllAsync(`SELECT status, COUNT(*) AS n FROM ${table} GROUP BY status`, []);
74
+ const count = (status) => rows.find(r => r.status === status)?.n ?? 0;
75
+ return { pending: count('pending'), dead: count('dead') };
76
+ }
77
+ };
78
+ }
@@ -0,0 +1,56 @@
1
+ export type OutboxStatus = 'pending' | 'dead';
2
+ export type OutboxEntry<P = unknown> = {
3
+ /** Idempotency key. Send it to the server so a replay is a no-op. */
4
+ readonly id: string;
5
+ readonly type: string;
6
+ readonly payload: P;
7
+ readonly createdAt: number;
8
+ readonly attempts: number;
9
+ readonly nextAttemptAt: number;
10
+ readonly lastError: string | null;
11
+ readonly status: OutboxStatus;
12
+ };
13
+ export type OutboxCounts = {
14
+ readonly pending: number;
15
+ readonly dead: number;
16
+ };
17
+ /**
18
+ * Where entries live. Every method is one atomic write or read; the outbox
19
+ * never holds a transaction across a network call.
20
+ */
21
+ export type OutboxStore = {
22
+ insert(entry: OutboxEntry): Promise<void>;
23
+ /** Pending entries with nextAttemptAt <= now, oldest first. */
24
+ due(now: number, limit: number): Promise<OutboxEntry[]>;
25
+ /** Delivered: the entry is gone. */
26
+ remove(id: string): Promise<void>;
27
+ /** Failed, try again at nextAttemptAt. */
28
+ reschedule(id: string, attempts: number, nextAttemptAt: number, lastError: string): Promise<void>;
29
+ /** Failed for good: kept as dead for a person to inspect or retry. */
30
+ markDead(id: string, attempts: number, lastError: string): Promise<void>;
31
+ /** Dead entries back to pending, due now. Returns how many. */
32
+ revive(now: number): Promise<number>;
33
+ counts(): Promise<OutboxCounts>;
34
+ };
35
+ /**
36
+ * What one delivery attempt achieved. `retry` is temporary (no signal, 5xx,
37
+ * timeout); `reject` is permanent (validation, 4xx) and dead-letters the
38
+ * entry instead of retrying it forever.
39
+ */
40
+ export type SendOutcome = {
41
+ readonly status: 'sent';
42
+ } | {
43
+ readonly status: 'retry';
44
+ readonly error: string;
45
+ } | {
46
+ readonly status: 'reject';
47
+ readonly error: string;
48
+ };
49
+ export type FlushReport = {
50
+ readonly sent: number;
51
+ readonly retried: number;
52
+ readonly dead: number;
53
+ /** Stopped early: a `retry` with `stopOnRetry` (no signal, so stop). */
54
+ readonly stopped: boolean;
55
+ };
56
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,YAAY,GAAG,SAAS,GAAG,MAAM,CAAC;AAE9C,MAAM,MAAM,WAAW,CAAC,CAAC,GAAG,OAAO,IAAI;IACrC,qEAAqE;IACrE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;IACpB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;CAC/B,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAE/E;;;GAGG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB,MAAM,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1C,+DAA+D;IAC/D,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;IACxD,oCAAoC;IACpC,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAClC,0CAA0C;IAC1C,UAAU,CACR,EAAE,EAAE,MAAM,EACV,QAAQ,EAAE,MAAM,EAChB,aAAa,EAAE,MAAM,EACrB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,IAAI,CAAC,CAAC;IACjB,sEAAsE;IACtE,QAAQ,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACzE,+DAA+D;IAC/D,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACrC,MAAM,IAAI,OAAO,CAAC,YAAY,CAAC,CAAC;CACjC,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,WAAW,GACnB;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAC3B;IAAE,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GACpD;IAAE,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAE1D,MAAM,MAAM,WAAW,GAAG;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,wEAAwE;IACxE,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;CAC3B,CAAC"}
package/dist/types.js ADDED
File without changes
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@bitclaw/outbox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "license": "MIT",
5
+ "description": "Offline-first outbox: save events locally, deliver them with backoff and idempotency keys when the network returns. SQLite store works with expo-sqlite as-is.",
6
+ "files": [
7
+ "dist",
8
+ "LICENSE",
9
+ "README.md"
10
+ ],
11
+ "type": "module",
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ }
19
+ },
20
+ "scripts": {
21
+ "build": "tsc -p tsconfig.build.json",
22
+ "test": "bun test",
23
+ "test:watch": "bun test --watch",
24
+ "typecheck": "tsc --noEmit",
25
+ "lint": "biome check",
26
+ "lint:fix": "biome check --write",
27
+ "format": "biome format --write",
28
+ "knip": "knip",
29
+ "prepublishOnly": "npm run build && npm test",
30
+ "publish:patch": "npm version patch && git push --follow-tags",
31
+ "publish:minor": "npm version minor && git push --follow-tags",
32
+ "publish:major": "npm version major && git push --follow-tags"
33
+ },
34
+ "dependencies": {
35
+ "@bitclaw/mutex": "^0.1.0"
36
+ },
37
+ "devDependencies": {
38
+ "@biomejs/biome": "2.4.15",
39
+ "knip": "6.12.2",
40
+ "@types/bun": "1.3.13",
41
+ "typescript": "5.9.3"
42
+ },
43
+ "keywords": [
44
+ "outbox",
45
+ "offline",
46
+ "offline-first",
47
+ "sync",
48
+ "idempotency",
49
+ "react-native",
50
+ "expo-sqlite"
51
+ ],
52
+ "repository": {
53
+ "type": "git",
54
+ "url": "git+https://github.com/bitclaw/outbox.git"
55
+ }
56
+ }