@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/dist/auth.js ADDED
@@ -0,0 +1,343 @@
1
+ // Signing the user in: the authorization code flow with PKCE (S256) in a
2
+ // popup on the server's domain, the code handed back with postMessage
3
+ // (response_mode web_message), and DPoP-bound tokens. The access token
4
+ // lives in memory only; the refresh token is kept in IndexedDB. Nothing is
5
+ // written to localStorage or sessionStorage, and no token is put in a URL
6
+ // or logged.
7
+ import { BRAND } from "./brand.js";
8
+ import { createProof, getOrCreateKey, openPbDB, randomToken, sha256 } from "./dpop.js";
9
+ import { PbError, SIGN_IN_HINT } from "./errors.js";
10
+ import { attempt, clockError, readJSON } from "./http.js";
11
+ /** Refresh the access token when it has less than this left. */
12
+ const REFRESH_MARGIN_MS = 60_000;
13
+ /** How often to check whether the user closed the sign-in popup. */
14
+ const POPUP_POLL_MS = 500;
15
+ export const POPUP_NAME = `${BRAND}-sign-in`;
16
+ export const POPUP_FEATURES = "popup,width=480,height=720";
17
+ /** The type of the message the server's done page posts (server/internal/auth/oauth.go). */
18
+ const AUTH_MESSAGE_TYPE = "pb:auth";
19
+ /** popupBlocked is the error for a sign-in popup the browser did not open. */
20
+ export function popupBlocked() {
21
+ return new PbError("popup_blocked", `The browser blocked the ${BRAND} sign-in popup.`, "Call connect() (or signIn()) directly from a click or key handler, not on page load or after an await, so the browser allows the popup.");
22
+ }
23
+ export class Auth {
24
+ /**
25
+ * Resolves once the stored sign-in (if any) has been loaded from
26
+ * IndexedDB. Read signedIn and userId after `await auth.ready`; until
27
+ * then they are false and null. signIn, accessToken and signOut wait for
28
+ * it themselves.
29
+ */
30
+ ready;
31
+ /**
32
+ * Milliseconds to add to the device clock for DPoP proofs, learnt from
33
+ * the server's serverTime when it refuses a proof's iat.
34
+ */
35
+ clockOffsetMs = 0;
36
+ app;
37
+ base;
38
+ origin;
39
+ tokenKey;
40
+ lockName;
41
+ _signedIn = false;
42
+ _userId = null;
43
+ access = null;
44
+ refreshing = null;
45
+ signingIn = null;
46
+ signInPopup = null;
47
+ keys = null;
48
+ localTail = Promise.resolve();
49
+ constructor(opts) {
50
+ this.app = opts.app;
51
+ this.base = opts.baseUrl.replace(/\/+$/, "");
52
+ this.origin = new URL(this.base).origin;
53
+ this.tokenKey = `${this.origin} ${this.app}`;
54
+ this.lockName = `pb:refresh ${this.origin} ${this.app}`;
55
+ this.ready = this.load();
56
+ }
57
+ /** Whether a refresh token is stored for this app and server (after ready). */
58
+ get signedIn() {
59
+ return this._signedIn;
60
+ }
61
+ /** The signed-in user's ID (u_...), or null. */
62
+ get userId() {
63
+ return this._userId;
64
+ }
65
+ async load() {
66
+ const stored = await this.readStored();
67
+ this._signedIn = stored !== undefined;
68
+ this._userId = stored?.userId ?? null;
69
+ }
70
+ // ---- sign-in ----
71
+ /**
72
+ * signIn opens the sign-in popup on the server and resolves once the user
73
+ * has signed in and connected the app. Call it directly from a click or
74
+ * key handler: the popup is opened before anything is awaited so the
75
+ * browser still sees the user's gesture, as a blank window that is sent
76
+ * to the authorization page once the PKCE challenge (an async SHA-256) is
77
+ * ready. Rejects with popup_blocked, access_denied or sign_in_cancelled.
78
+ * A call while a sign-in is in flight returns that sign-in's promise.
79
+ * popup, when given, is a blank window the caller already opened inside
80
+ * the gesture (connect() does this); it is used instead of opening one.
81
+ */
82
+ signIn(popup) {
83
+ // A second call while a sign-in is in flight shares it: both would
84
+ // otherwise drive the same named popup and the first would fail.
85
+ if (this.signingIn) {
86
+ if (popup && popup !== this.signInPopup)
87
+ popup.close();
88
+ return this.signingIn;
89
+ }
90
+ const run = this.runSignIn(popup);
91
+ this.signingIn = run;
92
+ const clear = () => {
93
+ if (this.signingIn === run)
94
+ this.signingIn = null;
95
+ };
96
+ run.then(clear, clear);
97
+ return run;
98
+ }
99
+ async runSignIn(given) {
100
+ // No await before this line: window.open must run inside the gesture.
101
+ const popup = given ?? window.open("", POPUP_NAME, POPUP_FEATURES);
102
+ if (!popup || popup.closed)
103
+ throw popupBlocked();
104
+ this.signInPopup = popup;
105
+ let code;
106
+ const verifier = randomToken(32);
107
+ try {
108
+ const state = randomToken(16);
109
+ const challenge = await sha256(verifier);
110
+ const q = new URLSearchParams({
111
+ client_id: this.app,
112
+ origin: window.location.origin,
113
+ code_challenge: challenge,
114
+ code_challenge_method: "S256",
115
+ state,
116
+ response_mode: "web_message",
117
+ });
118
+ try {
119
+ popup.location.href = `${this.base}/oauth/authorize?${q}`;
120
+ }
121
+ catch {
122
+ throw new PbError("popup_blocked", `The ${BRAND} sign-in popup could not be sent to the sign-in page.`, "Close any other sign-in window and call connect() again from a click or key handler.");
123
+ }
124
+ // The waiter starts only after navigation succeeded, so no waiter is
125
+ // left behind when it fails. The page's message is delivered as a
126
+ // later task, so it cannot arrive before the listener below exists.
127
+ code = await this.waitForCode(popup, state);
128
+ }
129
+ catch (e) {
130
+ popup.close();
131
+ throw e;
132
+ }
133
+ finally {
134
+ this.signInPopup = null;
135
+ }
136
+ await this.ready;
137
+ const t = await this.tokenRequest({
138
+ grant_type: "authorization_code",
139
+ code,
140
+ code_verifier: verifier,
141
+ client_id: this.app,
142
+ });
143
+ await this.withLock(() => this.save(t));
144
+ }
145
+ /**
146
+ * waitForCode resolves with the code from the first message that comes
147
+ * from the popup, from the server's origin, of the sign-in type and with
148
+ * our state; every other message is ignored. It rejects when the user
149
+ * closes the popup first. The listener and timer are always removed.
150
+ */
151
+ waitForCode(popup, state) {
152
+ return new Promise((resolve, reject) => {
153
+ let closedPolls = 0;
154
+ const onMessage = (ev) => {
155
+ if (ev.origin !== this.origin || ev.source !== popup)
156
+ return;
157
+ const d = ev.data;
158
+ if (typeof d !== "object" || d === null)
159
+ return;
160
+ const m = d;
161
+ if (m.type !== AUTH_MESSAGE_TYPE || m.state !== state)
162
+ return;
163
+ cleanup();
164
+ if (m.error === "access_denied") {
165
+ reject(new PbError("access_denied", `The user did not connect this app to ${BRAND}.`, "Let the user try again from a click when they are ready."));
166
+ }
167
+ else if (typeof m.code === "string" && m.code !== "") {
168
+ resolve(m.code);
169
+ }
170
+ else {
171
+ reject(new PbError(typeof m.error === "string" ? m.error : "invalid_request", `${BRAND} sign-in did not return a code.`, SIGN_IN_HINT));
172
+ }
173
+ };
174
+ // A finished sign-in posts its message and closes the popup at once,
175
+ // so "closed" counts only when seen on two polls in a row: a message
176
+ // already on its way is handled first.
177
+ const timer = setInterval(() => {
178
+ if (!popup.closed)
179
+ return;
180
+ if (++closedPolls < 2)
181
+ return;
182
+ cleanup();
183
+ reject(new PbError("sign_in_cancelled", `The ${BRAND} sign-in window was closed before sign-in finished.`, SIGN_IN_HINT));
184
+ }, POPUP_POLL_MS);
185
+ const cleanup = () => {
186
+ window.removeEventListener("message", onMessage);
187
+ clearInterval(timer);
188
+ };
189
+ window.addEventListener("message", onMessage);
190
+ });
191
+ }
192
+ // ---- tokens ----
193
+ /**
194
+ * accessToken returns an access token valid for at least another 60
195
+ * seconds, refreshing it first when needed. Rejects with unauthorized
196
+ * when the user is not (or no longer) signed in.
197
+ */
198
+ async accessToken() {
199
+ await this.ready;
200
+ const a = this.access;
201
+ if (a && Date.now() < a.expiresAt - REFRESH_MARGIN_MS)
202
+ return a.token;
203
+ return this.refresh();
204
+ }
205
+ /**
206
+ * refresh gets a new access token with the stored refresh token. Callers
207
+ * in this tab share one refresh in flight. When stale (the token a
208
+ * request was refused with) is given and this tab already holds a
209
+ * different valid token, that token is returned instead.
210
+ */
211
+ refresh(stale) {
212
+ const a = this.access;
213
+ if (stale !== undefined && a && a.token !== stale && Date.now() < a.expiresAt - REFRESH_MARGIN_MS) {
214
+ return Promise.resolve(a.token);
215
+ }
216
+ if (!this.refreshing) {
217
+ this.refreshing = this.withLock(() => this.refreshLocked()).finally(() => {
218
+ this.refreshing = null;
219
+ });
220
+ }
221
+ return this.refreshing;
222
+ }
223
+ /**
224
+ * refreshLocked runs while holding the cross-tab lock. It re-reads the
225
+ * refresh token from IndexedDB, because another tab may have rotated it
226
+ * since: presenting a used refresh token revokes the whole session.
227
+ */
228
+ async refreshLocked() {
229
+ await this.ready;
230
+ const stored = await this.readStored();
231
+ if (!stored) {
232
+ this.forget();
233
+ throw new PbError("unauthorized", `Not signed in to ${BRAND}.`, SIGN_IN_HINT);
234
+ }
235
+ let t;
236
+ try {
237
+ t = await this.tokenRequest({ grant_type: "refresh_token", refresh_token: stored.refreshToken, client_id: this.app });
238
+ }
239
+ catch (e) {
240
+ // A refused refresh token (no DPoP reason) means the session is over.
241
+ // A refused proof leaves the refresh token unused, so it is kept.
242
+ if (e instanceof PbError && e.code === "unauthorized" && e.extra.reason === undefined) {
243
+ await this.deleteStored();
244
+ this.forget();
245
+ throw new PbError("unauthorized", `Signed out of ${BRAND}: ${e.message}`, SIGN_IN_HINT, e.extra);
246
+ }
247
+ throw e;
248
+ }
249
+ await this.save(t);
250
+ return t.access_token;
251
+ }
252
+ /**
253
+ * signOut forgets this app's tokens (in memory and IndexedDB). The DPoP
254
+ * key and other apps' sign-ins are kept.
255
+ */
256
+ async signOut() {
257
+ await this.ready;
258
+ await this.withLock(() => this.deleteStored());
259
+ this.forget();
260
+ }
261
+ /** tokenRequest calls the token endpoint, correcting the clock once on dpop_iat. */
262
+ async tokenRequest(body) {
263
+ const url = `${this.base}/oauth/token`;
264
+ let out = await attempt(this, "POST", url, body);
265
+ const serverTime = out.ok ? undefined : clockError(out.err);
266
+ if (serverTime) {
267
+ this.setServerTime(serverTime);
268
+ out = await attempt(this, "POST", url, body);
269
+ }
270
+ if (!out.ok)
271
+ throw out.err;
272
+ const t = (await readJSON(out.res));
273
+ if (!t || typeof t !== "object" || typeof t.access_token !== "string" || typeof t.refresh_token !== "string" ||
274
+ typeof t.expires_in !== "number" || typeof t.user_id !== "string") {
275
+ throw new PbError("internal", `${BRAND} returned an incomplete token response.`, "Check that baseUrl points at the server.");
276
+ }
277
+ return t;
278
+ }
279
+ async save(t) {
280
+ const db = await openPbDB();
281
+ try {
282
+ await db.put("tokens", { refreshToken: t.refresh_token, userId: t.user_id }, this.tokenKey);
283
+ }
284
+ finally {
285
+ db.close();
286
+ }
287
+ this.access = { token: t.access_token, expiresAt: Date.now() + t.expires_in * 1000 };
288
+ this._signedIn = true;
289
+ this._userId = t.user_id;
290
+ }
291
+ forget() {
292
+ this.access = null;
293
+ this._signedIn = false;
294
+ this._userId = null;
295
+ }
296
+ async readStored() {
297
+ const db = await openPbDB();
298
+ try {
299
+ return await db.get("tokens", this.tokenKey);
300
+ }
301
+ finally {
302
+ db.close();
303
+ }
304
+ }
305
+ async deleteStored() {
306
+ const db = await openPbDB();
307
+ try {
308
+ await db.delete("tokens", this.tokenKey);
309
+ }
310
+ finally {
311
+ db.close();
312
+ }
313
+ }
314
+ /**
315
+ * withLock runs fn while holding the refresh lock for this app and
316
+ * server, shared by every tab of the browser through Web Locks.
317
+ */
318
+ withLock(fn) {
319
+ const locks = typeof navigator === "undefined" ? undefined : navigator.locks;
320
+ if (locks)
321
+ return locks.request(this.lockName, fn);
322
+ // Without Web Locks (very old browsers) refreshes are serialised in
323
+ // this tab only; two tabs refreshing at the same moment could then
324
+ // present the same refresh token and end the session.
325
+ const run = this.localTail.then(fn, fn);
326
+ this.localTail = run.catch(() => undefined);
327
+ return run;
328
+ }
329
+ // ---- DPoP ----
330
+ /** proof returns a DPoP proof signed with this browser's key for the server. */
331
+ async proof(method, url, accessToken) {
332
+ if (!this.keys) {
333
+ this.keys = getOrCreateKey(this.base);
334
+ this.keys.catch(() => (this.keys = null));
335
+ }
336
+ return createProof(await this.keys, method, url, accessToken, this.clockOffsetMs);
337
+ }
338
+ /** setServerTime sets the clock offset from the server's serverTime (RFC 3339). */
339
+ setServerTime(serverTime) {
340
+ this.clockOffsetMs = Date.parse(serverTime) - Date.now();
341
+ }
342
+ }
343
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA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AG,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC5C,OAAO,GAAG,CAAC;IACb,CAAC;IAED,iBAAiB;IAEjB,gFAAgF;IAChF,KAAK,CAAC,KAAK,CAAC,MAAc,EAAE,GAAW,EAAE,WAAoB;QAC3D,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YACf,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACtC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC;QAC5C,CAAC;QACD,OAAO,WAAW,CAAC,MAAM,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,WAAW,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC;IACpF,CAAC;IAED,mFAAmF;IACnF,aAAa,CAAC,UAAkB;QAC9B,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAC3D,CAAC;CACF"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * BRAND is the product name shown in user-facing SDK text (error messages
3
+ * and hints). Change it here; never write the name anywhere else.
4
+ */
5
+ export declare const BRAND = "pb";
6
+ /** DEFAULT_BASE_URL is the local development server. */
7
+ export declare const DEFAULT_BASE_URL = "http://localhost:8787";
package/dist/brand.js ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * BRAND is the product name shown in user-facing SDK text (error messages
3
+ * and hints). Change it here; never write the name anywhere else.
4
+ */
5
+ export const BRAND = "pb";
6
+ /** DEFAULT_BASE_URL is the local development server. */
7
+ export const DEFAULT_BASE_URL = "http://localhost:8787";
8
+ //# sourceMappingURL=brand.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"brand.js","sourceRoot":"","sources":["../src/brand.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,IAAI,CAAC;AAE1B,wDAAwD;AACxD,MAAM,CAAC,MAAM,gBAAgB,GAAG,uBAAuB,CAAC"}
@@ -0,0 +1,170 @@
1
+ import { type DBSchema, type IDBPTransaction } from "idb";
2
+ import type { PbRecord, QueuedOp } from "./index.js";
3
+ /**
4
+ * uuidv7 returns a new lower-case UUIDv7 (RFC 9562): a 48-bit Unix
5
+ * millisecond timestamp, version 7, 12 bits of rand_a used as a counter so
6
+ * IDs made in the same millisecond still sort in creation order, the RFC
7
+ * 4122 variant, and 62 random bits from crypto.getRandomValues.
8
+ */
9
+ export declare function uuidv7(): string;
10
+ export interface WireRecord {
11
+ id: string;
12
+ collection: string;
13
+ rkey: string;
14
+ data: Record<string, unknown>;
15
+ schemaMajor: number;
16
+ schemaMinor: number;
17
+ rev: number;
18
+ createdByApp: string;
19
+ updatedByApp: string;
20
+ createdAt: string;
21
+ updatedAt: string;
22
+ }
23
+ export interface WireChange {
24
+ rev: number;
25
+ op: string;
26
+ collection: string;
27
+ rkey: string;
28
+ appId: string;
29
+ ts: string;
30
+ record: WireRecord | null;
31
+ }
32
+ /**
33
+ * CacheEntry is one record as this device knows it. server is the last
34
+ * server state seen (null when the server never had it or it is hidden),
35
+ * rev the highest server revision seen for it, deleted whether a server
36
+ * delete was seen (record keys are never reused by creates; a deleted
37
+ * record comes back only with a newer server state, when the user restores
38
+ * it from its history). local is the state with this device's queued writes
39
+ * applied on top of server (data null = deleted locally); it is null when
40
+ * nothing is queued for the record.
41
+ */
42
+ export interface CacheEntry {
43
+ part: string;
44
+ collection: string;
45
+ rkey: string;
46
+ server: WireRecord | null;
47
+ rev: number;
48
+ deleted: boolean;
49
+ local: LocalState | null;
50
+ }
51
+ export interface LocalState {
52
+ data: Record<string, unknown> | null;
53
+ createdAt: string;
54
+ updatedAt: string;
55
+ }
56
+ /** StoredOp is a queued write; seq (auto-increment) is the queue order. */
57
+ export interface StoredOp {
58
+ seq?: number;
59
+ part: string;
60
+ op: QueuedOp;
61
+ /** When the write was made on this device (RFC 3339). */
62
+ at: string;
63
+ }
64
+ interface CacheDB extends DBSchema {
65
+ records: {
66
+ key: [string, string, string];
67
+ value: CacheEntry;
68
+ indexes: {
69
+ coll: [string, string];
70
+ };
71
+ };
72
+ queue: {
73
+ key: number;
74
+ value: StoredOp;
75
+ indexes: {
76
+ part: string;
77
+ rec: [string, string, string];
78
+ };
79
+ };
80
+ meta: {
81
+ key: [string, string];
82
+ value: {
83
+ part: string;
84
+ key: string;
85
+ value: number;
86
+ };
87
+ };
88
+ }
89
+ type Stores = ("records" | "queue" | "meta")[];
90
+ type Tx = IDBPTransaction<CacheDB, Stores, "readwrite">;
91
+ /** The cache's IndexedDB database, separate from the sign-in database "pb". */
92
+ export declare const CACHE_DB = "pb-cache";
93
+ /** merge applies patch to base shallowly; null removes a key, undefined is ignored. */
94
+ export declare function merge(base: Record<string, unknown>, patch: Record<string, unknown>): Record<string, unknown>;
95
+ /**
96
+ * fold computes the local state: ops (this record's queued writes, in
97
+ * order) applied to the server state. null when nothing is queued.
98
+ */
99
+ export declare function fold(server: WireRecord | null, deleted: boolean, ops: StoredOp[]): LocalState | null;
100
+ /** recordId is the global record ID pb://<userId>/<collection>/<rkey>. */
101
+ export declare function recordId(userId: string, collection: string, rkey: string): string;
102
+ /**
103
+ * view is what the app sees of an entry: the local state with status
104
+ * "pending" while writes are queued (rev = the server rev it is based on,
105
+ * 0 for a new record), else the server state "synced"; null when the
106
+ * record is deleted or unknown.
107
+ */
108
+ export declare function view<T>(e: CacheEntry | undefined, userId: string): PbRecord<T> | null;
109
+ /** opRecordKey identifies the record an op writes. */
110
+ export declare const opKey: (op: QueuedOp) => string;
111
+ /**
112
+ * Cache is one partition (server origin, app, user) of the cache database.
113
+ * It keeps one connection open until close(); onChange is called with the
114
+ * collections whose records changed after every committed write.
115
+ */
116
+ export declare class Cache {
117
+ private readonly db;
118
+ readonly part: string;
119
+ onChange: (collections: Set<string>) => void;
120
+ private constructor();
121
+ static open(part: string): Promise<Cache>;
122
+ close(): void;
123
+ entry(collection: string, rkey: string): Promise<CacheEntry | undefined>;
124
+ entries(collection: string): Promise<CacheEntry[]>;
125
+ /** queued returns this partition's queued writes in order. */
126
+ queued(): Promise<StoredOp[]>;
127
+ queueLength(): Promise<number>;
128
+ lastRev(collection: string): Promise<number>;
129
+ setLastRev(collection: string, rev: number): Promise<void>;
130
+ /**
131
+ * write runs fn in one readwrite transaction over all stores and reports
132
+ * the collections fn marked as changed once it has committed.
133
+ */
134
+ write<R>(fn: (w: Writer) => Promise<R>): Promise<R>;
135
+ /** clear removes this partition's records, queue and positions. */
136
+ clear(): Promise<void>;
137
+ }
138
+ /** Writer is the cache inside one transaction. */
139
+ export declare class Writer {
140
+ readonly tx: Tx;
141
+ private readonly part;
142
+ readonly changed: Set<string>;
143
+ constructor(tx: Tx, part: string);
144
+ entry(collection: string, rkey: string): Promise<CacheEntry | undefined>;
145
+ /** newEntry is an entry for a record this device has never seen. */
146
+ newEntry(collection: string, rkey: string): CacheEntry;
147
+ /** opsFor returns the queued writes of one record, in order. */
148
+ opsFor(collection: string, rkey: string): Promise<StoredOp[]>;
149
+ /**
150
+ * save stores e with its local state recomputed from its queued writes.
151
+ * An entry with nothing to remember (no server state, not deleted,
152
+ * nothing queued) is removed instead.
153
+ */
154
+ save(e: CacheEntry): Promise<void>;
155
+ enqueue(op: QueuedOp, at: string): Promise<void>;
156
+ dequeue(seq: number): Promise<void>;
157
+ /**
158
+ * applyServer records a server state of a record (from a write result,
159
+ * a query, the changes feed or the live connection) if it is newer than
160
+ * what the cache has. record null means the record is deleted on the
161
+ * server. versions, when given, hides records of other majors. Queued
162
+ * local writes stay applied on top. A record hidden by versions is taken
163
+ * again at the same rev (the versions read may have widened). A deleted
164
+ * record is taken again only from a newer state (a restore from its
165
+ * history); a change at or below the rev already seen never brings it
166
+ * back. Returns whether anything changed.
167
+ */
168
+ applyServer(collection: string, rkey: string, rev: number, record: WireRecord | null, versions?: number[]): Promise<boolean>;
169
+ }
170
+ export {};