powersync-bridge 0.0.1-alpha.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 akpor-kofi
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 ADDED
@@ -0,0 +1,218 @@
1
+ # powersync-bridge
2
+
3
+ A client-side bridge between a [PowerSync](https://powersync.com) local SQLite database and a
4
+ conventional HTTP API, for web and React Native.
5
+
6
+ The right data source, local synced SQLite or the live API, is a runtime, per-screen decision.
7
+ This package makes it automatic:
8
+
9
+ - **`useRacedList`** — paint the first screen from whichever source is *correct* first. A
10
+ first-ever visit has an empty local table; a warm re-mount has yesterday's checkpoint. The
11
+ bridge fetches one API snapshot, merges by id with pending-write and freshness awareness,
12
+ and hands the list to local sync as soon as local is fresh in this session.
13
+ - **`useInfiniteList`** — scroll past the synced window. Older data arrives either through
14
+ PowerSync sync streams (one equality partition at a time, bounded) or through your API's
15
+ pages. Row removals are classified as filtered-out, delete, or eviction, so the list never
16
+ resurrects deletes and never loses content mid-scroll.
17
+ - **`useOnDemandStream`** — pull one record into the offline database by id.
18
+
19
+ Status: **v0 alpha**. Core engine and invariant tests are complete (35 tests on a virtual-time
20
+ fake driver); the PowerSync driver is written against `@powersync/common` 2.3 and needs a running
21
+ integration before GA. Sizes (minified + gzip): core 8.2 kB, React 0.6 kB, driver 1.8 kB.
22
+
23
+ ## What your backend must change
24
+
25
+ **Nothing.** No new tables, no new columns, no change to existing sync streams. The one rule is an
26
+ alignment, not a change: your list endpoint sorts rows the same way your local query does, with
27
+ `id` as the last tiebreaker.
28
+
29
+ | What you want | Streams you need | Routes you need |
30
+ |---|---|---|
31
+ | Fast, correct first paint of any list | none beyond what you have | your existing list endpoint |
32
+ | Scroll past the synced window, older pages from the API | none | the same endpoint accepting `cursor` (or `offset`, degraded) |
33
+ | Scroll past the synced window, older months into the offline DB | one stream with `subscription.parameter('month')`, partition computed with `substring()` on your existing timestamp | optional `GET …/floor` |
34
+ | Open one old record by id, offline-capable | one stream with `id = subscription.parameter('id')` | none |
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pnpm add powersync-bridge @powersync-bridge/react @powersync-bridge/drizzle @powersync-bridge/powersync
40
+ ```
41
+
42
+ Peers: `@powersync/common ^2.3`, `@powersync/web ^2.4` or `@powersync/react-native ^2.3`,
43
+ `@powersync/drizzle-driver`, `drizzle-orm`, `react ^18.2 || ^19`. TanStack Query is optional.
44
+
45
+ ## Setup (once, in a plain module)
46
+
47
+ ```ts
48
+ // bridge.ts
49
+ import { createBridge } from 'powersync-bridge';
50
+ import { createPowerSyncDriver } from '@powersync-bridge/powersync';
51
+ import { drizzleAdapter } from '@powersync-bridge/drizzle';
52
+ import { db, drizzle } from './db/powersync';
53
+
54
+ const adapter = drizzleAdapter(drizzle);
55
+ export const bridge = createBridge({
56
+ driver: createPowerSyncDriver(db, { adapter, onlineHint: () => navigator.onLine }),
57
+ adapter,
58
+ platformGates: { native: 'local-first', web: 'race' },
59
+ });
60
+ ```
61
+
62
+ ```ts
63
+ // db/boot.ts — connect THROUGH the bridge: identity is derived from the JWT your connector
64
+ // already returns. Never pass claims yourself.
65
+ await db.init();
66
+ await db.connect(bridge.wrapConnector(connector));
67
+ ```
68
+
69
+ ```tsx
70
+ // App.tsx
71
+ <BridgeProvider bridge={bridge}>
72
+ <Router />
73
+ </BridgeProvider>
74
+ ```
75
+
76
+ ## A raced list (page 1, with joins)
77
+
78
+ ```ts
79
+ import { z } from 'zod';
80
+ import { desc, eq } from 'drizzle-orm';
81
+ import { defineRacedList } from 'powersync-bridge';
82
+ import { drizzle } from '../db/powersync';
83
+ import { sales, customers, users } from '../db/schema';
84
+
85
+ const SaleApi = z.object({
86
+ id: z.string(), sold_at: z.string(), total: z.string(),
87
+ status: z.enum(['OPEN', 'PAID', 'VOID']), item_count: z.number().int(),
88
+ customer_name: z.string(), seller_name: z.string(),
89
+ });
90
+ type SaleApi = z.infer<typeof SaleApi>;
91
+
92
+ export const RecentSales = defineRacedList({
93
+ id: 'recent-sales',
94
+ table: 'sales',
95
+ // The row type is inferred from this query. Annotate the scope; close over your drizzle instance.
96
+ query: ({ orgId }: { orgId: string }) =>
97
+ drizzle
98
+ .select({
99
+ id: sales.id, soldAt: sales.soldAt, total: sales.total, status: sales.status,
100
+ itemCount: sales.itemCount, customerName: customers.name, sellerName: users.displayName,
101
+ })
102
+ .from(sales)
103
+ .innerJoin(customers, eq(customers.id, sales.customerId))
104
+ .innerJoin(users, eq(users.id, sales.sellerId))
105
+ .where(eq(sales.orgId, orgId))
106
+ .orderBy(desc(sales.soldAt), desc(sales.id))
107
+ .limit(50),
108
+ fetchSnapshot: async (_scope, signal) => {
109
+ const res = await api.get('/api/sales?limit=50', { signal });
110
+ return { rows: z.array(SaleApi).parse(res.items) };
111
+ },
112
+ mapApi: (o: SaleApi) => ({ // return type is checked against the query's row type
113
+ id: o.id, soldAt: o.sold_at, total: o.total, status: o.status,
114
+ itemCount: o.item_count, customerName: o.customer_name, sellerName: o.seller_name,
115
+ }),
116
+ orderKey: ['soldAt', 'id'] as const, // `id` is always the implicit tiebreaker
117
+ direction: 'desc',
118
+ limit: 50,
119
+ stream: { name: 'sales_window', params: null },
120
+ });
121
+ ```
122
+
123
+ ```tsx
124
+ function RecentSalesScreen({ orgId }: { orgId: string }) {
125
+ const { items, state, errors } = useRacedList(RecentSales, { orgId });
126
+ if (state === 'pending') return <Skeleton />;
127
+ return (
128
+ <FlatList
129
+ data={items}
130
+ keyExtractor={(r) => r.row.id}
131
+ renderItem={({ item }) => (
132
+ <SaleRow
133
+ sale={item.row}
134
+ muted={item.stale === true || !item.presentLocally}
135
+ onVoid={item.presentLocally ? () => voidSale(item.row.id) : undefined} // presence-gated writes
136
+ />
137
+ )}
138
+ />
139
+ );
140
+ }
141
+ ```
142
+
143
+ ## An infinite list (older months via sync streams)
144
+
145
+ ```ts
146
+ import { defineInfiniteList, type Cursor, type PageArgs } from 'powersync-bridge';
147
+
148
+ type SaleCursor = Cursor<SaleRow, ['soldAt', 'id']>; // [string, string] | undefined
149
+
150
+ export const SalesHistory = defineInfiniteList({
151
+ id: 'sales-history',
152
+ table: 'sales',
153
+ pageSize: 50,
154
+ orderKey: ['soldAt', 'id'] as const,
155
+ direction: 'desc',
156
+ // Annotate the page argument with the Cursor type; the row type is inferred from the return.
157
+ query: ({ cursor, limit }: PageArgs<SaleCursor>, { orgId }: { orgId: string }) =>
158
+ drizzle.select(projection).from(sales) /* …joins… */
159
+ .where(and(eq(sales.orgId, orgId), cursor ? or(lt(sales.soldAt, cursor[0]), and(eq(sales.soldAt, cursor[0]), lt(sales.id, cursor[1]))) : undefined))
160
+ .orderBy(desc(sales.soldAt), desc(sales.id))
161
+ .limit(limit),
162
+ escalate: {
163
+ kind: 'partition',
164
+ stream: 'sales_month',
165
+ partitionOf: (c) => (c ? c[0].slice(0, 7) : currentMonth()),
166
+ nextPartition: prevMonth,
167
+ partitionParams: (m) => ({ month: m }),
168
+ floor: '2015-01', // static floor, always required
169
+ serverFloor: async () => (await api.get('/api/sales/floor')).month, // optional exact floor
170
+ },
171
+ });
172
+ ```
173
+
174
+ ```yaml
175
+ # sync_streams.yaml — no partition column; the month is computed from your existing timestamp
176
+ sales_month:
177
+ query: >
178
+ SELECT * FROM sales
179
+ WHERE org_id = auth.parameter('org_id')
180
+ AND substring(sold_at::text, 1, 7) = subscription.parameter('month')
181
+ ```
182
+
183
+ Or escalate through your API instead (`kind: 'api'` with a cursor, or `kind: 'api-offset'` for
184
+ offset-only APIs, where duplicates are dropped and a shift is reported in `warnings`).
185
+
186
+ ## Rules that make it safe
187
+
188
+ - **Pending writes always win** — the live upload queue, a seeded snapshot-lifetime window, and
189
+ recently-acked writes shield your edits from an older API snapshot.
190
+ - **Freshness is session-scoped** — PowerSync's persisted `hasSynced` never counts as "fresh";
191
+ a checkpoint is stamped at its download start and the stamp is monotonic.
192
+ - **Deletes never resurrect** — a pending delete tombstones its id for the snapshot's lifetime.
193
+ - **Removals are classified** — a batched presence probe distinguishes filtered-out from
194
+ deleted; stream expiry distinguishes deleted from evicted; evicted rows stay visible but
195
+ are marked `presentLocally: false` and cannot be written.
196
+ - **Identity is derived** — from the connector's JWT, deny-listing volatile claims; an org
197
+ switch swaps every store's root synchronously, so no frame renders the outgoing tenant.
198
+
199
+ Sorting constraints: the sort column must compare identically on Postgres and SQLite.
200
+ ISO-8601 UTC strings, integers and uuidv7 are safe. For text use `ORDER BY col COLLATE "C"` on
201
+ the API; for decimals declare the column as `column.real` in the client schema.
202
+
203
+ ## Testing your own lists
204
+
205
+ `powersync-bridge/testing` ships a `FakeDriver` with virtual time: script sync status,
206
+ checkpoints, uploads, stream first-syncs and API responses, then assert on interleavings. See
207
+ `packages/core/test` for the invariant suite (T1–T44 in ARCHITECTURE.md §12.2).
208
+
209
+ ## Layout
210
+
211
+ ```
212
+ packages/core powersync-bridge engine, definitions, testing driver
213
+ packages/react @powersync-bridge/react BridgeProvider + hooks
214
+ packages/adapters/drizzle @powersync-bridge/drizzle builder → PreparedQuery (decoded rows)
215
+ packages/powersync @powersync-bridge/powersync BridgeDriver over @powersync/common
216
+ ```
217
+
218
+ Design: `ARCHITECTURE.md`. Build brief and worked example: `BUILD-READINESS.md`.
@@ -0,0 +1,198 @@
1
+ // src/freshness.ts
2
+ function streamKey(desc) {
3
+ return `${desc.name}:${desc.params ? JSON.stringify(desc.params) : ""}`;
4
+ }
5
+ var FreshnessTracker = class {
6
+ constructor(driver, clock) {
7
+ this.driver = driver;
8
+ this.clock = clock;
9
+ }
10
+ driver;
11
+ clock;
12
+ sessionConnectAt = null;
13
+ localFreshAt = Number.NEGATIVE_INFINITY;
14
+ prevCompletionAt = null;
15
+ lastDownloadStart = null;
16
+ lastSeenSyncedAt = null;
17
+ lastDownloading = false;
18
+ lastConnected = false;
19
+ lastHasSynced = void 0;
20
+ streamFreshAt = /* @__PURE__ */ new Map();
21
+ streamSeenSyncedAt = /* @__PURE__ */ new Map();
22
+ completions = [];
23
+ completionListeners = /* @__PURE__ */ new Set();
24
+ clearListeners = /* @__PURE__ */ new Set();
25
+ unsubscribe = null;
26
+ /** Call once at engine init and again after every identity swap. */
27
+ start(epochStartedAt) {
28
+ this.stop();
29
+ this.reset();
30
+ const status = this.driver.syncStatus();
31
+ this.lastConnected = status.connected;
32
+ this.lastDownloading = status.downloading;
33
+ this.lastHasSynced = status.hasSynced;
34
+ this.lastSeenSyncedAt = status.lastSyncedAt?.getTime() ?? null;
35
+ if (status.connected) this.sessionConnectAt = epochStartedAt;
36
+ if (status.downloading) {
37
+ this.prevCompletionAt = Math.max(epochStartedAt, this.lastSeenSyncedAt ?? Number.NEGATIVE_INFINITY);
38
+ }
39
+ for (const s of status.syncStreams) {
40
+ if (s.lastSyncedAt) this.streamSeenSyncedAt.set(streamKey(s), s.lastSyncedAt.getTime());
41
+ }
42
+ this.unsubscribe = this.driver.onStatusChanged(() => this.onStatus(this.driver.syncStatus()));
43
+ }
44
+ stop() {
45
+ this.unsubscribe?.();
46
+ this.unsubscribe = null;
47
+ }
48
+ reset() {
49
+ this.sessionConnectAt = null;
50
+ this.localFreshAt = Number.NEGATIVE_INFINITY;
51
+ this.prevCompletionAt = null;
52
+ this.lastDownloadStart = null;
53
+ this.lastSeenSyncedAt = null;
54
+ this.streamFreshAt.clear();
55
+ this.streamSeenSyncedAt.clear();
56
+ this.completions.length = 0;
57
+ }
58
+ get sessionConnectAtMs() {
59
+ return this.sessionConnectAt;
60
+ }
61
+ get localFreshAtMs() {
62
+ return this.localFreshAt;
63
+ }
64
+ streamFreshAtMs(desc) {
65
+ return this.streamFreshAt.get(streamKey(desc)) ?? Number.NEGATIVE_INFINITY;
66
+ }
67
+ /** Freshness for a list: the owning stream's stamp when declared, else the global stamp. */
68
+ freshAtFor(stream) {
69
+ if (!stream) return this.localFreshAt;
70
+ return Math.max(this.streamFreshAtMs(stream), this.localFreshAt);
71
+ }
72
+ /** "Answered" = in-session freshness evidence (R5). */
73
+ isFresh(stream) {
74
+ if (this.sessionConnectAt === null) return false;
75
+ return this.freshAtFor(stream) >= this.sessionConnectAt;
76
+ }
77
+ onCompletion(l) {
78
+ this.completionListeners.add(l);
79
+ return () => this.completionListeners.delete(l);
80
+ }
81
+ onClear(l) {
82
+ this.clearListeners.add(l);
83
+ return () => this.clearListeners.delete(l);
84
+ }
85
+ onStatus(status) {
86
+ const now = this.clock();
87
+ if (status.connected && !this.lastConnected && this.sessionConnectAt === null) {
88
+ this.sessionConnectAt = now;
89
+ }
90
+ this.lastConnected = status.connected;
91
+ if (status.downloading && !this.lastDownloading) this.lastDownloadStart = now;
92
+ this.lastDownloading = status.downloading;
93
+ const syncedAt = status.lastSyncedAt?.getTime() ?? null;
94
+ if (syncedAt !== null && syncedAt !== this.lastSeenSyncedAt) {
95
+ this.recordCompletion(now, null);
96
+ }
97
+ if (syncedAt !== null) this.lastSeenSyncedAt = syncedAt;
98
+ for (const s of status.syncStreams) {
99
+ const key = streamKey(s);
100
+ const at = s.lastSyncedAt?.getTime() ?? null;
101
+ if (at !== null && at !== this.streamSeenSyncedAt.get(key)) {
102
+ this.streamSeenSyncedAt.set(key, at);
103
+ const stamp = this.stampFor(now);
104
+ const prev = this.streamFreshAt.get(key) ?? Number.NEGATIVE_INFINITY;
105
+ this.streamFreshAt.set(key, Math.max(prev, stamp));
106
+ const c = { stamp: Math.max(prev, stamp), completedAt: now, stream: key };
107
+ for (const l of this.completionListeners) l(c);
108
+ }
109
+ }
110
+ if (this.lastHasSynced === true && status.hasSynced !== true) {
111
+ for (const l of this.clearListeners) l();
112
+ }
113
+ this.lastHasSynced = status.hasSynced;
114
+ }
115
+ stampFor(now) {
116
+ const candidates = [];
117
+ if (this.lastDownloadStart !== null && this.lastDownloadStart <= now) candidates.push(this.lastDownloadStart);
118
+ if (this.prevCompletionAt !== null) candidates.push(this.prevCompletionAt);
119
+ if (candidates.length === 0 && this.sessionConnectAt !== null) candidates.push(this.sessionConnectAt);
120
+ if (candidates.length === 0) return Number.NEGATIVE_INFINITY;
121
+ return Math.max(...candidates);
122
+ }
123
+ recordCompletion(now, stream) {
124
+ const stamp = this.stampFor(now);
125
+ this.localFreshAt = Math.max(this.localFreshAt, stamp);
126
+ this.prevCompletionAt = now;
127
+ this.lastDownloadStart = null;
128
+ const c = { stamp: this.localFreshAt, completedAt: now, stream };
129
+ this.completions.push(c);
130
+ for (const l of this.completionListeners) l(c);
131
+ }
132
+ };
133
+
134
+ // src/keyset.ts
135
+ function keyColumns(orderKey) {
136
+ if (typeof orderKey === "string") return [orderKey, "id"];
137
+ return [orderKey[0], orderKey[1]];
138
+ }
139
+ function idOf(row) {
140
+ const r = row;
141
+ if (r == null || r.id === void 0 || r.id === null) {
142
+ throw new Error("powersync-bridge: every row must have an `id`");
143
+ }
144
+ return String(r.id);
145
+ }
146
+ function compareValues(a, b) {
147
+ if (a === b) return 0;
148
+ if (a === null || a === void 0) return 1;
149
+ if (b === null || b === void 0) return -1;
150
+ if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();
151
+ if (typeof a === "number" && typeof b === "number") return a - b;
152
+ if (typeof a === "boolean" && typeof b === "boolean") return Number(a) - Number(b);
153
+ const sa = String(a);
154
+ const sb = String(b);
155
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
156
+ }
157
+ function rowComparator(orderKey, direction = "asc") {
158
+ const [k1, k2] = keyColumns(orderKey);
159
+ const sign = direction === "desc" ? -1 : 1;
160
+ return (a, b) => {
161
+ const c1 = compareValues(a[k1], b[k1]);
162
+ if (c1 !== 0) return c1 * sign;
163
+ return compareValues(a[k2], b[k2]) * sign;
164
+ };
165
+ }
166
+ function cursorOfRow(row, orderKey) {
167
+ const r = row;
168
+ if (typeof orderKey === "string") return r[orderKey];
169
+ return [r[orderKey[0]], r[orderKey[1]]];
170
+ }
171
+ function isAfterCursor(row, cursor, orderKey, direction = "asc") {
172
+ const [k1, k2] = keyColumns(orderKey);
173
+ const r = row;
174
+ const sign = direction === "desc" ? -1 : 1;
175
+ const [c1, c2] = typeof orderKey === "string" ? [cursor, void 0] : cursor;
176
+ const d1 = compareValues(r[k1], c1) * sign;
177
+ if (d1 !== 0) return d1 > 0;
178
+ if (c2 === void 0) return false;
179
+ return compareValues(r[k2], c2) * sign > 0;
180
+ }
181
+ function toBase64(s) {
182
+ if (typeof btoa === "function") return btoa(unescape(encodeURIComponent(s)));
183
+ return Buffer.from(s, "utf8").toString("base64");
184
+ }
185
+ function fromBase64(s) {
186
+ if (typeof atob === "function") return decodeURIComponent(escape(atob(s)));
187
+ return Buffer.from(s, "base64").toString("utf8");
188
+ }
189
+ function encodeCursor(cursor) {
190
+ return toBase64(JSON.stringify(cursor));
191
+ }
192
+ function decodeCursor(opaque) {
193
+ return JSON.parse(fromBase64(opaque));
194
+ }
195
+
196
+ export { FreshnessTracker, cursorOfRow, decodeCursor, encodeCursor, idOf, isAfterCursor, keyColumns, rowComparator, streamKey };
197
+ //# sourceMappingURL=chunk-TANEBEGU.js.map
198
+ //# sourceMappingURL=chunk-TANEBEGU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/freshness.ts","../src/keyset.ts"],"names":[],"mappings":";AAYO,SAAS,UAAU,IAAA,EAAiC;AACzD,EAAA,OAAO,CAAA,EAAG,IAAA,CAAK,IAAI,CAAA,CAAA,EAAI,IAAA,CAAK,MAAA,GAAS,IAAA,CAAK,SAAA,CAAU,IAAA,CAAK,MAAM,CAAA,GAAI,EAAE,CAAA,CAAA;AACvE;AAUO,IAAM,mBAAN,MAAuB;AAAA,EAgB5B,WAAA,CACmB,QACA,KAAA,EACjB;AAFiB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAAA,EAChB;AAAA,EAFgB,MAAA;AAAA,EACA,KAAA;AAAA,EAjBX,gBAAA,GAAkC,IAAA;AAAA,EAClC,eAAe,MAAA,CAAO,iBAAA;AAAA,EACtB,gBAAA,GAAkC,IAAA;AAAA,EAClC,iBAAA,GAAmC,IAAA;AAAA,EACnC,gBAAA,GAAkC,IAAA;AAAA,EAClC,eAAA,GAAkB,KAAA;AAAA,EAClB,aAAA,GAAgB,KAAA;AAAA,EAChB,aAAA,GAAqC,MAAA;AAAA,EAC5B,aAAA,uBAAoB,GAAA,EAAoB;AAAA,EACxC,kBAAA,uBAAyB,GAAA,EAAoB;AAAA,EAC7C,cAAsC,EAAC;AAAA,EACvC,mBAAA,uBAA0B,GAAA,EAAuC;AAAA,EACjE,cAAA,uBAAqB,GAAA,EAAgB;AAAA,EAC9C,WAAA,GAAmC,IAAA;AAAA;AAAA,EAQ3C,MAAM,cAAA,EAA8B;AAClC,IAAA,IAAA,CAAK,IAAA,EAAK;AACV,IAAA,IAAA,CAAK,KAAA,EAAM;AACX,IAAA,MAAM,MAAA,GAAS,IAAA,CAAK,MAAA,CAAO,UAAA,EAAW;AACtC,IAAA,IAAA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a,MAAA,EAA+B;AAC1D,EAAA,OAAO,QAAA,CAAS,IAAA,CAAK,SAAA,CAAU,MAAM,CAAC,CAAA;AACxC;AAEO,SAAS,aAAgB,MAAA,EAAyB;AACvD,EAAA,OAAO,IAAA,CAAK,KAAA,CAAM,UAAA,CAAW,MAAM,CAAC,CAAA;AACtC","file":"chunk-TANEBEGU.js","sourcesContent":["import type { BridgeDriver, StreamDescription, SyncStatusView } from './types';\n\nexport type Clock = () => number;\n\nexport interface CheckpointCompletion {\n /** Lower-bound stamp of the checkpoint's data position (download start), ms. */\n readonly stamp: number;\n readonly completedAt: number;\n /** Stream this completion was observed on; null for the global status. */\n readonly stream: string | null;\n}\n\nexport function streamKey(desc: StreamDescription): string {\n return `${desc.name}:${desc.params ? JSON.stringify(desc.params) : ''}`;\n}\n\n/**\n * Session-scoped, monotonic, transition-independent freshness (§5.2, R3/R5).\n *\n * stamp(checkpoint_n) = max(observed download start ≤ its completion,\n * completion time of checkpoint n−1,\n * sessionConnectAt when no other bound exists)\n * localFreshAt = max(previous, stamp) — a null observation never lowers it.\n */\nexport class FreshnessTracker {\n private sessionConnectAt: number | null = null;\n private localFreshAt = Number.NEGATIVE_INFINITY;\n private prevCompletionAt: number | null = null;\n private lastDownloadStart: number | null = null;\n private lastSeenSyncedAt: number | null = null;\n private lastDownloading = false;\n private lastConnected = false;\n private lastHasSynced: boolean | undefined = undefined;\n private readonly streamFreshAt = new Map<string, number>();\n private readonly streamSeenSyncedAt = new Map<string, number>();\n private readonly completions: CheckpointCompletion[] = [];\n private readonly completionListeners = new Set<(c: CheckpointCompletion) => void>();\n private readonly clearListeners = new Set<() => void>();\n private unsubscribe: (() => void) | null = null;\n\n constructor(\n private readonly driver: BridgeDriver,\n private readonly clock: Clock,\n ) {}\n\n /** Call once at engine init and again after every identity swap. */\n start(epochStartedAt: number): void {\n this.stop();\n this.reset();\n const status = this.driver.syncStatus();\n this.lastConnected = status.connected;\n this.lastDownloading = status.downloading;\n this.lastHasSynced = status.hasSynced;\n this.lastSeenSyncedAt = status.lastSyncedAt?.getTime() ?? null;\n if (status.connected) this.sessionConnectAt = epochStartedAt;\n // Boot mid-download: provisional bound for the FIRST completion, never applied to localFreshAt now.\n if (status.downloading) {\n this.prevCompletionAt = Math.max(epochStartedAt, this.lastSeenSyncedAt ?? Number.NEGATIVE_INFINITY);\n }\n for (const s of status.syncStreams) {\n if (s.lastSyncedAt) this.streamSeenSyncedAt.set(streamKey(s), s.lastSyncedAt.getTime());\n }\n this.unsubscribe = this.driver.onStatusChanged(() => this.onStatus(this.driver.syncStatus()));\n }\n\n stop(): void {\n this.unsubscribe?.();\n this.unsubscribe = null;\n }\n\n private reset(): void {\n this.sessionConnectAt = null;\n this.localFreshAt = Number.NEGATIVE_INFINITY;\n this.prevCompletionAt = null;\n this.lastDownloadStart = null;\n this.lastSeenSyncedAt = null;\n this.streamFreshAt.clear();\n this.streamSeenSyncedAt.clear();\n this.completions.length = 0;\n }\n\n get sessionConnectAtMs(): number | null {\n return this.sessionConnectAt;\n }\n\n get localFreshAtMs(): number {\n return this.localFreshAt;\n }\n\n streamFreshAtMs(desc: StreamDescription): number {\n return this.streamFreshAt.get(streamKey(desc)) ?? Number.NEGATIVE_INFINITY;\n }\n\n /** Freshness for a list: the owning stream's stamp when declared, else the global stamp. */\n freshAtFor(stream: StreamDescription | undefined): number {\n if (!stream) return this.localFreshAt;\n return Math.max(this.streamFreshAtMs(stream), this.localFreshAt);\n }\n\n /** \"Answered\" = in-session freshness evidence (R5). */\n isFresh(stream: StreamDescription | undefined): boolean {\n if (this.sessionConnectAt === null) return false;\n return this.freshAtFor(stream) >= this.sessionConnectAt;\n }\n\n onCompletion(l: (c: CheckpointCompletion) => void): () => void {\n this.completionListeners.add(l);\n return () => this.completionListeners.delete(l);\n }\n\n onClear(l: () => void): () => void {\n this.clearListeners.add(l);\n return () => this.clearListeners.delete(l);\n }\n\n private onStatus(status: SyncStatusView): void {\n const now = this.clock();\n\n if (status.connected && !this.lastConnected && this.sessionConnectAt === null) {\n this.sessionConnectAt = now; // FIRST connect of the epoch — never per reconnect (R5)\n }\n this.lastConnected = status.connected;\n\n if (status.downloading && !this.lastDownloading) this.lastDownloadStart = now;\n this.lastDownloading = status.downloading;\n\n const syncedAt = status.lastSyncedAt?.getTime() ?? null;\n if (syncedAt !== null && syncedAt !== this.lastSeenSyncedAt) {\n this.recordCompletion(now, null);\n }\n if (syncedAt !== null) this.lastSeenSyncedAt = syncedAt; // null never lowers anything (R5)\n\n for (const s of status.syncStreams) {\n const key = streamKey(s);\n const at = s.lastSyncedAt?.getTime() ?? null;\n if (at !== null && at !== this.streamSeenSyncedAt.get(key)) {\n this.streamSeenSyncedAt.set(key, at);\n const stamp = this.stampFor(now);\n const prev = this.streamFreshAt.get(key) ?? Number.NEGATIVE_INFINITY;\n this.streamFreshAt.set(key, Math.max(prev, stamp));\n const c: CheckpointCompletion = { stamp: Math.max(prev, stamp), completedAt: now, stream: key };\n for (const l of this.completionListeners) l(c);\n }\n }\n\n if (this.lastHasSynced === true && status.hasSynced !== true) {\n for (const l of this.clearListeners) l();\n }\n this.lastHasSynced = status.hasSynced;\n }\n\n private stampFor(now: number): number {\n const candidates: number[] = [];\n if (this.lastDownloadStart !== null && this.lastDownloadStart <= now) candidates.push(this.lastDownloadStart);\n if (this.prevCompletionAt !== null) candidates.push(this.prevCompletionAt);\n if (candidates.length === 0 && this.sessionConnectAt !== null) candidates.push(this.sessionConnectAt);\n if (candidates.length === 0) return Number.NEGATIVE_INFINITY;\n return Math.max(...candidates);\n }\n\n private recordCompletion(now: number, stream: string | null): void {\n const stamp = this.stampFor(now);\n this.localFreshAt = Math.max(this.localFreshAt, stamp);\n this.prevCompletionAt = now;\n this.lastDownloadStart = null; // consumed; the next stamp derives from this completion\n const c: CheckpointCompletion = { stamp: this.localFreshAt, completedAt: now, stream };\n this.completions.push(c);\n for (const l of this.completionListeners) l(c);\n }\n}\n","import type { CursorOf, KeyOf, OpaqueCursor, OrderKey, SortDirection } from './types';\n\n/** `id` is always the implicit tiebreaker (§8.3): a scalar key K is treated as [K, 'id']. */\nexport function keyColumns<T>(orderKey: OrderKey<T>): [KeyOf<T>, KeyOf<T>] {\n if (typeof orderKey === 'string') return [orderKey, 'id' as KeyOf<T>];\n return [orderKey[0], orderKey[1]];\n}\n\nexport function idOf(row: unknown): string {\n const r = row as { id?: unknown };\n if (r == null || r.id === undefined || r.id === null) {\n throw new Error('powersync-bridge: every row must have an `id`');\n }\n return String(r.id);\n}\n\nfunction compareValues(a: unknown, b: unknown): number {\n if (a === b) return 0;\n if (a === null || a === undefined) return 1; // nulls last\n if (b === null || b === undefined) return -1;\n if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();\n if (typeof a === 'number' && typeof b === 'number') return a - b;\n if (typeof a === 'boolean' && typeof b === 'boolean') return Number(a) - Number(b);\n const sa = String(a);\n const sb = String(b);\n return sa < sb ? -1 : sa > sb ? 1 : 0;\n}\n\n/** Comparator over rows for the declared order key + direction. Byte order for strings (SQLite BINARY). */\nexport function rowComparator<T>(orderKey: OrderKey<T>, direction: SortDirection = 'asc'): (a: T, b: T) => number {\n const [k1, k2] = keyColumns(orderKey);\n const sign = direction === 'desc' ? -1 : 1;\n return (a, b) => {\n const c1 = compareValues((a as Record<string, unknown>)[k1], (b as Record<string, unknown>)[k1]);\n if (c1 !== 0) return c1 * sign;\n return compareValues((a as Record<string, unknown>)[k2], (b as Record<string, unknown>)[k2]) * sign;\n };\n}\n\n/** The cursor a row yields, in the definition's cursor shape. */\nexport function cursorOfRow<T, K extends OrderKey<T>>(row: T, orderKey: K): CursorOf<T, K> {\n const r = row as Record<string, unknown>;\n if (typeof orderKey === 'string') return r[orderKey] as CursorOf<T, K>;\n return [r[orderKey[0]], r[orderKey[1]]] as CursorOf<T, K>;\n}\n\n/** Whether `row` sorts strictly after `cursor` in the list's order (i.e. is \"beyond\" it). */\nexport function isAfterCursor<T, K extends OrderKey<T>>(\n row: T,\n cursor: CursorOf<T, K>,\n orderKey: K,\n direction: SortDirection = 'asc',\n): boolean {\n const [k1, k2] = keyColumns(orderKey);\n const r = row as Record<string, unknown>;\n const sign = direction === 'desc' ? -1 : 1;\n const [c1, c2] = typeof orderKey === 'string' ? [cursor, undefined] : (cursor as [unknown, unknown]);\n const d1 = compareValues(r[k1], c1) * sign;\n if (d1 !== 0) return d1 > 0;\n if (c2 === undefined) return false;\n return compareValues(r[k2], c2) * sign > 0;\n}\n\nfunction toBase64(s: string): string {\n if (typeof btoa === 'function') return btoa(unescape(encodeURIComponent(s)));\n return Buffer.from(s, 'utf8').toString('base64');\n}\n\nfunction fromBase64(s: string): string {\n if (typeof atob === 'function') return decodeURIComponent(escape(atob(s)));\n return Buffer.from(s, 'base64').toString('utf8');\n}\n\nexport function encodeCursor(cursor: unknown): OpaqueCursor {\n return toBase64(JSON.stringify(cursor)) as OpaqueCursor;\n}\n\nexport function decodeCursor<C>(opaque: OpaqueCursor): C {\n return JSON.parse(fromBase64(opaque)) as C;\n}\n"]}