@phibac/sdk 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 +202 -0
- package/README.md +53 -2
- package/dist/auth.d.ts +104 -0
- package/dist/auth.js +343 -0
- package/dist/auth.js.map +1 -0
- package/dist/brand.d.ts +7 -0
- package/dist/brand.js +8 -0
- package/dist/brand.js.map +1 -0
- package/dist/cache.d.ts +170 -0
- package/dist/cache.js +293 -0
- package/dist/cache.js.map +1 -0
- package/dist/collection.d.ts +119 -0
- package/dist/collection.js +511 -0
- package/dist/collection.js.map +1 -0
- package/dist/dpop.d.ts +50 -0
- package/dist/dpop.js +105 -0
- package/dist/dpop.js.map +1 -0
- package/dist/errors.d.ts +22 -0
- package/dist/errors.js +55 -0
- package/dist/errors.js.map +1 -0
- package/dist/files.d.ts +25 -0
- package/dist/files.js +65 -0
- package/dist/files.js.map +1 -0
- package/dist/http.d.ts +53 -0
- package/dist/http.js +130 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +90 -0
- package/dist/index.js +209 -0
- package/dist/index.js.map +1 -0
- package/dist/live.d.ts +116 -0
- package/dist/live.js +448 -0
- package/dist/live.js.map +1 -0
- package/dist/queue.d.ts +103 -0
- package/dist/queue.js +397 -0
- package/dist/queue.js.map +1 -0
- package/package.json +45 -4
- package/src/auth.ts +371 -0
- package/src/brand.ts +8 -0
- package/src/cache.ts +379 -0
- package/src/collection.ts +533 -0
- package/src/dpop.ts +132 -0
- package/src/errors.ts +61 -0
- package/src/files.ts +60 -0
- package/src/http.ts +154 -0
- package/src/index.ts +238 -0
- package/src/live.ts +434 -0
- package/src/queue.ts +419 -0
package/src/cache.ts
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
// The local cache: records and the offline write queue in IndexedDB, so
|
|
2
|
+
// reads are instant and writes work offline. Everything is partitioned by
|
|
3
|
+
// server origin, app and user, so another user signing in on the same
|
|
4
|
+
// browser never sees the previous user's records.
|
|
5
|
+
import { openDB, type DBSchema, type IDBPDatabase, type IDBPTransaction } from "idb";
|
|
6
|
+
import type { PbRecord, QueuedOp } from "./index.js";
|
|
7
|
+
|
|
8
|
+
// ---- identifiers ----
|
|
9
|
+
|
|
10
|
+
let lastMs = 0;
|
|
11
|
+
let lastSeq = 0;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* uuidv7 returns a new lower-case UUIDv7 (RFC 9562): a 48-bit Unix
|
|
15
|
+
* millisecond timestamp, version 7, 12 bits of rand_a used as a counter so
|
|
16
|
+
* IDs made in the same millisecond still sort in creation order, the RFC
|
|
17
|
+
* 4122 variant, and 62 random bits from crypto.getRandomValues.
|
|
18
|
+
*/
|
|
19
|
+
export function uuidv7(): string {
|
|
20
|
+
const b = crypto.getRandomValues(new Uint8Array(16));
|
|
21
|
+
let ms = Date.now();
|
|
22
|
+
let seq: number;
|
|
23
|
+
if (ms <= lastMs) {
|
|
24
|
+
ms = lastMs;
|
|
25
|
+
seq = lastSeq + 1;
|
|
26
|
+
if (seq > 0xfff) {
|
|
27
|
+
ms++;
|
|
28
|
+
seq = 0;
|
|
29
|
+
}
|
|
30
|
+
} else {
|
|
31
|
+
seq = (b[6]! << 4) & 0x7ff; // random start, leaving room to count up
|
|
32
|
+
}
|
|
33
|
+
lastMs = ms;
|
|
34
|
+
lastSeq = seq;
|
|
35
|
+
for (let i = 5; i >= 0; i--) {
|
|
36
|
+
b[i] = ms % 256;
|
|
37
|
+
ms = Math.floor(ms / 256);
|
|
38
|
+
}
|
|
39
|
+
b[6] = 0x70 | (seq >> 8);
|
|
40
|
+
b[7] = seq & 0xff;
|
|
41
|
+
b[8] = 0x80 | (b[8]! & 0x3f);
|
|
42
|
+
const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
43
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// ---- wire shapes (server/internal/api/records.go) ----
|
|
47
|
+
|
|
48
|
+
export interface WireRecord {
|
|
49
|
+
id: string;
|
|
50
|
+
collection: string;
|
|
51
|
+
rkey: string;
|
|
52
|
+
data: Record<string, unknown>;
|
|
53
|
+
schemaMajor: number;
|
|
54
|
+
schemaMinor: number;
|
|
55
|
+
rev: number;
|
|
56
|
+
createdByApp: string;
|
|
57
|
+
updatedByApp: string;
|
|
58
|
+
createdAt: string;
|
|
59
|
+
updatedAt: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface WireChange {
|
|
63
|
+
rev: number;
|
|
64
|
+
op: string;
|
|
65
|
+
collection: string;
|
|
66
|
+
rkey: string;
|
|
67
|
+
appId: string;
|
|
68
|
+
ts: string;
|
|
69
|
+
record: WireRecord | null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ---- stored shapes ----
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* CacheEntry is one record as this device knows it. server is the last
|
|
76
|
+
* server state seen (null when the server never had it or it is hidden),
|
|
77
|
+
* rev the highest server revision seen for it, deleted whether a server
|
|
78
|
+
* delete was seen (record keys are never reused by creates; a deleted
|
|
79
|
+
* record comes back only with a newer server state, when the user restores
|
|
80
|
+
* it from its history). local is the state with this device's queued writes
|
|
81
|
+
* applied on top of server (data null = deleted locally); it is null when
|
|
82
|
+
* nothing is queued for the record.
|
|
83
|
+
*/
|
|
84
|
+
export interface CacheEntry {
|
|
85
|
+
part: string;
|
|
86
|
+
collection: string;
|
|
87
|
+
rkey: string;
|
|
88
|
+
server: WireRecord | null;
|
|
89
|
+
rev: number;
|
|
90
|
+
deleted: boolean;
|
|
91
|
+
local: LocalState | null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface LocalState {
|
|
95
|
+
data: Record<string, unknown> | null;
|
|
96
|
+
createdAt: string;
|
|
97
|
+
updatedAt: string;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** StoredOp is a queued write; seq (auto-increment) is the queue order. */
|
|
101
|
+
export interface StoredOp {
|
|
102
|
+
seq?: number;
|
|
103
|
+
part: string;
|
|
104
|
+
op: QueuedOp;
|
|
105
|
+
/** When the write was made on this device (RFC 3339). */
|
|
106
|
+
at: string;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
interface CacheDB extends DBSchema {
|
|
110
|
+
records: { key: [string, string, string]; value: CacheEntry; indexes: { coll: [string, string] } };
|
|
111
|
+
queue: { key: number; value: StoredOp; indexes: { part: string; rec: [string, string, string] } };
|
|
112
|
+
meta: { key: [string, string]; value: { part: string; key: string; value: number } };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
type Stores = ("records" | "queue" | "meta")[];
|
|
116
|
+
type Tx = IDBPTransaction<CacheDB, Stores, "readwrite">;
|
|
117
|
+
|
|
118
|
+
/** The cache's IndexedDB database, separate from the sign-in database "pb". */
|
|
119
|
+
export const CACHE_DB = "pb-cache";
|
|
120
|
+
const CACHE_DB_VERSION = 1;
|
|
121
|
+
|
|
122
|
+
// ---- state helpers ----
|
|
123
|
+
|
|
124
|
+
/** merge applies patch to base shallowly; null removes a key, undefined is ignored. */
|
|
125
|
+
export function merge(base: Record<string, unknown>, patch: Record<string, unknown>): Record<string, unknown> {
|
|
126
|
+
const out = { ...base };
|
|
127
|
+
for (const [k, v] of Object.entries(patch)) {
|
|
128
|
+
if (v === null) delete out[k];
|
|
129
|
+
else if (v !== undefined) out[k] = v;
|
|
130
|
+
}
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* fold computes the local state: ops (this record's queued writes, in
|
|
136
|
+
* order) applied to the server state. null when nothing is queued.
|
|
137
|
+
*/
|
|
138
|
+
export function fold(server: WireRecord | null, deleted: boolean, ops: StoredOp[]): LocalState | null {
|
|
139
|
+
if (ops.length === 0) return null;
|
|
140
|
+
let data: Record<string, unknown> | null = server && !deleted ? server.data : null;
|
|
141
|
+
let createdAt = server?.createdAt ?? ops[0]!.at;
|
|
142
|
+
let updatedAt = server?.updatedAt ?? ops[0]!.at;
|
|
143
|
+
for (const s of ops) {
|
|
144
|
+
const input = (s.op.input.data ?? {}) as Record<string, unknown>;
|
|
145
|
+
if (s.op.kind === "create") {
|
|
146
|
+
data = { ...input };
|
|
147
|
+
createdAt = s.at;
|
|
148
|
+
} else if (s.op.kind === "update") {
|
|
149
|
+
// An update of a record the server deleted (and no queued create)
|
|
150
|
+
// leaves no record, not one made of the patch alone.
|
|
151
|
+
data = data === null ? null : merge(data, input);
|
|
152
|
+
} else {
|
|
153
|
+
data = null;
|
|
154
|
+
}
|
|
155
|
+
updatedAt = s.at;
|
|
156
|
+
}
|
|
157
|
+
return { data, createdAt, updatedAt };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** recordId is the global record ID pb://<userId>/<collection>/<rkey>. */
|
|
161
|
+
export function recordId(userId: string, collection: string, rkey: string): string {
|
|
162
|
+
return `pb://${userId}/${collection}/${rkey}`;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* view is what the app sees of an entry: the local state with status
|
|
167
|
+
* "pending" while writes are queued (rev = the server rev it is based on,
|
|
168
|
+
* 0 for a new record), else the server state "synced"; null when the
|
|
169
|
+
* record is deleted or unknown.
|
|
170
|
+
*/
|
|
171
|
+
export function view<T>(e: CacheEntry | undefined, userId: string): PbRecord<T> | null {
|
|
172
|
+
if (!e) return null;
|
|
173
|
+
const id = recordId(userId, e.collection, e.rkey);
|
|
174
|
+
if (e.local) {
|
|
175
|
+
if (e.local.data === null) return null;
|
|
176
|
+
return {
|
|
177
|
+
id,
|
|
178
|
+
collection: e.collection,
|
|
179
|
+
rkey: e.rkey,
|
|
180
|
+
data: e.local.data as T,
|
|
181
|
+
rev: e.server?.rev ?? 0,
|
|
182
|
+
status: "pending",
|
|
183
|
+
createdAt: e.local.createdAt,
|
|
184
|
+
updatedAt: e.local.updatedAt,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
if (!e.server || e.deleted) return null;
|
|
188
|
+
const s = e.server;
|
|
189
|
+
return { id, collection: e.collection, rkey: e.rkey, data: s.data as T, rev: s.rev, status: "synced", createdAt: s.createdAt, updatedAt: s.updatedAt };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** opRecordKey identifies the record an op writes. */
|
|
193
|
+
export const opKey = (op: QueuedOp) => `${op.collection}\u0000${op.rkey}`;
|
|
194
|
+
|
|
195
|
+
// ---- the cache ----
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Cache is one partition (server origin, app, user) of the cache database.
|
|
199
|
+
* It keeps one connection open until close(); onChange is called with the
|
|
200
|
+
* collections whose records changed after every committed write.
|
|
201
|
+
*/
|
|
202
|
+
export class Cache {
|
|
203
|
+
onChange: (collections: Set<string>) => void = () => {};
|
|
204
|
+
|
|
205
|
+
private constructor(
|
|
206
|
+
private readonly db: IDBPDatabase<CacheDB>,
|
|
207
|
+
readonly part: string,
|
|
208
|
+
) {
|
|
209
|
+
// Let a newer version of the SDK in another tab upgrade the database.
|
|
210
|
+
db.addEventListener("versionchange", () => db.close());
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
static async open(part: string): Promise<Cache> {
|
|
214
|
+
const db = await openDB<CacheDB>(CACHE_DB, CACHE_DB_VERSION, {
|
|
215
|
+
upgrade(db) {
|
|
216
|
+
const records = db.createObjectStore("records", { keyPath: ["part", "collection", "rkey"] });
|
|
217
|
+
records.createIndex("coll", ["part", "collection"]);
|
|
218
|
+
const queue = db.createObjectStore("queue", { keyPath: "seq", autoIncrement: true });
|
|
219
|
+
queue.createIndex("part", "part");
|
|
220
|
+
queue.createIndex("rec", ["part", "op.collection", "op.rkey"]);
|
|
221
|
+
db.createObjectStore("meta", { keyPath: ["part", "key"] });
|
|
222
|
+
},
|
|
223
|
+
});
|
|
224
|
+
return new Cache(db, part);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
close(): void {
|
|
228
|
+
this.db.close();
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ---- reads ----
|
|
232
|
+
|
|
233
|
+
async entry(collection: string, rkey: string): Promise<CacheEntry | undefined> {
|
|
234
|
+
return this.db.get("records", [this.part, collection, rkey]);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
async entries(collection: string): Promise<CacheEntry[]> {
|
|
238
|
+
return this.db.getAllFromIndex("records", "coll", [this.part, collection]);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** queued returns this partition's queued writes in order. */
|
|
242
|
+
async queued(): Promise<StoredOp[]> {
|
|
243
|
+
return this.db.getAllFromIndex("queue", "part", this.part);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async queueLength(): Promise<number> {
|
|
247
|
+
return this.db.countFromIndex("queue", "part", this.part);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async lastRev(collection: string): Promise<number> {
|
|
251
|
+
return (await this.db.get("meta", [this.part, `rev:${collection}`]))?.value ?? 0;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async setLastRev(collection: string, rev: number): Promise<void> {
|
|
255
|
+
await this.db.put("meta", { part: this.part, key: `rev:${collection}`, value: rev });
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// ---- writes ----
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* write runs fn in one readwrite transaction over all stores and reports
|
|
262
|
+
* the collections fn marked as changed once it has committed.
|
|
263
|
+
*/
|
|
264
|
+
async write<R>(fn: (w: Writer) => Promise<R>): Promise<R> {
|
|
265
|
+
const tx = this.db.transaction(["records", "queue", "meta"], "readwrite");
|
|
266
|
+
const w = new Writer(tx, this.part);
|
|
267
|
+
let out: R;
|
|
268
|
+
try {
|
|
269
|
+
out = await fn(w);
|
|
270
|
+
} catch (e) {
|
|
271
|
+
try {
|
|
272
|
+
tx.abort();
|
|
273
|
+
} catch {
|
|
274
|
+
// already finished
|
|
275
|
+
}
|
|
276
|
+
await tx.done.catch(() => undefined);
|
|
277
|
+
throw e;
|
|
278
|
+
}
|
|
279
|
+
await tx.done;
|
|
280
|
+
if (w.changed.size > 0) this.onChange(w.changed);
|
|
281
|
+
return out;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** clear removes this partition's records, queue and positions. */
|
|
285
|
+
async clear(): Promise<void> {
|
|
286
|
+
await this.write(async (w) => {
|
|
287
|
+
const tx = w.tx;
|
|
288
|
+
for (const k of await tx.objectStore("records").getAllKeys()) {
|
|
289
|
+
if (k[0] === this.part) {
|
|
290
|
+
w.changed.add(k[1]);
|
|
291
|
+
await tx.objectStore("records").delete(k);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
for (const k of await tx.objectStore("queue").index("part").getAllKeys(this.part)) {
|
|
295
|
+
await tx.objectStore("queue").delete(k);
|
|
296
|
+
}
|
|
297
|
+
for (const k of await tx.objectStore("meta").getAllKeys()) {
|
|
298
|
+
if (k[0] === this.part) await tx.objectStore("meta").delete(k);
|
|
299
|
+
}
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Writer is the cache inside one transaction. */
|
|
305
|
+
export class Writer {
|
|
306
|
+
readonly changed = new Set<string>();
|
|
307
|
+
|
|
308
|
+
constructor(
|
|
309
|
+
readonly tx: Tx,
|
|
310
|
+
private readonly part: string,
|
|
311
|
+
) {}
|
|
312
|
+
|
|
313
|
+
entry(collection: string, rkey: string): Promise<CacheEntry | undefined> {
|
|
314
|
+
return this.tx.objectStore("records").get([this.part, collection, rkey]);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** newEntry is an entry for a record this device has never seen. */
|
|
318
|
+
newEntry(collection: string, rkey: string): CacheEntry {
|
|
319
|
+
return { part: this.part, collection, rkey, server: null, rev: 0, deleted: false, local: null };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** opsFor returns the queued writes of one record, in order. */
|
|
323
|
+
opsFor(collection: string, rkey: string): Promise<StoredOp[]> {
|
|
324
|
+
return this.tx.objectStore("queue").index("rec").getAll([this.part, collection, rkey]);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* save stores e with its local state recomputed from its queued writes.
|
|
329
|
+
* An entry with nothing to remember (no server state, not deleted,
|
|
330
|
+
* nothing queued) is removed instead.
|
|
331
|
+
*/
|
|
332
|
+
async save(e: CacheEntry): Promise<void> {
|
|
333
|
+
e.local = fold(e.server, e.deleted, await this.opsFor(e.collection, e.rkey));
|
|
334
|
+
this.changed.add(e.collection);
|
|
335
|
+
if (!e.server && !e.deleted && !e.local && e.rev === 0) {
|
|
336
|
+
await this.tx.objectStore("records").delete([this.part, e.collection, e.rkey]);
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
await this.tx.objectStore("records").put(e);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
async enqueue(op: QueuedOp, at: string): Promise<void> {
|
|
343
|
+
await this.tx.objectStore("queue").add({ part: this.part, op, at });
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async dequeue(seq: number): Promise<void> {
|
|
347
|
+
await this.tx.objectStore("queue").delete(seq);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* applyServer records a server state of a record (from a write result,
|
|
352
|
+
* a query, the changes feed or the live connection) if it is newer than
|
|
353
|
+
* what the cache has. record null means the record is deleted on the
|
|
354
|
+
* server. versions, when given, hides records of other majors. Queued
|
|
355
|
+
* local writes stay applied on top. A record hidden by versions is taken
|
|
356
|
+
* again at the same rev (the versions read may have widened). A deleted
|
|
357
|
+
* record is taken again only from a newer state (a restore from its
|
|
358
|
+
* history); a change at or below the rev already seen never brings it
|
|
359
|
+
* back. Returns whether anything changed.
|
|
360
|
+
*/
|
|
361
|
+
async applyServer(collection: string, rkey: string, rev: number, record: WireRecord | null, versions?: number[]): Promise<boolean> {
|
|
362
|
+
const e = (await this.entry(collection, rkey)) ?? this.newEntry(collection, rkey);
|
|
363
|
+
if (rev < e.rev || (rev === e.rev && (e.deleted || e.server !== null))) return false;
|
|
364
|
+
if (rev === e.rev && (record === null || (versions && !versions.includes(record.schemaMajor)))) return false;
|
|
365
|
+
e.rev = rev;
|
|
366
|
+
if (record === null) {
|
|
367
|
+
e.deleted = true;
|
|
368
|
+
e.server = null;
|
|
369
|
+
} else if (versions && !versions.includes(record.schemaMajor)) {
|
|
370
|
+
e.deleted = false;
|
|
371
|
+
e.server = null;
|
|
372
|
+
} else {
|
|
373
|
+
e.deleted = false;
|
|
374
|
+
e.server = record;
|
|
375
|
+
}
|
|
376
|
+
await this.save(e);
|
|
377
|
+
return true;
|
|
378
|
+
}
|
|
379
|
+
}
|