@hadoku/prefs-client 1.1.27 → 1.1.29

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 CHANGED
@@ -152,6 +152,25 @@ const byUser = await resolveAvatars(
152
152
  byUser[id].name; // their live display name, or null for an unknown or closed account
153
153
  ```
154
154
 
155
+ A server that shows people over and over (a room's roster, a tier list) uses the cached lookup
156
+ instead of calling `resolveAvatars` on every join:
157
+
158
+ ```ts
159
+ import { createPeopleLookup } from '@wolffm/prefs-client/people';
160
+ const people = createPeopleLookup({
161
+ baseUrl,
162
+ serviceKey,
163
+ userAgent: 'hadoku-<app>-people/1',
164
+ });
165
+ const byUser = await people.resolve(userIds); // Map: an answer, null for no entry; absent if unreachable
166
+ people.peek(userId);
167
+ people.forget(userId); // forget on account erase
168
+ ```
169
+
170
+ Cached a minute (`fresh: true` skips it), one lookup per id at a time, a failure answers nobody
171
+ and is not cached (`onError` hears it), no key means no lookups. watchparty and
172
+ `@wolffm/game-server` both read people through it.
173
+
155
174
  **Names come from here too.** A server stores only userIds (IDENTITY_MODEL R12) and names
156
175
  people, online or not, when it shows them: `resolveAvatars(...)[id].name`. Never keep a copy.
157
176
  prefs-api reads the registry at most once a minute per isolate, so a rename shows within a
package/dist/index.d.ts CHANGED
@@ -75,7 +75,7 @@ declare function getDeviceId(storage?: AsyncStorage): Promise<string>;
75
75
  type IdentityScope = 'user' | 'session' | 'anon' | 'none';
76
76
  interface WhoamiResult {
77
77
  userId: string;
78
- userType: 'admin' | 'wife' | 'service' | 'friend' | 'member' | 'public';
78
+ userType: 'admin' | 'wife' | 'service' | 'friend' | 'member' | 'guest' | 'public';
79
79
  name?: string | null;
80
80
  /**
81
81
  * How `userId` was derived. Callers that PERSIST anything keyed by
package/dist/index.js CHANGED
@@ -128,7 +128,7 @@ function adaptWhoami(body) {
128
128
  if (!body || body.valid === false) {
129
129
  return { userId: ANON_USER_ID, userType: "public", scope: "anon" };
130
130
  }
131
- const userType = body.userType === "admin" || body.userType === "wife" || body.userType === "service" || body.userType === "friend" || body.userType === "member" || body.userType === "public" ? body.userType : "public";
131
+ const userType = body.userType === "admin" || body.userType === "wife" || body.userType === "service" || body.userType === "friend" || body.userType === "member" || body.userType === "guest" || body.userType === "public" ? body.userType : "public";
132
132
  const name = typeof body.name === "string" ? body.name : null;
133
133
  const verified = body.verified === true ? { verified: true } : {};
134
134
  if (typeof body.userId === "string" && body.userId) {
@@ -0,0 +1,59 @@
1
+ import { R as ResolvedPerson } from './avatar-contract-vrX2StQI.js';
2
+ import './cosmetics-contract-CKe1lNNV.js';
3
+
4
+ /**
5
+ * Server-side: who people are and what they look like, by userId, for a server that shows people
6
+ * (a room's roster, a tier list, a match card) — `resolveAvatars` behind a short cache.
7
+ *
8
+ * Every game and app server needs the same lookup, so it is here once: watchparty's
9
+ * `rooms/avatars.ts` and `@wolffm/game-server`'s `people.ts` each built it. What a server does with
10
+ * an answer (its own `Person`, its own look) stays its own; this hands back prefs-api's answer.
11
+ *
12
+ * - **Cached a minute** by default: a room's joins share one lookup, and a change made elsewhere
13
+ * shows within the minute. `fresh` skips the cache (the person has just changed theirs).
14
+ * - **An id asked twice at once is asked once.** A burst of joins after a restart waits on the
15
+ * lookup already in flight for an id rather than starting another.
16
+ * - **A failure answers nobody and is not cached**, so an outage recovers on the next ask. It is
17
+ * reported (`onError`), never thrown: a missing look costs a face its dressing, not a join.
18
+ * - **No key, no lookups** (unless `keyless`, for an e2e stand-in that answers without one).
19
+ *
20
+ * The User-Agent is the caller's: hadoku.me's WAF challenges a bare client one. Each lookup gives
21
+ * up after `timeoutMs`, so one that never answers does not hold a join open.
22
+ */
23
+
24
+ interface PeopleLookupOptions {
25
+ /** The prefs mount, without `/api/v1`. */
26
+ baseUrl: string;
27
+ /** This server's service-tier key. Empty: no lookups (unless `keyless`). */
28
+ serviceKey: string;
29
+ /** Sent on every lookup: hadoku.me's WAF challenges a bare client user-agent. */
30
+ userAgent: string;
31
+ /** Look people up with no key: only an e2e stand-in answers that. */
32
+ keyless?: boolean;
33
+ /** How long an answer is kept. Default a minute. */
34
+ ttlMs?: number;
35
+ /** How long one lookup may take. Default 5 s. */
36
+ timeoutMs?: number;
37
+ /** Told of a failed lookup, with the ids it was for. */
38
+ onError?: (err: unknown, userIds: readonly string[]) => void;
39
+ fetch?: typeof fetch;
40
+ now?: () => number;
41
+ }
42
+ interface PeopleLookup {
43
+ /**
44
+ * Each id prefs-api answered for, now or within the cache's minute. An id it gave no entry for
45
+ * (an unknown or closed account) is answered `null`; an id the lookup could not reach is absent.
46
+ */
47
+ resolve(userIds: readonly string[], opts?: {
48
+ fresh?: boolean;
49
+ }): Promise<Map<string, ResolvedPerson | null>>;
50
+ /** The cached answer for one id: `undefined` when there is none fresh. */
51
+ peek(userId: string): ResolvedPerson | null | undefined;
52
+ /** Drop one id's answer (account erase); 1 when one was held, else 0. */
53
+ forget(userId: string): number;
54
+ /** Drop every answer. */
55
+ clear(): void;
56
+ }
57
+ declare function createPeopleLookup(opts: PeopleLookupOptions): PeopleLookup;
58
+
59
+ export { type PeopleLookup, type PeopleLookupOptions, ResolvedPerson, createPeopleLookup };
package/dist/people.js ADDED
@@ -0,0 +1,123 @@
1
+ // src/constants.ts
2
+ var PREFS_API_BASE = "https://hadoku.me/prefs";
3
+
4
+ // src/avatar-contract.ts
5
+ var RESOLVE_MAX_IDS = 100;
6
+
7
+ // src/avatar.ts
8
+ var AvatarError = class extends Error {
9
+ constructor(status, message) {
10
+ super(message);
11
+ this.status = status;
12
+ this.name = "AvatarError";
13
+ }
14
+ status;
15
+ };
16
+ async function readJson(res) {
17
+ if (!res.ok) {
18
+ const body = await res.json().catch(() => null);
19
+ throw new AvatarError(res.status, body?.message ?? `HTTP ${res.status}`);
20
+ }
21
+ return await res.json();
22
+ }
23
+ async function resolveAvatars(opts, userIds) {
24
+ const f = opts.fetch ?? fetch;
25
+ const url = `${opts.baseUrl ?? PREFS_API_BASE}/api/v1/_avatar/resolve`;
26
+ const unique = [...new Set(userIds)];
27
+ const out = {};
28
+ for (let i = 0; i < unique.length; i += RESOLVE_MAX_IDS) {
29
+ const res = await f(url, {
30
+ method: "POST",
31
+ headers: { "Content-Type": "application/json", "X-User-Key": opts.serviceKey },
32
+ body: JSON.stringify({ userIds: unique.slice(i, i + RESOLVE_MAX_IDS) })
33
+ });
34
+ Object.assign(out, (await readJson(res)).avatars);
35
+ }
36
+ return out;
37
+ }
38
+
39
+ // src/people.ts
40
+ var DEFAULT_TTL_MS = 6e4;
41
+ var DEFAULT_TIMEOUT_MS = 5e3;
42
+ var PRUNE_AT = 1024;
43
+ function createPeopleLookup(opts) {
44
+ const now = opts.now ?? Date.now;
45
+ const ttl = opts.ttlMs ?? DEFAULT_TTL_MS;
46
+ const timeout = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
47
+ const baseUrl = opts.baseUrl.replace(/\/+$/, "");
48
+ const cache = /* @__PURE__ */ new Map();
49
+ const inflight = /* @__PURE__ */ new Map();
50
+ const lookupFetch = (input, init) => (opts.fetch ?? fetch)(input, {
51
+ ...init,
52
+ headers: {
53
+ ...init?.headers,
54
+ "User-Agent": opts.userAgent
55
+ },
56
+ signal: AbortSignal.timeout(timeout)
57
+ });
58
+ const peek = (userId) => {
59
+ const hit = cache.get(userId);
60
+ return hit !== void 0 && hit.expiresAt > now() ? hit.person : void 0;
61
+ };
62
+ const lookup = (ids) => {
63
+ const run = (async () => {
64
+ try {
65
+ const answer = await resolveAvatars(
66
+ { baseUrl, serviceKey: opts.serviceKey, fetch: lookupFetch },
67
+ ids
68
+ );
69
+ const at = now();
70
+ for (const id of ids) cache.set(id, { person: answer[id] ?? null, expiresAt: at + ttl });
71
+ if (cache.size > PRUNE_AT) {
72
+ for (const [k, e] of cache) if (e.expiresAt <= at) cache.delete(k);
73
+ }
74
+ } catch (err) {
75
+ opts.onError?.(err, ids);
76
+ }
77
+ })();
78
+ for (const id of ids) inflight.set(id, run);
79
+ void run.finally(() => {
80
+ for (const id of ids) if (inflight.get(id) === run) inflight.delete(id);
81
+ });
82
+ return run;
83
+ };
84
+ return {
85
+ peek,
86
+ forget(userId) {
87
+ inflight.delete(userId);
88
+ return cache.delete(userId) ? 1 : 0;
89
+ },
90
+ clear() {
91
+ cache.clear();
92
+ inflight.clear();
93
+ },
94
+ async resolve(userIds, { fresh = false } = {}) {
95
+ const out = /* @__PURE__ */ new Map();
96
+ const wanted = [...new Set(userIds)];
97
+ if (opts.serviceKey === "" && opts.keyless !== true) return out;
98
+ const waits = [];
99
+ const missing = [];
100
+ for (const id of wanted) {
101
+ if (!fresh) {
102
+ if (peek(id) !== void 0) continue;
103
+ const pending = inflight.get(id);
104
+ if (pending !== void 0) {
105
+ waits.push(pending);
106
+ continue;
107
+ }
108
+ }
109
+ missing.push(id);
110
+ }
111
+ if (missing.length > 0) waits.push(lookup(missing));
112
+ await Promise.all(waits);
113
+ for (const id of wanted) {
114
+ const hit = peek(id);
115
+ if (hit !== void 0) out.set(id, hit);
116
+ }
117
+ return out;
118
+ }
119
+ };
120
+ }
121
+ export {
122
+ createPeopleLookup
123
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/prefs-client",
3
- "version": "1.1.27",
4
- "gitHead": "821671a109034b78ce04c52eb9cf9456eea8be22",
3
+ "version": "1.1.29",
4
+ "gitHead": "1a8adf4b1717bfa1bb9a18d7680d0fc7db2d7a5b",
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",
@@ -38,6 +38,10 @@
38
38
  "./cosmetics": {
39
39
  "types": "./dist/cosmetics.d.ts",
40
40
  "default": "./dist/cosmetics.js"
41
+ },
42
+ "./people": {
43
+ "types": "./dist/people.d.ts",
44
+ "default": "./dist/people.js"
41
45
  }
42
46
  },
43
47
  "files": [