@diffenderfer-games/hub 0.0.0-stage → 2.0.0-next.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 +21 -0
- package/README.md +138 -2
- package/dist/auto.d.ts +36 -0
- package/dist/auto.d.ts.map +1 -0
- package/dist/auto.js +27 -0
- package/dist/auto.js.map +1 -0
- package/dist/daily.d.ts +2 -0
- package/dist/daily.js +1 -0
- package/dist/doctor/cli.mjs +238 -0
- package/dist/doctor/cli.mjs.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +6 -0
- package/dist/input.d.ts +2 -0
- package/dist/input.js +3 -0
- package/dist/mp.d.ts +4 -0
- package/dist/mp.js +1 -0
- package/dist/race.d.ts +4 -0
- package/dist/race.js +1 -0
- package/dist/rooms.d.ts +4 -0
- package/dist/rooms.js +1 -0
- package/dist/shared/bridge.js +209 -0
- package/dist/shared/bridge.js.map +1 -0
- package/dist/shared/client-version.gen.js +7 -0
- package/dist/shared/client-version.gen.js.map +1 -0
- package/dist/shared/daily.d.ts +123 -0
- package/dist/shared/daily.d.ts.map +1 -0
- package/dist/shared/daily.js +191 -0
- package/dist/shared/daily.js.map +1 -0
- package/dist/shared/dom.js +48 -0
- package/dist/shared/dom.js.map +1 -0
- package/dist/shared/globals.js +97 -0
- package/dist/shared/globals.js.map +1 -0
- package/dist/shared/index.d.ts +706 -0
- package/dist/shared/index.d.ts.map +1 -0
- package/dist/shared/input.d.ts +730 -0
- package/dist/shared/input.d.ts.map +1 -0
- package/dist/shared/input.js +2718 -0
- package/dist/shared/input.js.map +1 -0
- package/dist/shared/latest-state.js +17 -0
- package/dist/shared/latest-state.js.map +1 -0
- package/dist/shared/mp.d.ts +9 -0
- package/dist/shared/mp.d.ts.map +1 -0
- package/dist/shared/mp.js +30 -0
- package/dist/shared/mp.js.map +1 -0
- package/dist/shared/multiplayer-types.d.ts +47 -0
- package/dist/shared/multiplayer-types.d.ts.map +1 -0
- package/dist/shared/page-stack.js +207 -0
- package/dist/shared/page-stack.js.map +1 -0
- package/dist/shared/race-types.d.ts +126 -0
- package/dist/shared/race-types.d.ts.map +1 -0
- package/dist/shared/race.d.ts +9 -0
- package/dist/shared/race.d.ts.map +1 -0
- package/dist/shared/race.js +53 -0
- package/dist/shared/race.js.map +1 -0
- package/dist/shared/room-types.d.ts +125 -0
- package/dist/shared/room-types.d.ts.map +1 -0
- package/dist/shared/rooms.d.ts +9 -0
- package/dist/shared/rooms.d.ts.map +1 -0
- package/dist/shared/rooms.js +62 -0
- package/dist/shared/rooms.js.map +1 -0
- package/dist/shared/runtime-opener.js +84 -0
- package/dist/shared/runtime-opener.js.map +1 -0
- package/dist/shared/social.d.ts +148 -0
- package/dist/shared/social.d.ts.map +1 -0
- package/dist/shared/social.js +73 -0
- package/dist/shared/social.js.map +1 -0
- package/dist/shared/src.js +2164 -0
- package/dist/shared/src.js.map +1 -0
- package/dist/shared/wire-types.d.ts +51 -0
- package/dist/shared/wire-types.d.ts.map +1 -0
- package/dist/social.d.ts +6 -0
- package/dist/social.js +3 -0
- package/dist/types.d.ts +1 -0
- package/dist/types.js +0 -0
- package/package.json +87 -4
- package/src/auto.ts +39 -0
- package/src/core/connection.ts +299 -0
- package/src/core/errors.ts +147 -0
- package/src/core/game-data.ts +38 -0
- package/src/core/hub-economy.ts +179 -0
- package/src/core/hub-progress.ts +205 -0
- package/src/core/hub.ts +131 -0
- package/src/core/menu-control.ts +61 -0
- package/src/core/offline/events.ts +50 -0
- package/src/core/offline/favorites.ts +21 -0
- package/src/core/offline/local-store.ts +261 -0
- package/src/core/offline/queue.ts +171 -0
- package/src/core/page.ts +74 -0
- package/src/core/rest/endpoint-types.ts +22 -0
- package/src/core/rest/rest-client.ts +152 -0
- package/src/core/rest/routes.gen.ts +90 -0
- package/src/core/storage/json-guards.ts +74 -0
- package/src/core/storage/key-value.ts +66 -0
- package/src/core/ticket.ts +43 -0
- package/src/core/types.ts +134 -0
- package/src/core/version/client-version.gen.ts +3 -0
- package/src/core/version/hub-version.ts +62 -0
- package/src/core/version/semver.ts +97 -0
- package/src/daily/daily-system.ts +161 -0
- package/src/daily/page-daily.ts +36 -0
- package/src/daily/types.ts +67 -0
- package/src/daily.ts +10 -0
- package/src/doctor/checks.ts +76 -0
- package/src/doctor/cli.ts +106 -0
- package/src/doctor/tsconfig.json +12 -0
- package/src/globals.ts +110 -0
- package/src/index.ts +50 -0
- package/src/input/device-state.ts +146 -0
- package/src/input/edges.ts +55 -0
- package/src/input/gamepad.ts +61 -0
- package/src/input/input-events.ts +32 -0
- package/src/input/input-registry.ts +164 -0
- package/src/input/input-system.ts +393 -0
- package/src/input/legacy-controls.ts +64 -0
- package/src/input/nav-state.ts +191 -0
- package/src/input/navigator.ts +171 -0
- package/src/input/on-screen-controls.ts +101 -0
- package/src/input/page-control.ts +43 -0
- package/src/input/page-input.ts +193 -0
- package/src/input/player-remaps.ts +77 -0
- package/src/input/source-values.ts +116 -0
- package/src/input/spatial.ts +47 -0
- package/src/input/types.ts +331 -0
- package/src/input/zero-config.ts +177 -0
- package/src/input.ts +22 -0
- package/src/mp.ts +10 -0
- package/src/overlay/controls-panel.ts +163 -0
- package/src/overlay/dom.ts +46 -0
- package/src/overlay/layout-clusters.ts +162 -0
- package/src/overlay/layout-geometry.ts +136 -0
- package/src/overlay/layout.ts +203 -0
- package/src/overlay/listener-scope.ts +23 -0
- package/src/overlay/on-screen-keyboard.ts +137 -0
- package/src/overlay/overlay.ts +208 -0
- package/src/overlay/styles.ts +54 -0
- package/src/overlay/virtual-controls.ts +262 -0
- package/src/race.ts +10 -0
- package/src/realtime/bridge.ts +121 -0
- package/src/realtime/cross-bundle.ts +29 -0
- package/src/realtime/fallback-notice.ts +48 -0
- package/src/realtime/hub-link.ts +65 -0
- package/src/realtime/latest-state.ts +33 -0
- package/src/realtime/multiplayer-forwarder.ts +28 -0
- package/src/realtime/multiplayer-types.ts +52 -0
- package/src/realtime/page-runtime.ts +60 -0
- package/src/realtime/race-forwarder.ts +59 -0
- package/src/realtime/race-types.ts +132 -0
- package/src/realtime/room-types.ts +125 -0
- package/src/realtime/rooms-forwarder.ts +79 -0
- package/src/realtime/runtime-api.ts +49 -0
- package/src/realtime/runtime-opener.ts +61 -0
- package/src/realtime/social-forwarder.ts +72 -0
- package/src/realtime/social-types.ts +78 -0
- package/src/realtime/types.ts +53 -0
- package/src/realtime/wire-types.ts +72 -0
- package/src/rooms.ts +10 -0
- package/src/social.ts +18 -0
- package/src/types.ts +13 -0
- package/src/uistack/page-stack.ts +45 -0
- package/src/uistack/play-suspension.ts +82 -0
- package/src/uistack/types.ts +76 -0
- package/src/uistack/ui-stack.ts +144 -0
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The offline mutation queue. Writes apply to the local cache at once and
|
|
3
|
+
* queue a durable op; when the hub is reachable again the queue replays in
|
|
4
|
+
* order. Ops collapse as they are queued (a save's last write wins, `incr`s
|
|
5
|
+
* add up, `max`es keep the largest, a board keeps its best, profile patches
|
|
6
|
+
* merge), so the backlog stays small.
|
|
7
|
+
*
|
|
8
|
+
* The op shapes are the v1 client's, unchanged: a page upgraded from a
|
|
9
|
+
* vendored copy replays the queue that copy left in `localStorage`.
|
|
10
|
+
*/
|
|
11
|
+
import type { Json } from '@diffenderfer-games/hub-contract';
|
|
12
|
+
import type { SortDir } from '@diffenderfer-games/hub-contract';
|
|
13
|
+
import { isJson, isNullableString, isRecord, optionalNumber, optionalString, type UncheckedRecord } from '../storage/json-guards';
|
|
14
|
+
|
|
15
|
+
/** A score submission's options as queued (the metadata already JSON). */
|
|
16
|
+
export interface QueuedScoreOptions {
|
|
17
|
+
/** The board's title; only used when the board key is first created. */
|
|
18
|
+
readonly title?: string;
|
|
19
|
+
/** The sort direction; only used on board creation. Default `desc`. */
|
|
20
|
+
readonly sort?: SortDir;
|
|
21
|
+
/** Any JSON stored with the entry (a character, a run seed). */
|
|
22
|
+
readonly meta?: Json;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** A profile change: either part may be left out. */
|
|
26
|
+
export interface ProfilePatch {
|
|
27
|
+
/** Shown to other players; `null` clears it. */
|
|
28
|
+
displayName?: string | null;
|
|
29
|
+
/** The game's own profile data. */
|
|
30
|
+
data?: Json;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A queued op's id and when it was queued. */
|
|
34
|
+
interface QueueStamp {
|
|
35
|
+
/** Unique within this page: `<epoch ms>-<sequence>`. */
|
|
36
|
+
readonly id: string;
|
|
37
|
+
/** When it was queued (epoch ms). */
|
|
38
|
+
readonly ts: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A queued write, before it is stamped. */
|
|
42
|
+
export type QueueOpInput =
|
|
43
|
+
| { readonly kind: 'putSave'; readonly slot: string; readonly data: Json; readonly label: string | null }
|
|
44
|
+
| { readonly kind: 'deleteSave'; readonly slot: string }
|
|
45
|
+
| { readonly kind: 'setStat'; readonly key: string; readonly value: number }
|
|
46
|
+
| { readonly kind: 'maxStat'; readonly key: string; readonly value: number }
|
|
47
|
+
| { readonly kind: 'incrStat'; readonly key: string; readonly amount: number }
|
|
48
|
+
| { readonly kind: 'submitScore'; readonly key: string; readonly score: number; readonly opts: QueuedScoreOptions }
|
|
49
|
+
| { readonly kind: 'setProfile'; readonly patch: ProfilePatch };
|
|
50
|
+
|
|
51
|
+
/** A queued write, as stored under `hub:<slug>:queue`. */
|
|
52
|
+
export type QueueOp = QueueOpInput & QueueStamp;
|
|
53
|
+
|
|
54
|
+
/** The score options in a stored op, or `undefined` when they are malformed. */
|
|
55
|
+
function readScoreOptions(stored: UncheckedRecord): QueuedScoreOptions | undefined {
|
|
56
|
+
const title = optionalString(stored.title);
|
|
57
|
+
const sort = stored.sort === 'asc' || stored.sort === 'desc' ? stored.sort : undefined;
|
|
58
|
+
if (stored.meta !== undefined && !isJson(stored.meta)) {
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
return { ...(title === undefined ? {} : { title }), ...(sort === undefined ? {} : { sort }), ...(stored.meta === undefined ? {} : { meta: stored.meta }) };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The profile patch in a stored op, or `undefined` when it is malformed. */
|
|
65
|
+
function readProfilePatch(stored: UncheckedRecord): ProfilePatch | undefined {
|
|
66
|
+
if ((stored.displayName !== undefined && !isNullableString(stored.displayName)) || (stored.data !== undefined && !isJson(stored.data))) {
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
const patch: ProfilePatch = {};
|
|
70
|
+
if (stored.displayName !== undefined) {
|
|
71
|
+
patch.displayName = stored.displayName;
|
|
72
|
+
}
|
|
73
|
+
if (stored.data !== undefined) {
|
|
74
|
+
patch.data = stored.data;
|
|
75
|
+
}
|
|
76
|
+
return patch;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** One stored op's write, or `undefined` when it is not a known, well-formed op. */
|
|
80
|
+
function readOpInput(stored: UncheckedRecord): QueueOpInput | undefined {
|
|
81
|
+
const slot = optionalString(stored.slot);
|
|
82
|
+
const key = optionalString(stored.key);
|
|
83
|
+
const statValue = optionalNumber(stored.value);
|
|
84
|
+
switch (stored.kind) {
|
|
85
|
+
case 'putSave':
|
|
86
|
+
return slot !== undefined && isJson(stored.data) && isNullableString(stored.label) ? { kind: 'putSave', slot, data: stored.data, label: stored.label } : undefined;
|
|
87
|
+
case 'deleteSave':
|
|
88
|
+
return slot === undefined ? undefined : { kind: 'deleteSave', slot };
|
|
89
|
+
case 'setStat':
|
|
90
|
+
case 'maxStat':
|
|
91
|
+
return key !== undefined && statValue !== undefined ? { kind: stored.kind, key, value: statValue } : undefined;
|
|
92
|
+
case 'incrStat': {
|
|
93
|
+
const amount = optionalNumber(stored.amount);
|
|
94
|
+
return key !== undefined && amount !== undefined ? { kind: 'incrStat', key, amount } : undefined;
|
|
95
|
+
}
|
|
96
|
+
case 'submitScore': {
|
|
97
|
+
const score = optionalNumber(stored.score);
|
|
98
|
+
const opts = isRecord(stored.opts) ? readScoreOptions(stored.opts) : undefined;
|
|
99
|
+
return key !== undefined && score !== undefined && opts !== undefined ? { kind: 'submitScore', key, score, opts } : undefined;
|
|
100
|
+
}
|
|
101
|
+
case 'setProfile': {
|
|
102
|
+
const patch = isRecord(stored.patch) ? readProfilePatch(stored.patch) : undefined;
|
|
103
|
+
return patch === undefined ? undefined : { kind: 'setProfile', patch };
|
|
104
|
+
}
|
|
105
|
+
default:
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The well-formed ops of a stored queue, in order; anything malformed is dropped. */
|
|
111
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: a queue read back from localStorage (possibly written by a v1 client)
|
|
112
|
+
export function readQueue(stored: unknown): QueueOp[] {
|
|
113
|
+
if (!Array.isArray(stored)) {
|
|
114
|
+
return [];
|
|
115
|
+
}
|
|
116
|
+
return stored.flatMap((entry): QueueOp[] => {
|
|
117
|
+
if (!isRecord(entry)) {
|
|
118
|
+
return [];
|
|
119
|
+
}
|
|
120
|
+
const input = readOpInput(entry);
|
|
121
|
+
const id = optionalString(entry.id);
|
|
122
|
+
const ts = optionalNumber(entry.ts);
|
|
123
|
+
return input === undefined || id === undefined || ts === undefined ? [] : [{ ...input, id, ts }];
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The better of two scores on a board sorted `sort` (`desc` by default). */
|
|
128
|
+
export function betterScore(first: number, second: number, sort: SortDir | undefined): number {
|
|
129
|
+
return sort === 'asc' ? Math.min(first, second) : Math.max(first, second);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The op that `queued` becomes when `incoming` collapses into it, or `undefined` when they don't collapse. */
|
|
133
|
+
function collapsedOp(queued: QueueOp, incoming: QueueOp): QueueOp | undefined {
|
|
134
|
+
if (queued.kind === 'incrStat' && incoming.kind === 'incrStat' && queued.key === incoming.key) {
|
|
135
|
+
return { ...queued, amount: queued.amount + incoming.amount };
|
|
136
|
+
}
|
|
137
|
+
if (queued.kind === 'maxStat' && incoming.kind === 'maxStat' && queued.key === incoming.key) {
|
|
138
|
+
return { ...queued, value: Math.max(queued.value, incoming.value) };
|
|
139
|
+
}
|
|
140
|
+
if (queued.kind === 'setStat' && incoming.kind === 'setStat' && queued.key === incoming.key) {
|
|
141
|
+
return { ...queued, value: incoming.value };
|
|
142
|
+
}
|
|
143
|
+
if (queued.kind === 'submitScore' && incoming.kind === 'submitScore' && queued.key === incoming.key) {
|
|
144
|
+
return { ...queued, score: betterScore(queued.score, incoming.score, incoming.opts.sort), opts: incoming.opts };
|
|
145
|
+
}
|
|
146
|
+
if (queued.kind === 'setProfile' && incoming.kind === 'setProfile') {
|
|
147
|
+
return { ...queued, patch: { ...queued.patch, ...incoming.patch } };
|
|
148
|
+
}
|
|
149
|
+
return undefined;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Whether an op writes save slot `slot`. */
|
|
153
|
+
function writesSlot(op: QueueOp, slot: string): boolean {
|
|
154
|
+
return (op.kind === 'putSave' || op.kind === 'deleteSave') && op.slot === slot;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* The queue with `incoming` added: a save or delete replaces any queued
|
|
159
|
+
* write to the same slot (and goes last); a compatible op merges into the
|
|
160
|
+
* first queued one in place; anything else is appended.
|
|
161
|
+
*/
|
|
162
|
+
export function enqueueOp(queue: readonly QueueOp[], incoming: QueueOp): QueueOp[] {
|
|
163
|
+
if (incoming.kind === 'putSave' || incoming.kind === 'deleteSave') {
|
|
164
|
+
return [...queue.filter((op) => !writesSlot(op, incoming.slot)), incoming];
|
|
165
|
+
}
|
|
166
|
+
const mergeAt = queue.findIndex((op) => collapsedOp(op, incoming) !== undefined);
|
|
167
|
+
if (mergeAt < 0) {
|
|
168
|
+
return [...queue, incoming];
|
|
169
|
+
}
|
|
170
|
+
return queue.map((op, i) => (i === mergeAt ? (collapsedOp(op, incoming) ?? op) : op));
|
|
171
|
+
}
|
package/src/core/page.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the page tells the client: the host's injected `window.__HUB__`
|
|
3
|
+
* (contract `HubInject`), the game's slug, and the API base. A page the host
|
|
4
|
+
* did not inject (`game.hub: false`, local development) has no `__HUB__`.
|
|
5
|
+
*/
|
|
6
|
+
import type { HubInject } from '@diffenderfer-games/hub-contract';
|
|
7
|
+
import { isRecord, optionalString } from './storage/json-guards';
|
|
8
|
+
|
|
9
|
+
declare global {
|
|
10
|
+
interface Window {
|
|
11
|
+
/** The host's injected config (contract `HubInject`); read through {@link injectedConfig}. */
|
|
12
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: written by the host's inline script, read field by field
|
|
13
|
+
__HUB__?: unknown;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The fields of `window.__HUB__` the core client reads. */
|
|
18
|
+
export type InjectedConfig = Partial<Pick<HubInject, 'slug'>> & { readonly apiBase?: string };
|
|
19
|
+
|
|
20
|
+
/** Whether this code runs in a browser page. */
|
|
21
|
+
export function isBrowserPage(): boolean {
|
|
22
|
+
return typeof window !== 'undefined';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Whether the host injected this page (`window.__HUB__` exists), so the menu and social runtime can arrive. */
|
|
26
|
+
export function isHubInjectedPage(): boolean {
|
|
27
|
+
return isBrowserPage() && isRecord(window.__HUB__);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The injected config's slug and API base, read defensively (empty outside a hub page). */
|
|
31
|
+
export function injectedConfig(): InjectedConfig {
|
|
32
|
+
if (!isBrowserPage() || !isRecord(window.__HUB__)) {
|
|
33
|
+
return {};
|
|
34
|
+
}
|
|
35
|
+
const slug = optionalString(window.__HUB__.slug);
|
|
36
|
+
const apiBase = optionalString(window.__HUB__.apiBase);
|
|
37
|
+
return { ...(slug === undefined ? {} : { slug }), ...(apiBase === undefined ? {} : { apiBase }) };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The game's slug: the injected one, else the first URL path segment, else `null`. */
|
|
41
|
+
export function detectSlug(): string | null {
|
|
42
|
+
const injectedSlug = injectedConfig().slug;
|
|
43
|
+
if (injectedSlug !== undefined && injectedSlug !== '') {
|
|
44
|
+
return injectedSlug;
|
|
45
|
+
}
|
|
46
|
+
if (typeof location === 'undefined') {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
return location.pathname.split('/').find((segment) => segment !== '') ?? null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** An API base made absolute against the page origin (`http://localhost` outside a browser), without a trailing slash. */
|
|
53
|
+
export function absoluteApiBase(apiBase: string): string {
|
|
54
|
+
const origin = typeof location === 'undefined' ? 'http://localhost' : location.origin;
|
|
55
|
+
return new URL(apiBase, origin).toString().replace(/\/$/, '');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The page's API base: the injected one, else `/_api`, made absolute. */
|
|
59
|
+
export function detectApiBase(): string {
|
|
60
|
+
return absoluteApiBase(injectedConfig().apiBase ?? '/_api');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Dispatch a `CustomEvent` on `window` (no-op outside a browser; listener errors never reach the caller). */
|
|
64
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: event details are whatever the event documents; listeners read them
|
|
65
|
+
export function emitWindowEvent(eventName: string, detail?: unknown): void {
|
|
66
|
+
if (!isBrowserPage()) {
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
try {
|
|
70
|
+
window.dispatchEvent(new CustomEvent(eventName, { detail }));
|
|
71
|
+
} catch {
|
|
72
|
+
// A page without CustomEvent (very old browsers) misses the event.
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-endpoint request and reply types, derived from the contract's spec
|
|
3
|
+
* **type** only (`import type`, erased at build): the browser bundle carries
|
|
4
|
+
* the route table, never the schemas (plan D16).
|
|
5
|
+
*/
|
|
6
|
+
import type { CallReturn, ClientData } from '@ayepi/core/client';
|
|
7
|
+
import type { PublicEndpoints } from '@diffenderfer-games/hub-contract';
|
|
8
|
+
|
|
9
|
+
/** The name of a public REST endpoint (`getCurrentUser`, `writeSave`, ...). */
|
|
10
|
+
export type EndpointName = keyof PublicEndpoints;
|
|
11
|
+
|
|
12
|
+
/** One endpoint's request fields: path params, query and body merged into one object. */
|
|
13
|
+
export type EndpointFields<K extends EndpointName> = ClientData<PublicEndpoints[K]>;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* An endpoint that declares several success statuses comes back from ayepi's
|
|
17
|
+
* client as `{ status, data }`; this client always hands back the body.
|
|
18
|
+
*/
|
|
19
|
+
type ReplyBody<Reply> = Reply extends { readonly status: number; readonly data: infer Body } ? Body : Reply;
|
|
20
|
+
|
|
21
|
+
/** One endpoint's success reply body. */
|
|
22
|
+
export type EndpointReply<K extends EndpointName> = ReplyBody<Awaited<CallReturn<PublicEndpoints[K]>>>;
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The REST transport: a small fetch router over the contract's route table
|
|
3
|
+
* (plan §12 A10). It splits one merged fields object into the path, query
|
|
4
|
+
* and JSON body the way ayepi's client does, stamps `x-hub-client`, and turns
|
|
5
|
+
* failures into {@link HubError}s. It carries no schemas: replies are typed
|
|
6
|
+
* from the contract and trusted, as ayepi's zod-free client trusts them.
|
|
7
|
+
*/
|
|
8
|
+
import { errorFor, HubError, readErrorFields, UNSUPPORTED_BY_HUB } from '../errors';
|
|
9
|
+
import { isRecord } from '../storage/json-guards';
|
|
10
|
+
import { HUB_CLIENT_VERSION } from '../version/client-version.gen';
|
|
11
|
+
import type { EndpointFields, EndpointName, EndpointReply } from './endpoint-types';
|
|
12
|
+
import { ROUTES } from './routes.gen';
|
|
13
|
+
|
|
14
|
+
/** The header that tells the hub which client version is calling. */
|
|
15
|
+
export const CLIENT_VERSION_HEADER = 'x-hub-client';
|
|
16
|
+
|
|
17
|
+
/** What both hubs answer for a route they do not have. */
|
|
18
|
+
const NO_SUCH_ENDPOINT = 'No such API endpoint.';
|
|
19
|
+
|
|
20
|
+
/** How a {@link RestClient} reaches the hub. */
|
|
21
|
+
export interface RestClientOptions {
|
|
22
|
+
/** The API's absolute base URL without a trailing slash, e.g. `https://diffenderfer.games/_api`. */
|
|
23
|
+
readonly apiBase: string;
|
|
24
|
+
/** The fetch to use. */
|
|
25
|
+
readonly fetch: typeof fetch;
|
|
26
|
+
/** Called whenever the hub answered at all (any status): the network is up. */
|
|
27
|
+
readonly onReachable?: () => void;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The arguments of a call: the fields, optional when the endpoint takes none that are required. */
|
|
31
|
+
export type CallArguments<K extends EndpointName> = Partial<EndpointFields<K>> extends EndpointFields<K>
|
|
32
|
+
? [fields?: EndpointFields<K>]
|
|
33
|
+
: [fields: EndpointFields<K>];
|
|
34
|
+
|
|
35
|
+
/** Typed calls to the hub's public REST API. */
|
|
36
|
+
export interface RestClient {
|
|
37
|
+
/** The API's absolute base URL. */
|
|
38
|
+
readonly apiBase: string;
|
|
39
|
+
/** Call an endpoint; resolves with its reply body, rejects with a {@link HubError}. */
|
|
40
|
+
call<K extends EndpointName>(name: K, ...fieldsArgument: CallArguments<K>): Promise<EndpointReply<K>>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** One field value as URL text. */
|
|
44
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: a request field value of any contract type
|
|
45
|
+
function urlText(fieldValue: unknown): string {
|
|
46
|
+
if (typeof fieldValue === 'string') {
|
|
47
|
+
return fieldValue;
|
|
48
|
+
}
|
|
49
|
+
if (typeof fieldValue === 'number' || typeof fieldValue === 'boolean') {
|
|
50
|
+
return String(fieldValue);
|
|
51
|
+
}
|
|
52
|
+
return JSON.stringify(fieldValue);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The request one call makes: its URL (under the API base), method and JSON body. */
|
|
56
|
+
export interface PlannedRequest {
|
|
57
|
+
/** The path and query, e.g. `/games/pool/leaderboards/best?limit=50`. */
|
|
58
|
+
readonly pathAndQuery: string;
|
|
59
|
+
/** The HTTP method. */
|
|
60
|
+
readonly method: string;
|
|
61
|
+
/** The JSON body text, or `undefined` for none. */
|
|
62
|
+
readonly bodyText: string | undefined;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Split merged fields into path, query and body for one endpoint: `:name`
|
|
67
|
+
* segments take their field, query keys go to the query string, and the
|
|
68
|
+
* rest is the JSON body. POST and PUT always send a body (`{}` when empty),
|
|
69
|
+
* as the v1 client did; DELETE sends one only when it has fields.
|
|
70
|
+
*/
|
|
71
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: the caller's typed fields, walked generically
|
|
72
|
+
export function planRequest(name: EndpointName, fields: unknown): PlannedRequest {
|
|
73
|
+
const route = ROUTES[name];
|
|
74
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: the caller's typed fields, walked generically
|
|
75
|
+
const remaining = new Map<string, unknown>(Object.entries(isRecord(fields) ? fields : {}).filter(([, fieldValue]) => fieldValue !== undefined));
|
|
76
|
+
const path = route.path.replace(/:([A-Za-z]+)/g, (_segment, paramName: string) => {
|
|
77
|
+
const paramValue = remaining.get(paramName);
|
|
78
|
+
remaining.delete(paramName);
|
|
79
|
+
return encodeURIComponent(urlText(paramValue));
|
|
80
|
+
});
|
|
81
|
+
const queryKeys: readonly string[] = route.method === 'GET' ? [...remaining.keys()] : route.query;
|
|
82
|
+
const query = new URLSearchParams();
|
|
83
|
+
for (const key of queryKeys) {
|
|
84
|
+
const queryValue = remaining.get(key);
|
|
85
|
+
remaining.delete(key);
|
|
86
|
+
if (queryValue !== undefined && queryValue !== null) {
|
|
87
|
+
query.set(key, urlText(queryValue));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const queryText = query.toString();
|
|
91
|
+
const hasBody = route.method === 'POST' || route.method === 'PUT' || (route.method === 'DELETE' && remaining.size > 0);
|
|
92
|
+
return {
|
|
93
|
+
pathAndQuery: queryText === '' ? path : `${path}?${queryText}`,
|
|
94
|
+
method: route.method,
|
|
95
|
+
bodyText: hasBody ? JSON.stringify(Object.fromEntries(remaining)) : undefined,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The reply body, typed by the contract. This is the client's one trust
|
|
101
|
+
* boundary on replies: there is no zod in the browser bundle (plan D16).
|
|
102
|
+
*/
|
|
103
|
+
async function readReply<Reply>(response: Response): Promise<Reply> {
|
|
104
|
+
try {
|
|
105
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-return -- trust boundary: the hub's JSON reply, typed by the contract (the zod-free client trusts the server, plan D16)
|
|
106
|
+
return await response.json();
|
|
107
|
+
} catch {
|
|
108
|
+
throw new HubError('The hub sent a reply that is not JSON.', response.status);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The error for a failed response. */
|
|
113
|
+
async function failureOf(name: EndpointName, response: Response): Promise<HubError> {
|
|
114
|
+
let fields = readErrorFields(undefined);
|
|
115
|
+
try {
|
|
116
|
+
fields = readErrorFields(await response.json());
|
|
117
|
+
} catch {
|
|
118
|
+
// A non-JSON error body keeps the generic message.
|
|
119
|
+
}
|
|
120
|
+
if (response.status === 404 && fields.error === NO_SUCH_ENDPOINT) {
|
|
121
|
+
return new HubError(`This hub does not have "${name}" yet: deploy the hub first, or use an older client.`, 404, { code: UNSUPPORTED_BY_HUB });
|
|
122
|
+
}
|
|
123
|
+
return errorFor(fields.error ?? `Request failed (${response.status})`, response.status, fields);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** A REST client for one API base. */
|
|
127
|
+
export function createRestClient(options: RestClientOptions): RestClient {
|
|
128
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: the caller's typed fields, walked generically
|
|
129
|
+
async function send<Reply>(name: EndpointName, fields: unknown): Promise<Reply> {
|
|
130
|
+
const planned = planRequest(name, fields);
|
|
131
|
+
let response: Response;
|
|
132
|
+
try {
|
|
133
|
+
response = await options.fetch(options.apiBase + planned.pathAndQuery, {
|
|
134
|
+
method: planned.method,
|
|
135
|
+
credentials: 'same-origin',
|
|
136
|
+
headers: { 'content-type': 'application/json', [CLIENT_VERSION_HEADER]: HUB_CLIENT_VERSION },
|
|
137
|
+
...(planned.bodyText === undefined ? {} : { body: planned.bodyText }),
|
|
138
|
+
});
|
|
139
|
+
} catch (failure) {
|
|
140
|
+
throw new HubError(`Hub unreachable: ${failure instanceof Error ? failure.message : String(failure)}`);
|
|
141
|
+
}
|
|
142
|
+
options.onReachable?.();
|
|
143
|
+
if (!response.ok) {
|
|
144
|
+
throw await failureOf(name, response);
|
|
145
|
+
}
|
|
146
|
+
return readReply<Reply>(response);
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
apiBase: options.apiBase,
|
|
150
|
+
call: (name, ...fieldsArgument) => send(name, fieldsArgument[0]),
|
|
151
|
+
};
|
|
152
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Generated by tools/hub-client/generate.ts. Do not edit; run `npm run gen:hub-client` in next/.
|
|
2
|
+
/** Every public REST endpoint's method, path (under `/_api`) and query keys, from the contract. */
|
|
3
|
+
export const ROUTES = {
|
|
4
|
+
ensureGuestSession: { method: 'POST', path: '/auth/guest', query: [] },
|
|
5
|
+
signUpWithPassword: { method: 'POST', path: '/auth/signup', query: [] },
|
|
6
|
+
logInWithPassword: { method: 'POST', path: '/auth/login', query: [] },
|
|
7
|
+
logOut: { method: 'POST', path: '/auth/logout', query: [] },
|
|
8
|
+
getCurrentUser: { method: 'GET', path: '/me', query: [] },
|
|
9
|
+
claimGuestAccount: { method: 'POST', path: '/auth/claim', query: [] },
|
|
10
|
+
listGames: { method: 'GET', path: '/games', query: [] },
|
|
11
|
+
listWhatsNewNotes: { method: 'GET', path: '/changes', query: ['game', 'since'] },
|
|
12
|
+
listFavoriteGames: { method: 'GET', path: '/favorites', query: [] },
|
|
13
|
+
setGameFavorite: { method: 'PUT', path: '/favorites/:slug', query: [] },
|
|
14
|
+
markWhatsNewSeen: { method: 'POST', path: '/changes/seen', query: [] },
|
|
15
|
+
getGameStats: { method: 'GET', path: '/games/:slug/stats', query: ['user'] },
|
|
16
|
+
getGameProfile: { method: 'GET', path: '/games/:slug/profile', query: [] },
|
|
17
|
+
setGameProfile: { method: 'PUT', path: '/games/:slug/profile', query: [] },
|
|
18
|
+
listSaves: { method: 'GET', path: '/games/:slug/saves', query: [] },
|
|
19
|
+
getSave: { method: 'GET', path: '/games/:slug/saves/:slot', query: [] },
|
|
20
|
+
writeSave: { method: 'PUT', path: '/games/:slug/saves/:slot', query: [] },
|
|
21
|
+
deleteSave: { method: 'DELETE', path: '/games/:slug/saves/:slot', query: [] },
|
|
22
|
+
updateGameStat: { method: 'POST', path: '/games/:slug/stats', query: [] },
|
|
23
|
+
resetMyGameProgress: { method: 'POST', path: '/games/:slug/reset', query: [] },
|
|
24
|
+
listMyLeaderboardRecords: { method: 'GET', path: '/me/records', query: ['game'] },
|
|
25
|
+
getMyOfflineSnapshot: { method: 'GET', path: '/me/snapshot', query: ['top'] },
|
|
26
|
+
listTopOfEveryLeaderboard: { method: 'GET', path: '/leaderboards', query: ['top'] },
|
|
27
|
+
listGameLeaderboards: { method: 'GET', path: '/games/:slug/leaderboards', query: [] },
|
|
28
|
+
getLeaderboard: { method: 'GET', path: '/games/:slug/leaderboards/:key', query: ['limit'] },
|
|
29
|
+
submitScore: { method: 'POST', path: '/games/:slug/leaderboards/:key/scores', query: [] },
|
|
30
|
+
listDailyChallengesForAllGames: { method: 'GET', path: '/daily', query: [] },
|
|
31
|
+
getGameDailyChallenges: { method: 'GET', path: '/games/:slug/daily', query: [] },
|
|
32
|
+
startDailyChallenge: { method: 'POST', path: '/games/:slug/daily/:day/start', query: [] },
|
|
33
|
+
completeDailyChallenge: { method: 'POST', path: '/games/:slug/daily/:day/complete', query: [] },
|
|
34
|
+
getMyInventory: { method: 'GET', path: '/games/:slug/inventory', query: [] },
|
|
35
|
+
grantInventoryItems: { method: 'POST', path: '/games/:slug/inventory/grant', query: [] },
|
|
36
|
+
exchangeInventoryItems: { method: 'POST', path: '/games/:slug/inventory/exchange', query: [] },
|
|
37
|
+
getPlayerInventory: { method: 'GET', path: '/games/:slug/players/:userId/inventory', query: [] },
|
|
38
|
+
listTradePartners: { method: 'GET', path: '/games/:slug/trades/players', query: [] },
|
|
39
|
+
listMyTrades: { method: 'GET', path: '/games/:slug/trades', query: ['box', 'status'] },
|
|
40
|
+
declineTrade: { method: 'POST', path: '/games/:slug/trades/:id/decline', query: [] },
|
|
41
|
+
cancelTrade: { method: 'POST', path: '/games/:slug/trades/:id/cancel', query: [] },
|
|
42
|
+
createTrade: { method: 'POST', path: '/games/:slug/trades', query: [] },
|
|
43
|
+
acceptTrade: { method: 'POST', path: '/games/:slug/trades/:id/accept', query: [] },
|
|
44
|
+
counterTradeOffer: { method: 'POST', path: '/games/:slug/trades/:id/counter', query: [] },
|
|
45
|
+
getSiteAnalytics: { method: 'GET', path: '/analytics', query: [] },
|
|
46
|
+
reportClientError: { method: 'POST', path: '/client-log', query: [] },
|
|
47
|
+
recordGameEvent: { method: 'POST', path: '/games/:slug/events', query: [] },
|
|
48
|
+
getGameAnalytics: { method: 'GET', path: '/games/:slug/analytics', query: [] },
|
|
49
|
+
getSocialConfig: { method: 'GET', path: '/social/config', query: [] },
|
|
50
|
+
getOnlineCounts: { method: 'GET', path: '/social/counts', query: [] },
|
|
51
|
+
getMySocialProfile: { method: 'GET', path: '/social/me', query: [] },
|
|
52
|
+
listFriendsAndRequests: { method: 'GET', path: '/social/friends', query: [] },
|
|
53
|
+
findPlayerByName: { method: 'GET', path: '/social/players/by-name/:name', query: [] },
|
|
54
|
+
getPlayerCard: { method: 'GET', path: '/social/players/:id', query: [] },
|
|
55
|
+
updateMySocialProfile: { method: 'PUT', path: '/social/me', query: [] },
|
|
56
|
+
setParentChatLock: { method: 'POST', path: '/social/chat-lock', query: [] },
|
|
57
|
+
sendFriendRequest: { method: 'POST', path: '/social/friends', query: [] },
|
|
58
|
+
acceptFriendRequest: { method: 'POST', path: '/social/friends/:id/accept', query: [] },
|
|
59
|
+
declineFriendRequest: { method: 'POST', path: '/social/friends/:id/decline', query: [] },
|
|
60
|
+
removeFriend: { method: 'DELETE', path: '/social/friends/:id', query: [] },
|
|
61
|
+
setFriendNotifications: { method: 'PUT', path: '/social/friends/:id/notify', query: [] },
|
|
62
|
+
blockPlayer: { method: 'POST', path: '/social/blocks', query: [] },
|
|
63
|
+
unblockPlayer: { method: 'DELETE', path: '/social/blocks/:id', query: [] },
|
|
64
|
+
listRecentPlayers: { method: 'GET', path: '/social/recent', query: [] },
|
|
65
|
+
listConversations: { method: 'GET', path: '/social/conversations', query: [] },
|
|
66
|
+
listDirectMessages: { method: 'GET', path: '/social/messages/:userId', query: ['before'] },
|
|
67
|
+
sendDirectMessage: { method: 'POST', path: '/social/messages/:userId', query: [] },
|
|
68
|
+
markDirectMessagesRead: { method: 'POST', path: '/social/messages/:userId/read', query: [] },
|
|
69
|
+
getNotificationPreferences: { method: 'GET', path: '/social/notify', query: [] },
|
|
70
|
+
unsubscribeFromPush: { method: 'DELETE', path: '/social/push', query: [] },
|
|
71
|
+
setNotificationPreferences: { method: 'PUT', path: '/social/notify', query: [] },
|
|
72
|
+
subscribeToPush: { method: 'POST', path: '/social/push', query: [] },
|
|
73
|
+
fileReport: { method: 'POST', path: '/social/reports', query: [] },
|
|
74
|
+
listPublicSuggestions: { method: 'GET', path: '/suggestions', query: ['sort'] },
|
|
75
|
+
submitSuggestion: { method: 'POST', path: '/suggestions', query: [] },
|
|
76
|
+
voteForSuggestion: { method: 'POST', path: '/suggestions/:id/vote', query: [] },
|
|
77
|
+
removeSuggestionVote: { method: 'DELETE', path: '/suggestions/:id/vote', query: [] },
|
|
78
|
+
withdrawSuggestion: { method: 'DELETE', path: '/suggestions/:id', query: [] },
|
|
79
|
+
sendGameInvite: { method: 'POST', path: '/mp/invites', query: [] },
|
|
80
|
+
acceptGameInvite: { method: 'POST', path: '/mp/invites/:id/accept', query: [] },
|
|
81
|
+
declineGameInvite: { method: 'POST', path: '/mp/invites/:id/decline', query: [] },
|
|
82
|
+
cancelGameInvite: { method: 'DELETE', path: '/mp/invites/:id', query: [] },
|
|
83
|
+
redeemLaunchToken: { method: 'GET', path: '/mp/launch/:token', query: [] },
|
|
84
|
+
setPartyJoinInfo: { method: 'POST', path: '/mp/parties/:id/join-info', query: [] },
|
|
85
|
+
leaveParty: { method: 'POST', path: '/mp/parties/:id/leave', query: [] },
|
|
86
|
+
launchIntoFriendsRoom: { method: 'POST', path: '/mp/join', query: [] },
|
|
87
|
+
getGameServerTicket: { method: 'POST', path: '/mp/ticket', query: [] },
|
|
88
|
+
listMyRaceHistory: { method: 'GET', path: '/race/history', query: ['game', 'with', 'before', 'limit'] },
|
|
89
|
+
getHubVersion: { method: 'GET', path: '/version', query: [] },
|
|
90
|
+
} as const;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small type guards for values this client did not create: JSON read back
|
|
3
|
+
* from `localStorage`, error bodies, objects from other bundles. The browser
|
|
4
|
+
* client carries no zod (plan D16), so these replace schema parsing on the
|
|
5
|
+
* few shapes it reads.
|
|
6
|
+
*/
|
|
7
|
+
import type { Json } from '@diffenderfer-games/hub-contract';
|
|
8
|
+
|
|
9
|
+
/** A plain object's fields, not yet checked. */
|
|
10
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: the fields of a value read from storage or another bundle
|
|
11
|
+
export type UncheckedRecord = Readonly<Record<string, unknown>>;
|
|
12
|
+
|
|
13
|
+
/** Whether `candidate` is a non-null, non-array object. */
|
|
14
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: checks a value read from storage or another bundle
|
|
15
|
+
export function isRecord(candidate: unknown): candidate is UncheckedRecord {
|
|
16
|
+
return typeof candidate === 'object' && candidate !== null && !Array.isArray(candidate);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** `candidate` when it is a string, else `undefined`. */
|
|
20
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: one field of an unchecked record
|
|
21
|
+
export function optionalString(candidate: unknown): string | undefined {
|
|
22
|
+
return typeof candidate === 'string' ? candidate : undefined;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** `candidate` when it is a finite number, else `undefined`. */
|
|
26
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: one field of an unchecked record
|
|
27
|
+
export function optionalNumber(candidate: unknown): number | undefined {
|
|
28
|
+
return typeof candidate === 'number' && Number.isFinite(candidate) ? candidate : undefined;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Whether `candidate` is a string or `null`. */
|
|
32
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: one field of an unchecked record
|
|
33
|
+
export function isNullableString(candidate: unknown): candidate is string | null {
|
|
34
|
+
return candidate === null || typeof candidate === 'string';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Whether `candidate` is a JSON value (what `JSON.parse` can return). */
|
|
38
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: checks a value read from storage
|
|
39
|
+
export function isJson(candidate: unknown): candidate is Json {
|
|
40
|
+
if (candidate === null || typeof candidate === 'string' || typeof candidate === 'boolean') {
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
if (typeof candidate === 'number') {
|
|
44
|
+
return Number.isFinite(candidate);
|
|
45
|
+
}
|
|
46
|
+
if (Array.isArray(candidate)) {
|
|
47
|
+
return candidate.every(isJson);
|
|
48
|
+
}
|
|
49
|
+
return isRecord(candidate) && Object.values(candidate).every(isJson);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Whether `candidate` is an object whose every value is a finite number. */
|
|
53
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: checks a value read from storage
|
|
54
|
+
export function isNumberRecord(candidate: unknown): candidate is Readonly<Record<string, number>> {
|
|
55
|
+
return isRecord(candidate) && Object.values(candidate).every((entry) => optionalNumber(entry) !== undefined);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The strings in `candidate`, or an empty list when it is not an array. */
|
|
59
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: a list read from storage
|
|
60
|
+
export function stringsIn(candidate: unknown): string[] {
|
|
61
|
+
return Array.isArray(candidate) ? candidate.filter((entry): entry is string => typeof entry === 'string') : [];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Parse JSON text without throwing: `undefined` when it is not JSON. */
|
|
65
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: text read from storage, checked by the caller's guard next
|
|
66
|
+
export function parseJsonText(text: string): unknown {
|
|
67
|
+
try {
|
|
68
|
+
// eslint-disable-next-line no-restricted-syntax -- trust boundary: JSON.parse's result, checked by the caller's guard next
|
|
69
|
+
const parsed: unknown = JSON.parse(text);
|
|
70
|
+
return parsed;
|
|
71
|
+
} catch {
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The string store behind the offline cache and queues: `localStorage` when
|
|
3
|
+
* the page has it, else an in-memory map (privacy mode, Node, tests). Every
|
|
4
|
+
* key keeps the v1 client's name, so a page upgraded from a vendored copy
|
|
5
|
+
* still reads the queue and cache that copy wrote.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** A string key-value store with `localStorage`'s semantics. */
|
|
9
|
+
export interface KeyValueStore {
|
|
10
|
+
/** The stored text, or `null`. */
|
|
11
|
+
read(key: string): string | null;
|
|
12
|
+
/** Store text; a full or blocked storage is ignored. */
|
|
13
|
+
write(key: string, text: string): void;
|
|
14
|
+
/** Forget a key. */
|
|
15
|
+
remove(key: string): void;
|
|
16
|
+
/** Every stored key. */
|
|
17
|
+
keys(): string[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A store backed by a `Storage` (`localStorage`). */
|
|
21
|
+
function storageBacked(storage: Storage): KeyValueStore {
|
|
22
|
+
return {
|
|
23
|
+
read: (key) => storage.getItem(key),
|
|
24
|
+
write: (key, text) => {
|
|
25
|
+
try {
|
|
26
|
+
storage.setItem(key, text);
|
|
27
|
+
} catch {
|
|
28
|
+
// A full or blocked storage loses the write, as in v1.
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
remove: (key) => {
|
|
32
|
+
storage.removeItem(key);
|
|
33
|
+
},
|
|
34
|
+
keys: () => Object.keys(storage),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** A store held in memory for this page only. */
|
|
39
|
+
export function createMemoryStore(): KeyValueStore {
|
|
40
|
+
const entries = new Map<string, string>();
|
|
41
|
+
return {
|
|
42
|
+
read: (key) => entries.get(key) ?? null,
|
|
43
|
+
write: (key, text) => {
|
|
44
|
+
entries.set(key, text);
|
|
45
|
+
},
|
|
46
|
+
remove: (key) => {
|
|
47
|
+
entries.delete(key);
|
|
48
|
+
},
|
|
49
|
+
keys: () => [...entries.keys()],
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The page's `localStorage`, or `undefined` when it is missing or throws (privacy mode). */
|
|
54
|
+
function pageStorage(): Storage | undefined {
|
|
55
|
+
try {
|
|
56
|
+
return typeof localStorage === 'undefined' ? undefined : localStorage;
|
|
57
|
+
} catch {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** `localStorage` when available, else a fresh in-memory store. */
|
|
63
|
+
export function createPageStore(): KeyValueStore {
|
|
64
|
+
const storage = pageStorage();
|
|
65
|
+
return storage === undefined ? createMemoryStore() : storageBacked(storage);
|
|
66
|
+
}
|