dopaminejs 2.4.0 → 2.5.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dopaminejs",
3
- "version": "2.4.0",
3
+ "version": "2.5.0",
4
4
  "description": "Progression mechanics for web apps: XP, levels, achievements and timezone-correct daily streaks, with the particles and sound to make them land. Zero dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/dopamine.cjs",
@@ -16,6 +16,11 @@
16
16
  "import": "./dist/engine.js",
17
17
  "require": "./dist/engine.cjs"
18
18
  },
19
+ "./core": {
20
+ "types": "./types/core.d.ts",
21
+ "import": "./dist/core.js",
22
+ "require": "./dist/core.cjs"
23
+ },
19
24
  "./style.css": "./dist/style.css"
20
25
  },
21
26
  "sideEffects": false,
@@ -29,6 +29,28 @@ export class SoundManager {
29
29
 
30
30
  // Queued follow-up tones, so destroy() can cancel them.
31
31
  this._timers = new Set();
32
+
33
+ // unlockOn removers, so destroy() takes listeners that never fired off too.
34
+ this._unlocks = new Set();
35
+ }
36
+
37
+ /**
38
+ * Start audio on the first gesture on `target`. Browsers keep an
39
+ * AudioContext silent until the page gets one, and a touch pointerdown
40
+ * is not one, so the default waits for pointerup. Returns a remover.
41
+ */
42
+ unlockOn(target, events = ['pointerup', 'touchend', 'keydown']) {
43
+ const remove = () => {
44
+ for (const type of events) target.removeEventListener(type, unlock);
45
+ this._unlocks.delete(remove);
46
+ };
47
+ const unlock = () => {
48
+ remove();
49
+ this.initAudio();
50
+ };
51
+ for (const type of events) target.addEventListener(type, unlock);
52
+ this._unlocks.add(remove);
53
+ return remove;
32
54
  }
33
55
 
34
56
  /**
@@ -300,6 +322,8 @@ export class SoundManager {
300
322
  * Browsers cap the number of live AudioContexts per page.
301
323
  */
