@hadoku/prefs-client 1.1.24 → 1.1.25
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/README.md +2 -1
- package/dist/index.d.ts +5 -4
- package/dist/index.js +97 -54
- package/dist/react.d.ts +1 -1
- package/dist/{types-DCldC4WA.d.ts → types-r2SIOIuu.d.ts} +45 -7
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -57,7 +57,8 @@ function Settings() {
|
|
|
57
57
|
|
|
58
58
|
- **Cache**: localStorage at `prefs-cache:{userId}:{appId}`. Stale-while-revalidate.
|
|
59
59
|
- **Writes**: 1s-debounced PUT. Multiple `save()` calls within the window coalesce into one network call.
|
|
60
|
-
- **Conflicts**: API-Always-Wins. On a 409 the SDK adopts the server blob and re-renders; the local patch is discarded
|
|
60
|
+
- **Conflicts**: API-Always-Wins. On a 409 the SDK adopts the server blob and re-renders; the local patch is discarded, and the `save()` (with an explicit `expectedVersion`) or `flush()` waiting on it rejects with `PrefsConflictError`.
|
|
61
|
+
- **`expectedVersion`**: by default the SDK sends the last version it has seen (0 before the first read). `save(patch, { expectedVersion: n })` sends `n`; `{ expectedVersion: null }` sends none — last write wins. Both send at once rather than debounced.
|
|
61
62
|
- **Cross-tab**: BroadcastChannel keyed by `prefs:{userId}:{appId}` propagates saves between tabs without a server roundtrip.
|
|
62
63
|
- **Anon → authed**: call `client.promoteAnonPrefsToUser()` after sign-in. If the server already has user-scope prefs (signed in on another device first), the server wins.
|
|
63
64
|
- **Dirty-field protection**: a background refresh (or an incoming cross-tab broadcast) never overwrites a field with a save still pending/in-flight — it merges the server/remote blob with your unconfirmed local value instead. Otherwise a refresh landing between an optimistic write and its debounced PUT would visibly revert the change.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { P as PrefsClientOptions, a as PrefsClient, A as AsyncStorage } from './types-
|
|
3
|
-
export { b as
|
|
2
|
+
import { P as PrefsClientOptions, a as PrefsClient, A as AsyncStorage } from './types-r2SIOIuu.js';
|
|
3
|
+
export { b as PrefsConflictError, c as PrefsMigration, d as PrefsRow, S as SaveOptions, e as Scope, f as ServerReadResult, g as capacitorStorage, h as detectStorage, l as localStorageAdapter, m as memoryStorage, s as sessionStorageWrite } from './types-r2SIOIuu.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* createPrefsClient — vanilla (no React) client for the prefs-api.
|
|
@@ -15,9 +15,10 @@ export { b as PrefsMigration, c as PrefsRow, S as SaveOptions, d as Scope, e as
|
|
|
15
15
|
* save(patch)
|
|
16
16
|
* ├─ merge patch into in-memory current blob
|
|
17
17
|
* ├─ update cache + notify listeners synchronously (optimistic UI)
|
|
18
|
-
* ├─ debounce 1s, then PUT
|
|
18
|
+
* ├─ debounce 1s, then PUT (an explicit expectedVersion sends at once)
|
|
19
19
|
* └─ on 409: adopt server blob from response, overwrite cache, notify
|
|
20
|
-
* (API-Always-Wins per docs/planning/unified-prefs-2026-05-20.md)
|
|
20
|
+
* (API-Always-Wins per docs/planning/unified-prefs-2026-05-20.md),
|
|
21
|
+
* and reject the save()/flush() waiting on that patch
|
|
21
22
|
*
|
|
22
23
|
* subscribe(listener)
|
|
23
24
|
* ├─ stash listener in a Set
|
package/dist/index.js
CHANGED
|
@@ -105,6 +105,20 @@ function isUuid(s) {
|
|
|
105
105
|
return UUID_RE.test(s);
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
+
// src/types.ts
|
|
109
|
+
var PrefsConflictError = class extends Error {
|
|
110
|
+
constructor(patch, scope, serverVersion) {
|
|
111
|
+
super(`prefs-api refused a ${scope}-scope save with 409 (server version ${serverVersion})`);
|
|
112
|
+
this.patch = patch;
|
|
113
|
+
this.scope = scope;
|
|
114
|
+
this.serverVersion = serverVersion;
|
|
115
|
+
}
|
|
116
|
+
patch;
|
|
117
|
+
scope;
|
|
118
|
+
serverVersion;
|
|
119
|
+
name = "PrefsConflictError";
|
|
120
|
+
};
|
|
121
|
+
|
|
108
122
|
// src/whoami.ts
|
|
109
123
|
var ANON_USER_ID = "anon";
|
|
110
124
|
var WHOAMI_GLOBAL = "__hadokuWhoami";
|
|
@@ -194,11 +208,11 @@ function createPrefsClient(opts) {
|
|
|
194
208
|
let currentBlob = null;
|
|
195
209
|
let userVersion = 0;
|
|
196
210
|
let deviceVersion = 0;
|
|
197
|
-
let
|
|
198
|
-
|
|
211
|
+
let queued = [];
|
|
212
|
+
const unsettled = /* @__PURE__ */ new Set();
|
|
213
|
+
let sendChain = Promise.resolve();
|
|
199
214
|
const dirtyFields = /* @__PURE__ */ new Set();
|
|
200
215
|
let saveTimer = null;
|
|
201
|
-
let savePromise = null;
|
|
202
216
|
let initPromise = null;
|
|
203
217
|
let bcast = null;
|
|
204
218
|
let destroyed = false;
|
|
@@ -377,60 +391,77 @@ function createPrefsClient(opts) {
|
|
|
377
391
|
notify(currentBlob);
|
|
378
392
|
broadcast(currentBlob);
|
|
379
393
|
}
|
|
394
|
+
function newBatch(scope, expected, patch = {}) {
|
|
395
|
+
let settle;
|
|
396
|
+
const done = new Promise((resolve) => {
|
|
397
|
+
settle = resolve;
|
|
398
|
+
});
|
|
399
|
+
const batch = { patch, scope, expected, done, settle };
|
|
400
|
+
unsettled.add(batch);
|
|
401
|
+
return batch;
|
|
402
|
+
}
|
|
380
403
|
function scheduleFlush() {
|
|
381
404
|
if (saveTimer) clearTimeout(saveTimer);
|
|
382
|
-
saveTimer = setTimeout(
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
}
|
|
386
|
-
async function flushPending() {
|
|
387
|
-
if (Object.keys(pendingPatch).length === 0) return;
|
|
388
|
-
if (savePromise) {
|
|
389
|
-
await savePromise;
|
|
390
|
-
}
|
|
391
|
-
const patchSnapshot = pendingPatch;
|
|
392
|
-
const scopeSnapshot = pendingScope;
|
|
393
|
-
pendingPatch = {};
|
|
405
|
+
saveTimer = setTimeout(dispatchQueued, SAVE_DEBOUNCE_MS);
|
|
406
|
+
}
|
|
407
|
+
function dispatchQueued() {
|
|
394
408
|
if (saveTimer) {
|
|
395
409
|
clearTimeout(saveTimer);
|
|
396
410
|
saveTimer = null;
|
|
397
411
|
}
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
412
|
+
const batches = queued;
|
|
413
|
+
queued = [];
|
|
414
|
+
for (const batch of batches) {
|
|
415
|
+
sendChain = sendChain.then(() => send(batch));
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
function clearDirty(patch) {
|
|
419
|
+
for (const key of Object.keys(patch)) {
|
|
420
|
+
let stillPending = false;
|
|
421
|
+
for (const other of unsettled) {
|
|
422
|
+
if (key in other.patch) stillPending = true;
|
|
401
423
|
}
|
|
424
|
+
if (!stillPending) dirtyFields.delete(key);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
async function send(batch) {
|
|
428
|
+
if (!canSync()) {
|
|
429
|
+
unsettled.delete(batch);
|
|
430
|
+
clearDirty(batch.patch);
|
|
431
|
+
batch.settle(null);
|
|
402
432
|
return;
|
|
403
433
|
}
|
|
404
|
-
const expectedVersion =
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
}
|
|
414
|
-
await refreshFromServer();
|
|
415
|
-
} else {
|
|
416
|
-
if (scopeSnapshot === "user") {
|
|
417
|
-
userVersion = result.conflict.version;
|
|
418
|
-
} else {
|
|
419
|
-
deviceVersion = result.conflict.version;
|
|
420
|
-
}
|
|
421
|
-
await refreshFromServer();
|
|
422
|
-
}
|
|
423
|
-
for (const key of Object.keys(patchSnapshot)) {
|
|
424
|
-
if (!(key in pendingPatch)) dirtyFields.delete(key);
|
|
425
|
-
}
|
|
426
|
-
} catch {
|
|
427
|
-
pendingPatch = { ...patchSnapshot, ...pendingPatch };
|
|
428
|
-
pendingScope = scopeSnapshot;
|
|
429
|
-
} finally {
|
|
430
|
-
savePromise = null;
|
|
434
|
+
const expectedVersion = batch.expected === void 0 ? batch.scope === "user" ? userVersion : deviceVersion : batch.expected ?? void 0;
|
|
435
|
+
let conflict = null;
|
|
436
|
+
try {
|
|
437
|
+
const result = await putToServer(batch.scope, batch.patch, expectedVersion);
|
|
438
|
+
const version = result.ok ? result.row.version : result.conflict.version;
|
|
439
|
+
if ((result.ok ? result.scope : batch.scope) === "user") {
|
|
440
|
+
userVersion = version;
|
|
441
|
+
} else {
|
|
442
|
+
deviceVersion = version;
|
|
431
443
|
}
|
|
432
|
-
|
|
433
|
-
|
|
444
|
+
if (!result.ok) {
|
|
445
|
+
conflict = new PrefsConflictError(batch.patch, batch.scope, version);
|
|
446
|
+
}
|
|
447
|
+
} catch {
|
|
448
|
+
unsettled.delete(batch);
|
|
449
|
+
const front = queued[0];
|
|
450
|
+
if (front && front.scope === batch.scope && front.expected === batch.expected) {
|
|
451
|
+
front.patch = { ...batch.patch, ...front.patch };
|
|
452
|
+
} else {
|
|
453
|
+
queued.unshift(newBatch(batch.scope, batch.expected, batch.patch));
|
|
454
|
+
}
|
|
455
|
+
batch.settle(null);
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
unsettled.delete(batch);
|
|
459
|
+
clearDirty(batch.patch);
|
|
460
|
+
try {
|
|
461
|
+
await refreshFromServer();
|
|
462
|
+
} catch {
|
|
463
|
+
}
|
|
464
|
+
batch.settle(conflict);
|
|
434
465
|
}
|
|
435
466
|
const client = {
|
|
436
467
|
appId: opts.appId,
|
|
@@ -464,14 +495,21 @@ function createPrefsClient(opts) {
|
|
|
464
495
|
mirrorBootstrap(nextBlob);
|
|
465
496
|
notify(nextBlob);
|
|
466
497
|
broadcast(nextBlob);
|
|
467
|
-
|
|
468
|
-
|
|
498
|
+
const expected = saveOpts?.expectedVersion;
|
|
499
|
+
const last = queued[queued.length - 1];
|
|
500
|
+
let batch;
|
|
501
|
+
if (last && last.scope === scope && last.expected === void 0 && expected === void 0) {
|
|
502
|
+
batch = last;
|
|
503
|
+
} else {
|
|
504
|
+
batch = newBatch(scope, expected);
|
|
505
|
+
queued.push(batch);
|
|
469
506
|
}
|
|
470
|
-
|
|
471
|
-
pendingScope = scope;
|
|
507
|
+
batch.patch = { ...batch.patch, ...patch };
|
|
472
508
|
for (const key of Object.keys(patch)) dirtyFields.add(key);
|
|
473
|
-
if (
|
|
474
|
-
|
|
509
|
+
if (expected !== void 0) {
|
|
510
|
+
dispatchQueued();
|
|
511
|
+
const conflict = await batch.done;
|
|
512
|
+
if (conflict) throw conflict;
|
|
475
513
|
} else {
|
|
476
514
|
scheduleFlush();
|
|
477
515
|
}
|
|
@@ -506,7 +544,11 @@ function createPrefsClient(opts) {
|
|
|
506
544
|
await storage.remove(anonKey);
|
|
507
545
|
},
|
|
508
546
|
async flush() {
|
|
509
|
-
|
|
547
|
+
const waiting = [...unsettled];
|
|
548
|
+
dispatchQueued();
|
|
549
|
+
const conflicts = await Promise.all(waiting.map((b) => b.done));
|
|
550
|
+
const conflict = conflicts.find((c) => c !== null);
|
|
551
|
+
if (conflict) throw conflict;
|
|
510
552
|
},
|
|
511
553
|
destroy() {
|
|
512
554
|
if (destroyed) return;
|
|
@@ -523,6 +565,7 @@ export {
|
|
|
523
565
|
CACHE_KEY_PREFIX,
|
|
524
566
|
DEVICE_ID_KEY,
|
|
525
567
|
PREFS_API_BASE,
|
|
568
|
+
PrefsConflictError,
|
|
526
569
|
SAVE_DEBOUNCE_MS,
|
|
527
570
|
capacitorStorage,
|
|
528
571
|
createPrefsClient,
|
package/dist/react.d.ts
CHANGED
|
@@ -136,11 +136,40 @@ interface SaveOptions {
|
|
|
136
136
|
/** Default: 'user'. Use 'device' for per-device-only fields like theme. */
|
|
137
137
|
scope?: Scope;
|
|
138
138
|
/**
|
|
139
|
-
* Override the auto-managed expectedVersion
|
|
140
|
-
*
|
|
141
|
-
*
|
|
139
|
+
* Override the auto-managed expectedVersion for THIS patch.
|
|
140
|
+
*
|
|
141
|
+
* Left undefined, the SDK sends the last server version it has seen for the
|
|
142
|
+
* scope — 0 on a client that has not read the row yet, which prefs-api
|
|
143
|
+
* answers with 409 for any row that exists.
|
|
144
|
+
*
|
|
145
|
+
* - a number is sent as-is (`0` writes only if the row does not exist yet);
|
|
146
|
+
* - `null` sends no version at all: last write wins, prefs-api's contract
|
|
147
|
+
* for an omitted version. Use it for a pick the user just made on a page
|
|
148
|
+
* that need not have read the row first.
|
|
149
|
+
*
|
|
150
|
+
* Either way the patch is sent on its own and at once — never coalesced with
|
|
151
|
+
* a debounced batch — and save() rejects with {@link PrefsConflictError} if
|
|
152
|
+
* prefs-api refused it with 409.
|
|
142
153
|
*/
|
|
143
|
-
expectedVersion?: number;
|
|
154
|
+
expectedVersion?: number | null;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* A patch prefs-api refused with 409 because the row's version had moved. The
|
|
158
|
+
* client has already adopted the server's row (the API-wins rule) and dropped
|
|
159
|
+
* the patch; this tells the caller the save did not happen.
|
|
160
|
+
*/
|
|
161
|
+
declare class PrefsConflictError extends Error {
|
|
162
|
+
/** The patch that was dropped. */
|
|
163
|
+
readonly patch: Record<string, unknown>;
|
|
164
|
+
readonly scope: Scope;
|
|
165
|
+
/** The row's version on the server, which the client now holds. */
|
|
166
|
+
readonly serverVersion: number;
|
|
167
|
+
readonly name = "PrefsConflictError";
|
|
168
|
+
constructor(
|
|
169
|
+
/** The patch that was dropped. */
|
|
170
|
+
patch: Record<string, unknown>, scope: Scope,
|
|
171
|
+
/** The row's version on the server, which the client now holds. */
|
|
172
|
+
serverVersion: number);
|
|
144
173
|
}
|
|
145
174
|
/**
|
|
146
175
|
* `T` is the app's prefs blob (a `z.infer` of its schema). It is intentionally
|
|
@@ -162,7 +191,10 @@ interface PrefsClient<T> {
|
|
|
162
191
|
read(): Promise<T>;
|
|
163
192
|
/**
|
|
164
193
|
* Apply a partial patch. Coalesced via a 1s debounce so a slider that
|
|
165
|
-
* fires 30 onChange events in two seconds only PUTs twice.
|
|
194
|
+
* fires 30 onChange events in two seconds only PUTs twice. Resolves once
|
|
195
|
+
* the patch is applied locally; with an explicit `expectedVersion` it
|
|
196
|
+
* instead waits for the PUT and rejects with {@link PrefsConflictError} on
|
|
197
|
+
* a 409.
|
|
166
198
|
*/
|
|
167
199
|
save(patch: Partial<T>, opts?: SaveOptions): Promise<void>;
|
|
168
200
|
/** Subscribe to changes (incl. cross-tab via BroadcastChannel). */
|
|
@@ -181,10 +213,16 @@ interface PrefsClient<T> {
|
|
|
181
213
|
* unconditionally on sign-in; it decides for itself.
|
|
182
214
|
*/
|
|
183
215
|
promoteAnonPrefsToUser(): Promise<void>;
|
|
184
|
-
/**
|
|
216
|
+
/**
|
|
217
|
+
* Send every queued patch now and wait for it, and for any already in
|
|
218
|
+
* flight, to settle. Rejects with {@link PrefsConflictError} if prefs-api
|
|
219
|
+
* refused one of them with 409 (its fields now show the server's value). A
|
|
220
|
+
* network failure does not reject: that patch stays queued for the next
|
|
221
|
+
* save. For beforeunload, call it as `void client.flush().catch(...)`.
|
|
222
|
+
*/
|
|
185
223
|
flush(): Promise<void>;
|
|
186
224
|
/** Tear down (cancels timers, closes BroadcastChannel). */
|
|
187
225
|
destroy(): void;
|
|
188
226
|
}
|
|
189
227
|
|
|
190
|
-
export { type AsyncStorage as A, type PrefsClientOptions as P, type SaveOptions as S, type PrefsClient as a, type PrefsMigration as
|
|
228
|
+
export { type AsyncStorage as A, type PrefsClientOptions as P, type SaveOptions as S, type PrefsClient as a, PrefsConflictError as b, type PrefsMigration as c, type PrefsRow as d, type Scope as e, type ServerReadResult as f, capacitorStorage as g, detectStorage as h, localStorageAdapter as l, memoryStorage as m, sessionStorageWrite as s };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hadoku/prefs-client",
|
|
3
|
-
"version": "1.1.
|
|
4
|
-
"gitHead": "
|
|
3
|
+
"version": "1.1.25",
|
|
4
|
+
"gitHead": "155e8fbf36a57da2948b06923ae8dba64a88e09c",
|
|
5
5
|
"description": "Client SDK for the hadoku unified preferences store. Wraps /prefs/api/v1/* with localStorage caching, debounced writes, Zod-validated reads, and a usePrefs() React hook, plus match history, ratings and leaderboards for every game (./games), the one resolved avatar per user (./avatar), and the avatar cosmetics renderer (./cosmetics).",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "./dist/index.js",
|