302
324
  destroy() {
325
+ for (const remove of [...this._unlocks]) remove();
326
+
303
327
  for (const id of this._timers) {
304
328
  clearTimeout(id);
305
329
  }
@@ -56,15 +56,35 @@ export class DataService {
56
56
 
57
57
  /**
58
58
  * Load data from local storage
59
- * @param {string} key
60
- * @param {any} defaultValue
59
+ *
60
+ * A failed read returns `defaultValue`, so a caller cannot tell "nothing
61
+ * saved" from "could not read". Pass `{ strict: true }` to get the error
62
+ * instead; unparseable data then rejects with `code: 'DOPAMINE_CORRUPT'`
63
+ * and the raw string on `raw`.
64
+ * @param {string} key
65
+ * @param {any} defaultValue
66
+ * @param {{ strict?: boolean }} [options]
61
67
  */
62
- async load(key, defaultValue = null) {
68
+ async load(key, defaultValue = null, options = {}) {
69
+ let data;
63
70
  try {
64
71
  await this._tail;
65
- const data = await this.storage.getItem(this.prefix + key);
66
- return data ? JSON.parse(data) : defaultValue;
72
+ data = await this.storage.getItem(this.prefix + key);
73
+ } catch (e) {
74
+ if (options.strict) throw e;
75
+ console.error('Error loading data:', e);
76
+ return defaultValue;
77
+ }
78
+ if (!data) return defaultValue;
79
+ try {
80
+ return JSON.parse(data);
67
81
  } catch (e) {
82
+ if (options.strict) {
83
+ throw Object.assign(new Error(`[DopamineJS] saved "${key}" is not valid JSON`), {
84
+ code: 'DOPAMINE_CORRUPT',
85
+ raw: data,
86
+ });
87
+ }
68
88
  console.error('Error loading data:', e);
69
89
  return defaultValue;
70
90
  }
@@ -42,6 +42,20 @@ export class RewardSystem extends EventEmitter {
42
42
  // recordGame produced four full serializations of the player object.
43
43
  this._batchDepth = 0;
44
44
  this._pendingSave = false;
45
+
46
+ // Set when init() could not read storage. Saving stays off until a
47
+ // later init() reads it, so the saved player is never replaced.
48
+ this._loadFailed = false;
49
+ this._readFailed = false;
50
+ }
51
+
52
+ /**
53
+ * True when the last init() could not read the saved player, so nothing
54
+ * is saved until init() is called again and the read works.
55
+ * @returns {boolean}
56
+ */
57
+ get loadFailed() {
58
+ return this._readFailed;
45
59
  }
46
60
 
47
61
  /**
@@ -82,8 +96,9 @@ export class RewardSystem extends EventEmitter {
82
96
  * @returns {Promise<Object>} Player data
83
97
  */
84
98
  async init() {
85
- const saved = await this.dataService.load('player', null);
86
- this.player = this._migrate(saved);
99
+ const saved = await this._readSaved();
100
+ // A failed retry keeps the progress made since the first init.
101
+ if (!(this._loadFailed && this.player)) this.player = this._migrate(saved);
87
102
 
88
103
  // Check daily streak
89
104
  const streakChanged = this._updateDailyStreak();
@@ -98,6 +113,38 @@ export class RewardSystem extends EventEmitter {
98
113
  return this.player;
99
114
  }
100
115
 
116
+ /**
117
+ * Read the saved player. A failed read turns off saving for this
118
+ * session, so the new player built from the default never overwrites
119
+ * the real one. Calling init() again retries the read.
120
+ * @private
121
+ */
122
+ async _readSaved() {
123
+ // Stay blocked until the read succeeds, so a write made while a
124
+ // retry is in flight cannot land.
125
+ this._loadFailed = true;
126
+ try {
127
+ // A custom data service that ignores the option still works,
128
+ // without this protection.
129
+ const saved = await this.dataService.load('player', null, { strict: true });
130
+ this._loadFailed = false;
131
+ this._readFailed = false;
132
+ return saved;
133
+ } catch (error) {
134
+ if (error?.code === 'DOPAMINE_CORRUPT') {
135
+ // Keep the unreadable value instead of losing it on the next save.
136
+ const kept = await this.dataService.save('player_corrupt', error.raw);
137
+ if (kept) this._loadFailed = false;
138
+ this._readFailed = !kept;
139
+ this._publish('load_failed', { key: 'player', reason: 'corrupt', backedUp: kept });
140
+ return null;
141
+ }
142
+ this._readFailed = true;
143
+ this._publish('load_failed', { key: 'player', reason: 'read', error });
144
+ return null;
145
+ }
146
+ }
147
+
101
148
  /**
102
149
  * @private
103
150
  */
@@ -257,6 +304,7 @@ export class RewardSystem extends EventEmitter {
257
304
  * @private
258
305
  */
259
306
  async _write() {
307
+ if (this._loadFailed) return;
260
308
  this.player.lastPlayedAt = Date.now();
261
309
  const saved = await this.dataService.save('player', this.player);
262
310
 
@@ -3,6 +3,8 @@
3
3
  * Creates satisfying visual feedback for achievements and rewards
4
4
  */
5
5
 
6
+ import { prefersReducedMotion } from '../feel/motion.js';
7
+
6
8
  export class ParticleSystem {
7
9
  constructor(config = {}) {
8
10
  this.container = config.container ?
@@ -19,9 +21,7 @@ export class ParticleSystem {
19
21
  this.maxParticles = Number.isFinite(config.maxParticles) ? Math.max(0, Math.floor(config.maxParticles)) : 5000;
20
22
 
21
23
  // Effects are skipped for users who asked the OS for less motion.
22
- this._reducedMotion = config.respectReducedMotion !== false && typeof window.matchMedia === 'function'
23
- ? window.matchMedia('(prefers-reduced-motion: reduce)')
24
- : null;
24
+ this._reducedMotion = config.respectReducedMotion !== false ? prefersReducedMotion(window) : null;
25
25
 
26
26
  this.canvasId = config.canvasId || 'dopamine-particle-canvas';
27
27
 
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Short vibrations for hits and wins. A browser without the Vibration API
3
+ * (iOS Safari) or one that blocks it is silent, never an error.
4
+ */
5
+ export function createHaptics({ nav = globalThis.navigator, enabled = true } = {}) {
6
+ let on = Boolean(enabled);
7
+ const buzz = (pattern) => {
8
+ if (!on) return;
9
+ // A missing or non-function vibrate throws here too.
10
+ try {
11
+ nav.vibrate(pattern);
12
+ } catch {}
13
+ };
14
+ return {
15
+ tap: () => buzz(10),
16
+ double: () => buzz([10, 40, 10]),
17
+ setEnabled(value) {
18
+ on = Boolean(value);
19
+ },
20
+ };
21
+ }
@@ -0,0 +1,9 @@
1
+ const NO_PREFERENCE = Object.freeze({ matches: false });
2
+
3
+ /**
4
+ * The reduced-motion media query, or `{ matches: false }` where there is no
5
+ * matchMedia (SSR, tests). The live query updates when the user changes it.
6
+ */
7
+ export function prefersReducedMotion(win = globalThis.window) {
8
+ return (typeof win?.matchMedia === 'function' && win.matchMedia('(prefers-reduced-motion: reduce)')) || NO_PREFERENCE;
9
+ }
@@ -5,9 +5,165 @@
5
5
 
6
6
  const OVERLAY_ID = 'game-ui-overlay';
7
7
 
8
+ const DEFAULT_TEXT = {
9
+ levelUp: 'LEVEL UP!',
10
+ achievementUnlocked: 'Achievement Unlocked!',
11
+ nearMiss: 'CLOSE CALL!'
12
+ };
13
+
14
+ const DEFAULT_STREAK_ICON = '🔥';
15
+
16
+ // Config comes from callers, so an inherited property (a polluted prototype)
17
+ // must not count.
18
+ const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
19
+ const ownValue = (object, key) =>
20
+ (object !== null && typeof object === 'object' && hasOwn(object, key) ? object[key] : undefined);
21
+
22
+ const SVG_NS = 'http://www.w3.org/2000/svg';
23
+
24
+ const SVG_ELEMENTS = new Set([
25
+ 'svg', 'g', 'path', 'circle', 'ellipse', 'rect', 'line', 'polyline',
26
+ 'polygon', 'text', 'tspan', 'title', 'desc', 'defs', 'linearGradient',
27
+ 'radialGradient', 'stop', 'clipPath', 'mask'
28
+ ]);
29
+
30
+ // No style, no href, no event handlers: only geometry and paint.
31
+ const SVG_ATTRIBUTES = new Set([
32
+ 'viewBox', 'width', 'height', 'x', 'y', 'x1', 'y1', 'x2', 'y2', 'cx', 'cy',
33
+ 'r', 'rx', 'ry', 'd', 'points', 'transform', 'fill', 'fill-opacity',
34
+ 'fill-rule', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
35
+ 'stroke-opacity', 'opacity', 'offset', 'stop-color', 'stop-opacity',
36
+ 'gradientUnits', 'gradientTransform', 'clip-path', 'mask', 'clip-rule',
37
+ 'font-size', 'font-family', 'font-weight', 'text-anchor', 'id',
38
+ 'aria-hidden', 'aria-label', 'role'
39
+ ]);
40
+
41
+ // Attributes that may point at a gradient, clip path or mask in the same icon.
42
+ const REFERENCE_ATTRIBUTES = new Set(['fill', 'stroke', 'clip-path', 'mask']);
43
+ const TRANSFORM_ATTRIBUTES = new Set(['transform', 'gradientTransform']);
44
+
45
+ const SINGLE_FRAGMENT_URL = /^url\(\s*#([A-Za-z][\w.:-]*)\s*\)$/;
46
+ const PLAIN_COLOUR = /^[#a-zA-Z0-9(),.%\s-]+$/;
47
+ const PLAIN_TRANSFORM = /^[a-zA-Z0-9(),.\s-]+$/;
48
+ const SAFE_ID = /^[A-Za-z][\w.:-]*$/;
49
+
50
+ // Ids inside an icon are page-global (window.<id>, getElementById), so every
51
+ // render gets its own prefix.
52
+ let iconCounter = 0;
53
+
54
+ function collectIds(node, ids) {
55
+ if (node.nodeType !== 1 || node.namespaceURI !== SVG_NS || !SVG_ELEMENTS.has(node.localName)) {
56
+ return;
57
+ }
58
+ const id = node.getAttribute('id');
59
+ if (id && SAFE_ID.test(id)) ids.add(id);
60
+ for (const child of Array.from(node.childNodes)) collectIds(child, ids);
61
+ }
62
+
63
+ /**
64
+ * Returns the value to write, or null to drop the attribute.
65
+ */
66
+ function cleanValue(name, value, ctx) {
67
+ if (value.includes('\\')) return null;
68
+ const trimmed = value.trim();
69
+
70
+ if (name === 'id') {
71
+ return SAFE_ID.test(trimmed) ? ctx.prefix + trimmed : null;
72
+ }
73
+
74
+ if (REFERENCE_ATTRIBUTES.has(name)) {
75
+ const ref = SINGLE_FRAGMENT_URL.exec(trimmed);
76
+ if (ref) {
77
+ return ctx.ids.has(ref[1]) ? `url(#${ctx.prefix}${ref[1]})` : null;
78
+ }
79
+ return PLAIN_COLOUR.test(trimmed) && !/url/i.test(trimmed) ? trimmed : null;
80
+ }
81
+
82
+ if (TRANSFORM_ATTRIBUTES.has(name)) {
83
+ return PLAIN_TRANSFORM.test(trimmed) && !/url/i.test(trimmed) ? trimmed : null;
84
+ }
85
+
86
+ if (value.includes('(')) {
87
+ // Only a plain colour such as rgb() or hsl() is acceptable here.
88
+ return name === 'stop-color' && PLAIN_COLOUR.test(trimmed) && !/url/i.test(trimmed)
89
+ ? trimmed
90
+ : null;
91
+ }
92
+ return value;
93
+ }
94
+
95
+ function cleanNode(source, ctx) {
96
+ // 3 is text, 4 is CDATA.
97
+ if (source.nodeType === 3 || source.nodeType === 4) {
98
+ return document.createTextNode(source.data);
99
+ }
100
+ if (source.nodeType !== 1
101
+ || source.namespaceURI !== SVG_NS
102
+ || !SVG_ELEMENTS.has(source.localName)) {
103
+ return null;
104
+ }
105
+
106
+ const clean = document.createElementNS(SVG_NS, source.localName);
107
+ for (const attr of Array.from(source.attributes)) {
108
+ if (attr.namespaceURI !== null || !SVG_ATTRIBUTES.has(attr.name)) continue;
109
+ const value = cleanValue(attr.name, attr.value, ctx);
110
+ if (value !== null) clean.setAttribute(attr.name, value);
111
+ }
112
+ for (const child of Array.from(source.childNodes)) {
113
+ const kept = cleanNode(child, ctx);
114
+ if (kept) clean.appendChild(kept);
115
+ }
116
+ return clean;
117
+ }
118
+
119
+ /**
120
+ * Parse a string as SVG and rebuild it from an allowlist of elements and
121
+ * attributes, so nothing that can run script or load a resource survives.
122
+ * Returns null unless the whole string is one valid <svg> document.
123
+ */
124
+ function parseSafeSvg(markup) {
125
+ let doc;
126
+ // Inline HTML SVG usually has no xmlns, which the XML parser rejects.
127
+ const source = /^\s*<svg[\s>]/.test(markup) && !/^\s*<svg\b[^>]*\sxmlns\s*=/.test(markup)
128
+ ? markup.replace(/^(\s*<svg)/, `$1 xmlns="${SVG_NS}"`)
129
+ : markup;
130
+ try {
131
+ doc = new DOMParser().parseFromString(source,'image/svg+xml');
132
+ } catch {
133
+ return null;
134
+ }
135
+ const root = doc.documentElement;
136
+ if (!root || root.localName !== 'svg' || doc.getElementsByTagName('parsererror').length > 0) {
137
+ return null;
138
+ }
139
+ const ids = new Set();
140
+ collectIds(root, ids);
141
+ return cleanNode(root, { ids, prefix: `dj-icon-${++iconCounter}-` });
142
+ }
143
+
8
144
  export class GameUI {
9
- constructor(particleSystem) {
145
+ /**
146
+ * @param {Object} particleSystem
147
+ * @param {Object} [config]
148
+ * @param {{levelUp?: string, achievementUnlocked?: string, nearMiss?: string}} [config.text]
149
+ * Replaces the built-in popup strings.
150
+ * @param {{streak?: string|Node}} [config.icons]
151
+ * @param {boolean} [config.safeIcons] - Render string icons as sanitised
152
+ * SVG or plain text instead of HTML. Default false.
153
+ */
154
+ constructor(particleSystem, config = {}) {
10
155
  this.particleSystem = particleSystem;
156
+
157
+ // Only strings override a default, so a non-string cannot break a
158
+ // popup. An empty string is allowed and hides that text.
159
+ const textConfig = ownValue(config, 'text');
160
+ this.text = { ...DEFAULT_TEXT };
161
+ for (const key of Object.keys(DEFAULT_TEXT)) {
162
+ const value = ownValue(textConfig, key);
163
+ if (typeof value === 'string') this.text[key] = value;
164
+ }
165
+ this.safeIcons = ownValue(config, 'safeIcons') === true;
166
+ this._streakIcon = ownValue(ownValue(config, 'icons'), 'streak') ?? DEFAULT_STREAK_ICON;
11
167
  this.container = null;
12
168
  this.xpBar = null;
13
169
  this.levelDisplay = null;
@@ -50,7 +206,7 @@ export class GameUI {
50
206
  </div>
51
207
 
52
208
  <div class="streak-badge">
53
- <span class="streak-icon">🔥</span>
209
+ <span class="streak-icon"></span>
54
210
  <span class="streak-number">1</span>
55
211
  </div>
56
212
  </div>
@@ -82,6 +238,31 @@ export class GameUI {
82
238
  this.xpText = this.container.querySelector('.xp-text');
83
239
  this.levelDisplay = this.container.querySelector('.level-number');
84
240
  this.streakDisplay = this.container.querySelector('.streak-number');
241
+ this._setIcon(this.container.querySelector('.streak-icon'), this._streakIcon);
242
+ }
243
+
244
+ /**
245
+ * Single place where icons reach the DOM. A Node is appended. A string is
246
+ * HTML unless safeIcons is on (see SECURITY.md); then it is a sanitised
247
+ * SVG or plain text.
248
+ * @private
249
+ */
250
+ _setIcon(el, icon) {
251
+ el.textContent = '';
252
+ if (typeof Node !== 'undefined' && icon instanceof Node) {
253
+ el.appendChild(icon);
254
+ } else if (typeof icon !== 'string') {
255
+ return;
256
+ } else if (!this.safeIcons) {
257
+ el.innerHTML = icon;
258
+ } else {
259
+ const svg = parseSafeSvg(icon);
260
+ if (svg) {
261
+ el.appendChild(svg);
262
+ } else {
263
+ el.textContent = icon;
264
+ }
265
+ }
85
266
  }
86
267
 
87
268
  /**
@@ -173,8 +354,9 @@ export class GameUI {
173
354
  /**
174
355
  * Show achievement unlocked popup
175
356
  *
176
- * `icon` is rendered as HTML by design (documented in ARCHITECTURE.md, so
177
- * games can pass an <img> or inline SVG). Every other field is game state
357
+ * A string `icon` is rendered as HTML by design (documented in
358
+ * ARCHITECTURE.md, so games can pass an <img> or inline SVG). A Node is
359
+ * appended as is. Every other field is game state
178
360
  * and could carry a player-supplied or server-supplied string, so it goes
179
361
  * in as text.
180
362
  */
@@ -186,7 +368,7 @@ export class GameUI {
186
368
  <div class="achievement-content">
187
369
  <div class="achievement-icon"></div>
188
370
  <div class="achievement-info">
189
- <div class="achievement-title">Achievement Unlocked!</div>
371
+ <div class="achievement-title"></div>
190
372
  <div class="achievement-name"></div>
191
373
  <div class="achievement-desc"></div>
192
374
  <div class="achievement-xp"></div>
@@ -194,7 +376,8 @@ export class GameUI {
194
376
  </div>
195
377
  `;
196
378
 
197
- popup.querySelector('.achievement-icon').innerHTML = achievement.icon ?? '';
379
+ popup.querySelector('.achievement-title').textContent = this.text.achievementUnlocked;
380
+ this._setIcon(popup.querySelector('.achievement-icon'), achievement.icon);
198
381
  popup.querySelector('.achievement-name').textContent = achievement.name ?? '';
199
382
  popup.querySelector('.achievement-desc').textContent = achievement.description ?? '';
200
383
  popup.querySelector('.achievement-xp').textContent = `+${achievement.xp ?? 0} XP`;
@@ -223,11 +406,12 @@ export class GameUI {
223
406
  overlay.className = 'level-up-overlay';
224
407
  overlay.innerHTML = `
225
408
  <div class="level-up-content">
226
- <div class="level-up-title">LEVEL UP!</div>
409
+ <div class="level-up-title"></div>
227
410
  <div class="level-up-number"></div>
228
411
  <div class="level-up-subtitle">Amazing progress!</div>
229
412
  </div>
230
413
  `;
414
+ overlay.querySelector('.level-up-title').textContent = this.text.levelUp;
231
415
  overlay.querySelector('.level-up-number').textContent = newLevel;
232
416
 
233
417
  this._mount(overlay);
@@ -280,7 +464,7 @@ export class GameUI {
280
464
  * Show "near miss" indicator
281
465
  */
282
466
  showNearMiss(x, y) {
283
- this.showFloatingText('CLOSE CALL!', x, y, '#45b7d1', '20px');
467
+ this.showFloatingText(this.text.nearMiss, x, y, '#45b7d1', '20px');
284
468
  this.particleSystem.sparkle(x, y, 15, '#45b7d1');
285
469
  }
286
470
 
@@ -416,5 +600,6 @@ export class GameUI {
416
600
  this.streakBadge = null;
417
601
  this.levelDisplay = null;
418
602
  this.streakDisplay = null;
603
+ this._streakIcon = null;
419
604
  }
420
605
  }
package/src/index.js CHANGED
@@ -18,6 +18,10 @@ export { EventEmitter } from './dopamine/core/EventEmitter.js';
18
18
  // Storage resolution, useful for tests and for SSR where localStorage is absent.
19
19
  export { createMemoryStorage, resolveStorage } from './dopamine/utils/storage.js';
20
20
 
21
+ // Feel helpers: vibration and the reduced-motion preference
22
+ export { createHaptics } from './dopamine/feel/haptics.js';
23
+ export { prefersReducedMotion } from './dopamine/feel/motion.js';
24
+
21
25
  // Export New Engine Core
22
26
  export { Game } from './core/Game.js';
23
27
  export { Scene } from './core/Scene.js';
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Core subpath export: `import { RewardSystem } from 'dopaminejs/core'`
3
+ *
4
+ * The progression API with no UI, effects, sound or engine behind it, so it
5
+ * loads in React Native, Expo and other runtimes that have no browser. Nothing
6
+ * reachable from here may touch window, document, localStorage or navigator
7
+ * at import time. scripts/check-core-import.js enforces that against the build.
8
+ */
9
+
10
+ export { RewardSystem } from './dopamine/core/RewardSystem.js';
11
+ export { DataService } from './dopamine/core/DataService.js';
12
+ export { EventEmitter } from './dopamine/core/EventEmitter.js';
13
+ export { createMemoryStorage, resolveStorage } from './dopamine/utils/storage.js';
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Types for the `dopaminejs/core` subpath. Only what that entry exports at
3
+ * runtime, plus the types those values use, so importing GameUI or another
4
+ * web-only name from it fails to compile instead of being undefined.
5
+ */
6
+ export {
7
+ RewardSystem,
8
+ DataService,
9
+ EventEmitter,
10
+ createMemoryStorage,
11
+ resolveStorage
12
+ } from './index';
13
+
14
+ export type {
15
+ Player,
16
+ PlayerStreak,
17
+ UnlockedAchievement,
18
+ AchievementDefinition,
19
+ GameResult,
20
+ XPProgress,
21
+ AddXPResult,
22
+ RewardSystemConfig,
23
+ RewardEvent,
24
+ StorageLike,
25
+ AsyncStorageLike,
26
+ DataServiceConfig
27
+ } from './index';
package/types/index.d.ts CHANGED
@@ -38,8 +38,12 @@ export interface Player {
38
38
  export interface AchievementDefinition {
39
39
  name: string;
40
40
  description?: string;
41
- /** Rendered as HTML, so an <img> or inline SVG is allowed here. */
42
- icon?: string;
41
+ /**
42
+ * A string is rendered as HTML (an <img> or inline SVG is allowed), or as
43
+ * allowlisted SVG or text when GameUI is built with `safeIcons: true`. A
44
+ * Node is moved into the popup, not copied.
45
+ */
46
+ icon?: string | Node;
43
47
  /** Omitted means 0. Never undefined at runtime. */
44
48
  xp?: number;
45
49
  check(player: Player, gameName?: string, result?: GameResult): boolean;
@@ -81,7 +85,17 @@ export type RewardEvent =
81
85
  /** Payload `{ current, longest }`. Fires when the day rolls over. */
82
86
  | 'streak_updated'
83
87
  /** Payload `{ key }`. The storage write failed; state lives in memory only. */
84
- | 'save_failed';
88
+ | 'save_failed'
89
+ /**
90
+ * Payload `{ key, reason, error?, backedUp? }`. `reason: 'read'`: storage
91
+ * could not be read, so nothing is saved this session (call `init()` again
92
+ * to retry). `reason: 'corrupt'`: the saved value was not JSON; it is kept
93
+ * under `player_corrupt` as a JSON string and a new player starts. If that
94
+ * backup fails, `backedUp` is false and nothing is saved this session.
95
+ * A `load()` override must pass its third argument on, or a failed read
96
+ * looks like an empty one.
97
+ */
98
+ | 'load_failed';
85
99
 
86
100
  export class EventEmitter {
87
101
  on(event: string, callback: (data?: unknown) => void): () => void;
@@ -97,6 +111,11 @@ export class RewardSystem extends EventEmitter {
97
111
  achievements: Record<string, AchievementDefinition>;
98
112
  /** Kernel bus events are mirrored onto, if one was supplied. */
99
113
  events: EventBus | null;
114
+ /**
115
+ * True when the last `init()` could not read the saved player, so nothing
116
+ * is saved until `init()` is called again and the read works.
117
+ */
118
+ readonly loadFailed: boolean;
100
119
 
101
120
  init(): Promise<Player>;
102
121
  save(): Promise<void>;
@@ -153,7 +172,13 @@ export class DataService {
153
172
  storage: StorageLike | AsyncStorageLike;
154
173
  prefix: string;
155
174
  save(key: string, data: unknown): Promise<boolean>;
156
- load<T = unknown>(key: string, defaultValue?: T | null): Promise<T | null>;
175
+ /**
176
+ * Resolves `defaultValue` when the read fails, unless `strict` is set:
177
+ * then a storage error rejects as is, and unparseable data rejects with
178
+ * `code: 'DOPAMINE_CORRUPT'` and the raw string on `raw`. `RewardSystem`
179
+ * relies on this, so an override must pass `options` on.
180
+ */
181
+ load<T = unknown>(key: string, defaultValue?: T | null, options?: { strict?: boolean }): Promise<T | null>;
157
182
  clear(key: string): Promise<void>;
158
183
  }
159
184
 
@@ -162,6 +187,20 @@ export function createMemoryStorage(): StorageLike;
162
187
  /** localStorage if present and writable, otherwise an in-memory store. */
163
188
  export function resolveStorage(): StorageLike;
164
189
 
190
+ export interface Haptics {
191
+ /** A 10 ms buzz. */
192
+ tap(): void;
193
+ /** Buzzes 10, 40, 10 ms. */
194
+ double(): void;
195
+ setEnabled(enabled: boolean): void;
196
+ }
197
+
198
+ /** Silent where the Vibration API is missing or blocked. */
199
+ export function createHaptics(options?: { nav?: { vibrate?: (pattern: number | number[]) => unknown }; enabled?: boolean }): Haptics;
200
+
201
+ /** The reduced-motion query, or `{ matches: false }` without matchMedia. */
202
+ export function prefersReducedMotion(win?: { matchMedia?: (query: string) => { matches: boolean } }): { matches: boolean };
203
+
165
204
  // ---------------------------------------------------------------------------
166
205
  // UI
167
206
  // ---------------------------------------------------------------------------
@@ -176,8 +215,35 @@ export interface SummaryData {
176
215
  onExit?: () => void;
177
216
  }
178
217
 
218
+ export interface GameUIConfig {
219
+ /**
220
+ * When true, a string icon (achievement or streak) is parsed as SVG and
221
+ * rebuilt from an allowlist of elements and attributes, and any other
222
+ * string is shown as text. The string must be well-formed XML, so
223
+ * `&nbsp;` falls back to text. An `<svg>` with no xmlns is accepted.
224
+ * Default false: string icons are HTML.
225
+ */
226
+ safeIcons?: boolean;
227
+ /** Replaces the built-in popup strings. Rendered as text. */
228
+ text?: {
229
+ /** Default `LEVEL UP!`. */
230
+ levelUp?: string;
231
+ /** Default `Achievement Unlocked!`. */
232
+ achievementUnlocked?: string;
233
+ /** Default `CLOSE CALL!`. */
234
+ nearMiss?: string;
235
+ };
236
+ icons?: {
237
+ /**
238
+ * A string is HTML (unless `safeIcons` is on), a Node is moved into
239
+ * the badge, not copied. Default is a fire emoji.
240
+ */
241
+ streak?: string | Node;
242
+ };
243
+ }
244
+
179
245
  export class GameUI {
180
- constructor(particleSystem: ParticleSystem);
246
+ constructor(particleSystem: ParticleSystem, config?: GameUIConfig);
181
247
 
182
248
  container: HTMLElement | null;
183
249
 
@@ -279,6 +345,8 @@ export class SoundManager {
279
345
 
280
346
  /** Returns false when no Web Audio API is available, rather than throwing. */
281
347
  initAudio(): boolean;
348
+ /** Calls initAudio() on the first of `events` on `target`, then removes its listeners. Returns a remover. */
349
+ unlockOn(target: EventTarget, events?: string[]): () => void;
282
350
  setVolume(value: number): number;
283
351
  getVolume(): number;
284
352
  toggleMute(): boolean;