dopaminejs 2.5.0 → 3.0.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.
Files changed (81) hide show
  1. package/README.md +40 -50
  2. package/dist/DataService-E4pGQ1V3.cjs +1 -0
  3. package/dist/DataService-MfmvkqXR.js +737 -0
  4. package/dist/core.cjs +1 -1
  5. package/dist/core.js +2 -2
  6. package/dist/dopamine.cjs +1 -37
  7. package/dist/dopamine.js +3 -635
  8. package/dist/games.cjs +1 -0
  9. package/dist/games.js +82 -0
  10. package/dist/host-CkRL74ck.js +814 -0
  11. package/dist/host-Pzb-QBPU.cjs +37 -0
  12. package/dist/style.css +395 -2
  13. package/dist/testing.cjs +1 -0
  14. package/dist/testing.js +474 -0
  15. package/package.json +24 -9
  16. package/spec/README.md +227 -0
  17. package/spec/VERSION +1 -0
  18. package/spec/fixtures/achievements.json +611 -0
  19. package/spec/fixtures/levels.json +421 -0
  20. package/spec/fixtures/merge.json +1739 -0
  21. package/spec/fixtures/migrate.json +916 -0
  22. package/spec/fixtures/scores.json +755 -0
  23. package/spec/fixtures/streaks.json +924 -0
  24. package/spec/schema.json +61 -0
  25. package/src/dopamine/audio/SoundManager.js +54 -24
  26. package/src/dopamine/core/DopamineError.js +7 -0
  27. package/src/dopamine/core/RewardSystem.js +323 -373
  28. package/src/dopamine/core/achievements.js +49 -0
  29. package/src/dopamine/core/clock.js +11 -0
  30. package/src/dopamine/core/levels.js +4 -0
  31. package/src/dopamine/core/merge.js +68 -0
  32. package/src/dopamine/core/middleware.js +58 -0
  33. package/src/dopamine/core/store.js +261 -0
  34. package/src/dopamine/core/streaks.js +55 -0
  35. package/src/dopamine/effects/ParticleSystem.js +30 -0
  36. package/src/dopamine/host.js +358 -0
  37. package/src/dopamine/ui/{GameUI.js → RewardUI.js} +166 -202
  38. package/src/games.js +138 -0
  39. package/src/index.js +11 -34
  40. package/src/progression.js +3 -0
  41. package/src/testing.js +489 -0
  42. package/types/core.d.ts +9 -1
  43. package/types/games.d.ts +46 -0
  44. package/types/index.d.ts +291 -384
  45. package/types/testing.d.ts +96 -0
  46. package/dist/DataService-BPXCldpo.cjs +0 -1
  47. package/dist/DataService-CH9_gv_8.js +0 -398
  48. package/dist/ScreenShake-9jgNXPS6.cjs +0 -1
  49. package/dist/ScreenShake-CLvO1wx4.js +0 -827
  50. package/dist/engine.cjs +0 -1
  51. package/dist/engine.js +0 -2
  52. package/src/core/Animator.js +0 -62
  53. package/src/core/Collider.js +0 -86
  54. package/src/core/Component.js +0 -38
  55. package/src/core/DopamineKernel.js +0 -170
  56. package/src/core/EventBus.js +0 -206
  57. package/src/core/Game.js +0 -90
  58. package/src/core/GameObject.js +0 -99
  59. package/src/core/PluginRegistry.js +0 -359
  60. package/src/core/Scene.js +0 -107
  61. package/src/core/Sprite.js +0 -51
  62. package/src/core/SystemRegistry.js +0 -263
  63. package/src/core/Vector2.js +0 -50
  64. package/src/dopamine/components/ParticleEmitter.js +0 -50
  65. package/src/dopamine/components/ScreenShake.js +0 -50
  66. package/src/dopamine/components/index.js +0 -2
  67. package/src/dopamine/index.js +0 -93
  68. package/src/dopamine/utils/TextureGenerator.js +0 -90
  69. package/src/engine.js +0 -38
  70. package/src/interfaces/IAudioSystem.js +0 -58
  71. package/src/interfaces/IParticleSystem.js +0 -51
  72. package/src/interfaces/IPhysicsSystem.js +0 -52
  73. package/src/interfaces/ISystem.js +0 -48
  74. package/src/interfaces/index.js +0 -7
  75. package/src/renderer/Renderer.js +0 -45
  76. package/src/systems/Director.js +0 -34
  77. package/src/systems/Input.js +0 -81
  78. package/src/systems/Loader.js +0 -48
  79. package/src/systems/Physics.js +0 -210
  80. package/src/systems/Ticker.js +0 -91
  81. package/src/systems/deprecate.js +0 -38
@@ -1,45 +1,63 @@
1
1
  /**
2
2
  * Reward System Module
3
3
  * Manages achievements, XP, levels, streaks, and rewards
4
+ *
5
+ * The saved player is a document that merges (see merge.js). Nothing hands
6
+ * the document out: callers get frozen snapshots.
4
7
  */
5
8
 
6
9
  import { EventEmitter } from './EventEmitter.js';
7
-
8
- // Keys that resolve to something on Object.prototype. Game names and
9
- // achievement ids index plain objects, so these must never be used as one.
10
- const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
11
-
12
- const isSafeKey = (key) => typeof key === 'string' && key.length > 0 && !UNSAFE_KEYS.has(key);
13
- const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
14
- const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
15
-
16
- const toCount = (value, fallback, min = 0) => {
17
- const number = Number(value);
18
- return Number.isInteger(number) && number >= min ? number : fallback;
10
+ import { DopamineError } from './DopamineError.js';
11
+ import { systemClock } from './clock.js';
12
+ import { levelFor, thresholdFor } from './levels.js';
13
+ import { builtinAchievements, rewardsOf } from './achievements.js';
14
+ import { Middleware } from './middleware.js';
15
+ import { merge } from './merge.js';
16
+ import { currentStreak, longestRun, trimDays } from './streaks.js';
17
+ import {
18
+ LEGACY, MAX_DEVICES, cap, deviceIds, emptyDoc, validate, view, xpOf, levelOf, clone, freeze, isSafeKey, hasOwn, isRecord
19
+ } from './store.js';
20
+
21
+ const DEVICE_KEY = 'device';
22
+
23
+ const randomId = () => {
24
+ const bytes = new Uint8Array(8);
25
+ const random = globalThis.crypto;
26
+ if (typeof random?.getRandomValues === 'function') {
27
+ random.getRandomValues(bytes);
28
+ } else {
29
+ for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
30
+ }
31
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
19
32
  };
20
33
 
34
+ const isDeviceId = (id) => isSafeKey(id) && id !== LEGACY;
35
+
21
36
  export class RewardSystem extends EventEmitter {
22
37
  /**
23
38
  * @param {Object} dataService - Persistence, see DataService
24
39
  * @param {Object} [config]
25
40
  * @param {Object} [config.achievements] - Extra achievement definitions
26
- * @param {Object} [config.events] - Kernel EventBus to mirror events onto
27
- * @param {Object} [config.kernel] - Kernel; its `events` bus is used if present
41
+ * @param {{ now(): number, localDate(ms?: number): string }} [config.clock] - Time source
42
+ * @param {'any'|'record'} [config.streakDays] - What marks today as a play day.
43
+ * 'any' (default): record() or addXP(). 'record': record() only. XP from an
44
+ * achievement reward never marks a day.
28
45
  */
29
46
  constructor(dataService, config = {}) {
30
47
  super();
31
48
  this.dataService = dataService;
32
- this.player = null;
33
- this.achievements = { ...this._initAchievements(), ...(config.achievements || {}) };
34
-
35
- // Optional bridge to the kernel bus. EventBus.Events already declared
36
- // XP_GAINED, LEVEL_UP and ACHIEVEMENT_UNLOCKED with nothing emitting
37
- // them; this connects the two event systems without changing the
38
- // existing rewardSystem.on(...) surface that games already use.
39
- this.events = config.events || config.kernel?.events || null;
40
-
41
- // Write batching. Every mutation used to hit storage directly, so one
42
- // recordGame produced four full serializations of the player object.
49
+ this.clock = config.clock && typeof config.clock.now === 'function' && typeof config.clock.localDate === 'function'
50
+ ? config.clock
51
+ : systemClock;
52
+ this.achievements = { ...builtinAchievements(), ...(config.achievements || {}) };
53
+ this.streakDays = config.streakDays === 'record' ? 'record' : 'any';
54
+
55
+ this._doc = null;
56
+ this._deviceId = null;
57
+ this._deviceSaved = false;
58
+ this._middleware = new Middleware();
59
+
60
+ // Write batching: one record is one write.
43
61
  this._batchDepth = 0;
44
62
  this._pendingSave = false;
45
63
 
@@ -59,25 +77,14 @@ export class RewardSystem extends EventEmitter {
59
77
  }
60
78
 
61
79
  /**
62
- * Emit locally, and mirror onto the kernel bus when one is attached.
80
+ * Emit a frozen copy of the payload.
63
81
  * @private
64
82
  */
65
83
  _publish(event, data) {
66
- this.emit(event, data);
67
- if (this.events) {
68
- this.events.emit(event, data);
69
- }
84
+ const payload = Object.freeze({ ...data });
85
+ this.emit(event, payload);
70
86
  }
71
87
 
72
- /**
73
- * Run `fn` with saves collapsed into a single write at the end.
74
- *
75
- * Nested batches are counted, so an inner operation that batches on its
76
- * own still results in exactly one write for the outermost call.
77
- *
78
- * @param {Function} fn
79
- * @private
80
- */
81
88
  async _batch(fn) {
82
89
  this._batchDepth++;
83
90
  try {
@@ -91,26 +98,21 @@ export class RewardSystem extends EventEmitter {
91
98
  }
92
99
  }
93
100
 
101
+ _options() {
102
+ return { now: this.clock.now(), today: this.clock.localDate(), rewards: rewardsOf(this.achievements) };
103
+ }
104
+
94
105
  /**
95
106
  * Initialize the reward system for current player
96
- * @returns {Promise<Object>} Player data
107
+ * @returns {Promise<Object>} Frozen snapshot of the player
97
108
  */
98
109
  async init() {
99
110
  const saved = await this._readSaved();
100
111
  // A failed retry keeps the progress made since the first init.
101
- if (!(this._loadFailed && this.player)) this.player = this._migrate(saved);
102
-
103
- // Check daily streak
104
- const streakChanged = this._updateDailyStreak();
105
-
106
- // Save updated player data
112
+ if (!(this._loadFailed && this._doc)) this._doc = this._load(saved);
113
+ await this._readDevice();
107
114
  await this.save();
108
-
109
- if (streakChanged) {
110
- this._publishStreak();
111
- }
112
-
113
- return this.player;
115
+ return this.snapshot();
114
116
  }
115
117
 
116
118
  /**
@@ -124,8 +126,6 @@ export class RewardSystem extends EventEmitter {
124
126
  // retry is in flight cannot land.
125
127
  this._loadFailed = true;
126
128
  try {
127
- // A custom data service that ignores the option still works,
128
- // without this protection.
129
129
  const saved = await this.dataService.load('player', null, { strict: true });
130
130
  this._loadFailed = false;
131
131
  this._readFailed = false;
@@ -146,149 +146,153 @@ export class RewardSystem extends EventEmitter {
146
146
  }
147
147
 
148
148
  /**
149
+ * Saved state is untrusted: it goes through validate. A document from a
150
+ * newer version or with too many devices is left alone in storage.
151
+ * @private
152
+ */
153
+ _load(saved) {
154
+ if (!isRecord(saved)) return emptyDoc(this.clock.now());
155
+ try {
156
+ return validate(saved, this._options());
157
+ } catch (error) {
158
+ if (!(error instanceof DopamineError)) throw error;
159
+ this._loadFailed = true;
160
+ this._readFailed = true;
161
+ this._publish('load_failed', { key: 'player', reason: error.code, error });
162
+ return emptyDoc(this.clock.now());
163
+ }
164
+ }
165
+
166
+ /**
167
+ * The device id is made once, kept under its own key and never part of
168
+ * the merged document.
169
+ * @private
170
+ */
171
+ async _readDevice() {
172
+ if (this._deviceId) return;
173
+ let stored = null;
174
+ try {
175
+ stored = await this.dataService.load(DEVICE_KEY, null, { strict: true });
176
+ } catch {
177
+ // Unreadable: use a fresh id, saved with the first write that works.
178
+ this._deviceId = randomId();
179
+ return;
180
+ }
181
+ if (isDeviceId(stored)) {
182
+ this._deviceId = stored;
183
+ this._deviceSaved = true;
184
+ } else {
185
+ this._deviceId = randomId();
186
+ }
187
+ }
188
+
189
+ /**
190
+ * A write that would add a device past the cap is refused, so the stored
191
+ * save never becomes one that validate rejects.
149
192
  * @private
150
193
  */
194
+ _hasSlot() {
195
+ const ids = deviceIds(this._doc);
196
+ if (ids.has(this._deviceId) || ids.size < MAX_DEVICES) return true;
197
+ this._publish('load_failed', { key: 'player', reason: 'too_many_devices' });
198
+ return false;
199
+ }
200
+
151
201
  _requirePlayer() {
152
- if (!this.player) {
202
+ if (!this._doc) {
153
203
  throw new Error('[DopamineJS] RewardSystem.init() must be awaited before use');
154
204
  }
155
205
  }
156
206
 
157
207
  /**
158
- * @private
208
+ * A frozen copy of the player with the derived values: xp, level,
209
+ * totalGamesPlayed, streak and per-activity stats.
159
210
  */
160
- _publishStreak() {
161
- const { current, longest } = this.player.streak;
162
- this._publish('streak_updated', { current, longest });
211
+ snapshot() {
212
+ this._requirePlayer();
213
+ return freeze(view(this._doc, this.clock.localDate()));
163
214
  }
164
215
 
165
216
  /**
166
- * Get default player data structure
217
+ * The versioned document, a detached copy.
167
218
  */
168
- _getDefaultPlayer() {
169
- return {
170
- name: 'Player',
171
- xp: 0,
172
- level: 1,
173
- totalGamesPlayed: 0,
174
- createdAt: Date.now(),
175
- lastPlayedAt: Date.now(),
176
- streak: {
177
- current: 1,
178
- longest: 1,
179
- lastPlayDate: this._getTodayDateString()
180
- },
181
- achievements: {}, // achievement_id: { unlockedAt: timestamp, seen: boolean }
182
- stats: {
183
- // Dynamic stats object, games will add their own keys
184
- }
185
- };
219
+ export() {
220
+ this._requirePlayer();
221
+ return clone(this._doc);
186
222
  }
187
223
 
188
224
  /**
189
- * Merge a persisted player record onto the current default shape.
225
+ * Merge a document from elsewhere into this player. It is validated the
226
+ * same way a load is. Unless `silent`, the XP, level and achievements
227
+ * that went up are announced.
190
228
  *
191
- * Saves written by older versions are missing whatever fields were added
192
- * since. Without this the first property access on a new field throws
193
- * before the game has drawn a frame.
194
- *
195
- * @param {Object|null} saved - Previously persisted player, if any
196
- * @returns {Object} Player object guaranteed to have every field
197
- * @private
229
+ * @param {Object} doc
230
+ * @param {{ silent?: boolean }} [options]
198
231
  */
199
- _migrate(saved) {
200
- const defaults = this._getDefaultPlayer();
232
+ async import(doc, { silent = false } = {}) {
233
+ this._requirePlayer();
234
+ const before = this.snapshot();
235
+ const incoming = validate(doc, this._options());
236
+ const merged = merge(this._doc, incoming, this._options());
237
+ merged.level = levelOf(merged);
238
+ this._doc = merged;
201
239
 
202
- if (!isRecord(saved)) {
203
- return defaults;
240
+ const after = this.snapshot();
241
+ await this.save();
242
+ if (silent) return after;
243
+
244
+ const gained = after.xp - before.xp;
245
+ const leveledUp = after.level > before.level;
246
+ if (gained > 0) {
247
+ this._publish('xp_gained', {
248
+ amount: gained, reason: 'import', leveledUp, newLevel: after.level, total: after.xp
249
+ });
204
250
  }
205
-
206
- // Storage is writable by the player and by anything else on the
207
- // origin, so every field is checked. A string xp would concatenate on
208
- // the next addXP, and a non-object stats would throw on first use.
209
- const xpValue = Number(saved.xp);
210
- const xp = Number.isFinite(xpValue) && xpValue >= 0 ? xpValue : 0;
211
- const earned = this._calculateLevel(xp);
212
-
213
- const savedStreak = isRecord(saved.streak) ? saved.streak : {};
214
- const current = toCount(savedStreak.current, 1, 1);
215
- const lastPlayDate = typeof savedStreak.lastPlayDate === 'string'
216
- && /^\d{4}-\d{2}-\d{2}$/.test(savedStreak.lastPlayDate)
217
- ? savedStreak.lastPlayDate
218
- : defaults.streak.lastPlayDate;
219
-
220
- return {
221
- ...defaults,
222
- ...saved,
223
- name: typeof saved.name === 'string' ? saved.name : defaults.name,
224
- xp,
225
- // A level above the curve is kept: older versions banked levels
226
- // at half the XP and those players keep what they earned.
227
- level: Math.max(earned, toCount(saved.level, earned, 1)),
228
- totalGamesPlayed: toCount(saved.totalGamesPlayed, 0),
229
- createdAt: Number.isFinite(saved.createdAt) ? saved.createdAt : defaults.createdAt,
230
- lastPlayedAt: Number.isFinite(saved.lastPlayedAt) ? saved.lastPlayedAt : defaults.lastPlayedAt,
231
- streak: {
232
- current,
233
- longest: Math.max(current, toCount(savedStreak.longest, current, 1)),
234
- lastPlayDate
235
- },
236
- achievements: this._migrateAchievements(saved.achievements),
237
- stats: this._migrateStats(saved.stats)
238
- };
251
+ if (leveledUp) {
252
+ this._publish('level_up', { oldLevel: before.level, newLevel: after.level, totalXP: after.xp });
253
+ }
254
+ for (const id of Object.keys(after.achievements)) {
255
+ if (!hasOwn(before.achievements, id)) {
256
+ this._publish('achievement_unlocked', { ...this.achievements[id], id });
257
+ }
258
+ }
259
+ return after;
239
260
  }
240
261
 
241
262
  /**
242
- * @private
263
+ * Add a middleware object with any of beforeXP, afterXP, beforeRecord,
264
+ * afterRecord, beforeUnlock and afterUnlock. Hooks run in `use` order.
265
+ * @returns {Function} Removes it again
243
266
  */
244
- _migrateAchievements(saved) {
245
- const achievements = {};
246
- if (!isRecord(saved)) return achievements;
247
-
248
- for (const id of Object.keys(saved)) {
249
- const entry = saved[id];
250
- if (!isSafeKey(id) || !isRecord(entry)) continue;
251
-
252
- achievements[id] = {
253
- unlockedAt: Number.isFinite(entry.unlockedAt) ? entry.unlockedAt : Date.now(),
254
- seen: entry.seen === true
255
- };
256
- }
257
-
258
- return achievements;
267
+ use(middleware) {
268
+ return this._middleware.use(middleware);
259
269
  }
260
270
 
261
271
  /**
262
- * @private
272
+ * Add an achievement rule at runtime.
273
+ * @returns {Function} Removes it again
263
274
  */
264
- _migrateStats(saved) {
265
- const stats = {};
266
- if (!isRecord(saved)) return stats;
267
-
268
- for (const gameName of Object.keys(saved)) {
269
- const entry = saved[gameName];
270
- if (!isSafeKey(gameName) || !isRecord(entry)) continue;
271
-
272
- const game = {};
273
- for (const key of Object.keys(entry)) {
274
- if (isSafeKey(key) && Number.isFinite(entry[key])) {
275
- game[key] = entry[key];
276
- }
277
- }
278
- game.totalPlays = toCount(entry.totalPlays, 0);
279
- game.highScore = Number.isFinite(entry.highScore) ? entry.highScore : 0;
280
-
281
- stats[gameName] = game;
275
+ defineAchievement(id, definition) {
276
+ if (!isSafeKey(id)) {
277
+ throw new TypeError(`[DopamineJS] defineAchievement expects an id, received ${String(id)}`);
282
278
  }
283
-
284
- return stats;
279
+ if (!isRecord(definition) || typeof definition.check !== 'function') {
280
+ throw new TypeError('[DopamineJS] defineAchievement expects a definition with a check function');
281
+ }
282
+ const previous = hasOwn(this.achievements, id) ? this.achievements[id] : undefined;
283
+ this.achievements[id] = definition;
284
+ return () => {
285
+ if (this.achievements[id] !== definition) return;
286
+ if (previous) this.achievements[id] = previous;
287
+ else delete this.achievements[id];
288
+ };
285
289
  }
286
290
 
287
291
  /**
288
292
  * Save player data
289
293
  */
290
294
  async save() {
291
- if (!this.player) return;
295
+ if (!this._doc) return;
292
296
 
293
297
  // Inside a batch, mark dirty and let the outermost call do the write.
294
298
  if (this._batchDepth > 0) {
@@ -305,8 +309,11 @@ export class RewardSystem extends EventEmitter {
305
309
  */
306
310
  async _write() {
307
311
  if (this._loadFailed) return;
308
- this.player.lastPlayedAt = Date.now();
309
- const saved = await this.dataService.save('player', this.player);
312
+ this._doc.lastPlayedAt = this.clock.now();
313
+ if (!this._deviceSaved) {
314
+ this._deviceSaved = (await this.dataService.save(DEVICE_KEY, this._deviceId)) !== false;
315
+ }
316
+ const saved = await this.dataService.save('player', this._doc);
310
317
 
311
318
  // DataService logs and returns false rather than throwing, so a full
312
319
  // or blocked storage would otherwise lose progress without a sign.
@@ -316,42 +323,69 @@ export class RewardSystem extends EventEmitter {
316
323
  }
317
324
 
318
325
  /**
319
- * Add XP and handle level ups
326
+ * Add XP and handle level ups. A negative amount is kept as XP spent on
327
+ * this device and stops at zero.
320
328
  * @param {number} amount - XP to add
321
329
  * @param {string} reason - Why XP was awarded (for notifications)
322
330
  * @returns {Object} { leveledUp: boolean, newLevel: number, xpGained: number }
323
331
  */
324
332
  async addXP(amount, reason = '') {
325
333
  if (!Number.isFinite(amount)) {
326
- // Adding undefined/NaN here would poison player.xp permanently:
334
+ // Adding undefined/NaN here would poison the total permanently:
327
335
  // NaN survives every subsequent arithmetic op and gets persisted.
328
336
  throw new TypeError(`[DopamineJS] addXP expects a finite number, received ${amount}`);
329
337
  }
330
338
 
331
339
  this._requirePlayer();
340
+ if (!this._hasSlot()) return { leveledUp: false, newLevel: levelOf(this._doc), xpGained: 0 };
332
341
 
333
- const oldLevel = this.player.level;
342
+ const context = await this._middleware.before('beforeXP', { amount, reason }, (next) => Number.isFinite(next.amount));
343
+ if (context === false) {
344
+ return { leveledUp: false, newLevel: levelOf(this._doc), xpGained: 0 };
345
+ }
334
346
 
335
- // XP stops at zero, so a large negative amount removes less than
336
- // asked. Report what changed.
337
- amount = Math.max(amount, -this.player.xp);
338
- this.player.xp += amount;
347
+ if (this.streakDays === 'any' && context.amount > 0) this._markDay();
339
348
 
340
- // Check for level up. Levels are never taken back, so a negative
341
- // amount or a level banked under an older curve reports the stored one.
342
- const newLevel = Math.max(oldLevel, this._calculateLevel(this.player.xp));
343
- const leveledUp = newLevel > oldLevel;
349
+ const result = await this._applyXP(context.amount, context.reason, (doc, applied) => {
350
+ if (applied >= 0) {
351
+ doc.xpBy[this._deviceId] = cap((hasOwn(doc.xpBy, this._deviceId) ? doc.xpBy[this._deviceId] : 0) + applied);
352
+ } else {
353
+ doc.xpSpentBy[this._deviceId] = cap((hasOwn(doc.xpSpentBy, this._deviceId) ? doc.xpSpentBy[this._deviceId] : 0) - applied);
354
+ }
355
+ });
344
356
 
345
- if (leveledUp) {
346
- this.player.level = newLevel;
347
- }
357
+ await this._middleware.after('afterXP', {
358
+ amount: result.xpGained, reason: context.reason, total: xpOf(this._doc), level: result.newLevel
359
+ });
360
+ return result;
361
+ }
362
+
363
+ /**
364
+ * Change the total, then announce it. Levels are never taken back, so a
365
+ * negative amount or a level banked under an older curve reports the
366
+ * stored one.
367
+ * @private
368
+ */
369
+ async _applyXP(amount, reason, change) {
370
+ const doc = this._doc;
371
+ const oldLevel = levelOf(doc);
372
+
373
+ // XP stops at zero, so a large negative amount removes less than asked.
374
+ amount = Math.max(amount, -xpOf(doc));
375
+ change(doc, amount);
376
+ return this._announceXP(oldLevel, amount, reason);
377
+ }
378
+
379
+ async _announceXP(oldLevel, amount, reason) {
380
+ const doc = this._doc;
381
+ const total = xpOf(doc);
382
+ const newLevel = Math.max(oldLevel, levelFor(total));
383
+ const leveledUp = newLevel > oldLevel;
384
+ if (newLevel > doc.level) doc.level = newLevel;
348
385
 
349
386
  await this.save();
350
387
 
351
- // Notify listeners
352
- const total = this.player.xp;
353
388
  this._publish('xp_gained', { amount, reason, leveledUp, newLevel, total });
354
-
355
389
  if (leveledUp) {
356
390
  this._publish('level_up', { oldLevel, newLevel, totalXP: total });
357
391
  }
@@ -359,140 +393,158 @@ export class RewardSystem extends EventEmitter {
359
393
  return { leveledUp, newLevel, xpGained: amount };
360
394
  }
361
395
 
362
- /**
363
- * Calculate level from XP (exponential curve)
364
- */
365
- _calculateLevel(xp) {
366
- // Curve: XP = 50 * level * (level - 1)
367
- // 50L² - 50L - xp = 0 => L = (1 + sqrt(1 + 4*xp/50)) / 2
368
- if (!(xp > 0)) return 1;
369
-
370
- const level = Math.floor((1 + Math.sqrt(1 + 4 * xp / 50)) / 2);
371
- return Math.max(1, level);
372
- }
373
-
374
396
  /**
375
397
  * Get XP needed for next level
376
398
  */
377
399
  getXPForNextLevel() {
378
400
  this._requirePlayer();
379
401
 
380
- const nextLevel = this.player.level + 1;
381
- const xpNeeded = 50 * nextLevel * (nextLevel - 1);
382
- const currentLevelXP = 50 * this.player.level * (this.player.level - 1);
402
+ const level = levelOf(this._doc);
403
+ const xp = xpOf(this._doc);
404
+ const xpNeeded = thresholdFor(level + 1);
405
+ const currentLevelXP = thresholdFor(level);
383
406
  const band = xpNeeded - currentLevelXP;
384
407
 
385
- // Clamped: a save written before the curve fix banked levels at half
386
- // the XP, so player.xp can sit below its own level's floor. Those
387
- // players keep the level they earned and start the band at 0.
408
+ // Clamped: a level banked under an older curve can sit above its own
409
+ // XP floor. Those players keep the level and start the band at 0.
388
410
  const progress = band > 0
389
- ? Math.max(0, Math.min(1, (this.player.xp - currentLevelXP) / band))
411
+ ? Math.max(0, Math.min(1, (xp - currentLevelXP) / band))
390
412
  : 0;
391
413
 
392
414
  return {
393
415
  total: xpNeeded,
394
- needed: Math.max(0, xpNeeded - this.player.xp),
416
+ needed: Math.max(0, xpNeeded - xp),
395
417
  progress
396
418
  };
397
419
  }
398
420
 
399
- /**
400
- * Record game result and award XP
401
- * @param {string} gameName - Unique ID for the game
402
- * @param {Object} result - Game-specific result data
403
- */
404
- async recordGame(gameName, result = {}) {
405
- this._requirePlayer();
406
-
407
- if (!isSafeKey(gameName)) {
408
- throw new TypeError(`[DopamineJS] recordGame expects a game name, received ${String(gameName)}`);
421
+ _checkRecord(activity, result) {
422
+ if (!isSafeKey(activity)) {
423
+ throw new TypeError(`[DopamineJS] record expects an activity name, received ${String(activity)}`);
409
424
  }
410
425
 
411
426
  if (!isRecord(result)) {
412
- throw new TypeError('[DopamineJS] recordGame expects a result object');
427
+ throw new TypeError('[DopamineJS] record expects a result object');
413
428
  }
414
429
 
415
430
  // Checked before anything is touched, so a bad score cannot leave the
416
431
  // play counted and the XP missing.
417
432
  if (result.score !== undefined && !Number.isFinite(result.score)) {
418
- throw new TypeError(`[DopamineJS] recordGame expects a finite score, received ${String(result.score)}`);
433
+ throw new TypeError(`[DopamineJS] record expects a finite score, received ${String(result.score)}`);
419
434
  }
435
+ }
420
436
 
421
- // Batched: addXP and each unlockAchievement below also save, which
422
- // meant four full serializations of the player object per game.
423
- return this._batch(() => this._recordGame(gameName, result));
437
+ /**
438
+ * Record a play and award XP
439
+ * @param {string} activity - Unique ID for the game or activity
440
+ * @param {Object} result - Result data. `score` sets the best; other numbers add up.
441
+ * @returns {Promise<boolean>} False when a beforeRecord hook rejected it
442
+ */
443
+ async record(activity, result = {}) {
444
+ this._requirePlayer();
445
+ this._checkRecord(activity, result);
446
+ if (!this._hasSlot()) return false;
447
+
448
+ const context = await this._middleware.before('beforeRecord', { activity, result }, (next) => {
449
+ try {
450
+ this._checkRecord(next.activity, next.result);
451
+ return true;
452
+ } catch {
453
+ return false;
454
+ }
455
+ });
456
+ if (context === false) return false;
457
+
458
+ // Batched: addXP and each unlockAchievement below also save.
459
+ const xp = await this._batch(() => this._record(context.activity, context.result));
460
+ await this._middleware.after('afterRecord', { activity: context.activity, result: context.result, xp });
461
+ return true;
424
462
  }
425
463
 
426
464
  /**
465
+ * Count today as a play day. A new player starts at 1 without an event.
427
466
  * @private
428
467
  */
429
- async _recordGame(gameName, result) {
430
- // A game played on a new day counts for the streak, not only a
431
- // page load. A tab left open past midnight used to miss the day.
432
- if (this._updateDailyStreak()) {
433
- this._publishStreak();
468
+ _markDay() {
469
+ const doc = this._doc;
470
+ const today = this.clock.localDate();
471
+ if (doc.playDates.includes(today)) return;
472
+ const firstEver = doc.playDates.length === 0;
473
+ doc.playDates = trimDays([...doc.playDates, today], today);
474
+ doc.longest = Math.max(doc.longest, longestRun(doc.playDates));
475
+ if (!firstEver) {
476
+ this._publish('streak_updated', {
477
+ current: currentStreak(doc.playDates, today),
478
+ longest: Math.max(doc.longest, longestRun(doc.playDates))
479
+ });
434
480
  }
481
+ }
435
482
 
436
- // Initialize stats for this game if not exists
437
- if (!hasOwn(this.player.stats, gameName)) {
438
- this.player.stats[gameName] = { totalPlays: 0, highScore: 0 };
439
- }
483
+ /**
484
+ * @private
485
+ */
486
+ async _record(activity, result) {
487
+ const doc = this._doc;
488
+ const device = this._deviceId;
489
+ const bump = (map, by) => {
490
+ map[device] = cap((hasOwn(map, device) ? map[device] : 0) + by);
491
+ };
440
492
 
441
- const stats = this.player.stats[gameName];
493
+ this._markDay();
494
+
495
+ if (!hasOwn(doc.playsBy, activity)) {
496
+ doc.playsBy[activity] = {};
497
+ doc.best[activity] = 0;
498
+ doc.sumsBy[activity] = {};
499
+ }
442
500
 
443
- // Update stats
444
- stats.totalPlays++;
445
- this.player.totalGamesPlayed++;
501
+ bump(doc.playsBy[activity], 1);
502
+ bump(doc.gamesBy, 1);
446
503
 
447
- // Update high score if applicable
448
- if (result.score !== undefined && result.score > stats.highScore) {
449
- stats.highScore = result.score;
450
- this._publish('new_high_score', { gameName, score: result.score });
504
+ if (result.score !== undefined && result.score > doc.best[activity]) {
505
+ doc.best[activity] = result.score;
506
+ this._publish('personal_best', { activity, score: result.score });
451
507
  }
452
508
 
453
- // Merge other result data into stats
454
- Object.keys(result).forEach(key => {
455
- if (key !== 'score' && isSafeKey(key)) {
456
- const current = hasOwn(stats, key) && Number.isFinite(stats[key]) ? stats[key] : 0;
457
- stats[key] = current + (Number.isFinite(result[key]) ? result[key] : 0);
458
- }
459
- });
509
+ // Other numbers add up per device. A negative or non-numeric value
510
+ // adds nothing, so a device's total only grows.
511
+ for (const key of Object.keys(result)) {
512
+ if (key === 'score' || key === 'plays' || key === 'best' || !isSafeKey(key)) continue;
513
+ if (!hasOwn(doc.sumsBy[activity], key)) doc.sumsBy[activity][key] = {};
514
+ bump(doc.sumsBy[activity][key], Number.isFinite(result[key]) && result[key] > 0 ? result[key] : 0);
515
+ }
460
516
 
461
517
  // Base XP for playing
462
518
  let xp = 10;
463
519
 
464
- // Score-based bonus. A negative score earns nothing extra; it does
465
- // not take XP away.
520
+ // Score-based bonus. A negative score earns nothing extra.
466
521
  if (result.score) {
467
522
  xp += Math.max(0, Math.floor(result.score / 5));
468
523
  }
469
524
 
470
- // Streak multiplier
471
525
  xp = Math.floor(xp * this.getStreakMultiplier());
472
526
 
473
- await this.addXP(xp, `Played ${gameName}`);
474
-
475
- // Check for achievements
476
- await this.checkAchievements(gameName, result);
477
-
527
+ await this.addXP(xp, `Played ${activity}`);
528
+ await this.checkAchievements(activity, result);
478
529
  await this.save();
530
+ return xp;
479
531
  }
480
532
 
481
533
  /**
482
534
  * Check and unlock achievements
483
535
  */
484
- async checkAchievements(gameName, result) {
536
+ async checkAchievements(activity, result) {
485
537
  const unlockedAchievements = [];
486
538
 
487
539
  for (const [id, achievement] of Object.entries(this.achievements)) {
488
540
  // Skip if already unlocked
489
- if (hasOwn(this.player.achievements, id)) continue;
541
+ if (hasOwn(this._doc.achievements, id)) continue;
490
542
 
491
543
  // Check conditions are user-supplied; one throwing must not stop
492
544
  // the others from ever unlocking.
493
545
  let met = false;
494
546
  try {
495
- met = achievement.check(this.player, gameName, result);
547
+ met = achievement.check(this.snapshot(), activity, result);
496
548
  } catch (error) {
497
549
  console.error(`[DopamineJS] Achievement "${id}" check threw:`, error);
498
550
  continue;
@@ -515,23 +567,29 @@ export class RewardSystem extends EventEmitter {
515
567
  if (!isSafeKey(achievementId) || !hasOwn(this.achievements, achievementId)) return false;
516
568
 
517
569
  // Already unlocked: paying the XP again would let one call farm levels.
518
- if (hasOwn(this.player.achievements, achievementId)) return false;
570
+ if (hasOwn(this._doc.achievements, achievementId)) return false;
519
571
 
520
572
  const achievement = this.achievements[achievementId];
521
573
  if (!achievement) return false;
522
574
 
523
- // Mark as unlocked
524
- this.player.achievements[achievementId] = {
525
- unlockedAt: Date.now(),
526
- seen: false
527
- };
575
+ const { [achievementId]: reward } = rewardsOf(this.achievements);
576
+ const context = await this._middleware.before(
577
+ 'beforeUnlock',
578
+ { id: achievementId, reward },
579
+ (next) => Number.isFinite(next.reward) && next.reward >= 0
580
+ );
581
+ if (context === false) return false;
582
+
583
+ const doc = this._doc;
584
+ const oldLevel = levelOf(doc);
585
+ doc.achievements[achievementId] = { unlockedAt: this.clock.now(), seen: false, reward: context.reward };
528
586
 
529
- // Award XP. `xp` is optional in a user-defined achievement.
530
- await this.addXP(Number.isFinite(achievement.xp) ? achievement.xp : 0,
531
- `Achievement: ${achievement.name}`);
587
+ // The reward is part of the achievement, not of any device's XP.
588
+ await this._announceXP(oldLevel, context.reward, `Achievement: ${achievement.name}`);
532
589
 
533
590
  this._publish('achievement_unlocked', { ...achievement, id: achievementId });
534
591
  await this.save();
592
+ await this._middleware.after('afterUnlock', { id: achievementId, reward: context.reward });
535
593
 
536
594
  return true;
537
595
  }
@@ -540,7 +598,8 @@ export class RewardSystem extends EventEmitter {
540
598
  * Get all unlocked achievements
541
599
  */
542
600
  getUnlockedAchievements() {
543
- return Object.entries(this.player.achievements)
601
+ this._requirePlayer();
602
+ return Object.entries(this._doc.achievements)
544
603
  .map(([id, data]) => ({
545
604
  ...this.achievements[id],
546
605
  id,
@@ -560,130 +619,21 @@ export class RewardSystem extends EventEmitter {
560
619
  */
561
620
  async markAchievementsSeen(achievementIds) {
562
621
  for (const id of achievementIds) {
563
- if (hasOwn(this.player.achievements, id)) {
564
- this.player.achievements[id].seen = true;
622
+ if (hasOwn(this._doc.achievements, id)) {
623
+ this._doc.achievements[id].seen = true;
565
624
  }
566
625
  }
567
626
  await this.save();
568
627
  }
569
628
 
570
- /**
571
- * Update daily streak
572
- * @returns {boolean} True when the calendar day changed
573
- */
574
- _updateDailyStreak() {
575
- const today = this._getTodayDateString();
576
- const lastPlayed = this.player.streak.lastPlayDate;
577
-
578
- if (lastPlayed === today) {
579
- // Already played today
580
- return false;
581
- }
582
-
583
- const yesterday = this._getYesterdayDateString();
584
-
585
- if (lastPlayed === yesterday) {
586
- // Streak continues!
587
- this.player.streak.current++;
588
- if (this.player.streak.current > this.player.streak.longest) {
589
- this.player.streak.longest = this.player.streak.current;
590
- }
591
- } else {
592
- // Streak broken
593
- this.player.streak.current = 1;
594
- }
595
-
596
- this.player.streak.lastPlayDate = today;
597
- return true;
598
- }
599
-
600
629
  /**
601
630
  * Get streak multiplier for XP
602
631
  */
603
632
  getStreakMultiplier() {
604
- const streak = this.player.streak.current;
633
+ const streak = this.snapshot().streak.current;
605
634
  if (streak >= 7) return 2.0; // 2× at 7 days
606
635
  if (streak >= 5) return 1.5; // 1.5× at 5 days
607
636
  if (streak >= 3) return 1.25; // 1.25× at 3 days
608
637
  return 1.0;
609
638
  }
610
-
611
- /**
612
- * Format a Date as a YYYY-MM-DD string in the player's local timezone.
613
- *
614
- * Deliberately not toISOString(), which formats in UTC. For anyone east or
615
- * west of Greenwich that shifts the calendar day for part of every day and
616
- * makes streaks reset or double-count.
617
- *
618
- * @param {Date} date
619
- * @returns {string}
620
- * @private
621
- */
622
- _toLocalDateString(date) {
623
- const year = date.getFullYear();
624
- const month = String(date.getMonth() + 1).padStart(2, '0');
625
- const day = String(date.getDate()).padStart(2, '0');
626
- return `${year}-${month}-${day}`;
627
- }
628
-
629
- /**
630
- * Get today's local date as YYYY-MM-DD string
631
- */
632
- _getTodayDateString() {
633
- return this._toLocalDateString(new Date());
634
- }
635
-
636
- /**
637
- * Get yesterday's local date as YYYY-MM-DD string
638
- */
639
- _getYesterdayDateString() {
640
- const yesterday = new Date();
641
- yesterday.setDate(yesterday.getDate() - 1);
642
- return this._toLocalDateString(yesterday);
643
- }
644
-
645
- /**
646
- * Initialize achievement definitions
647
- * Can be extended by games
648
- */
649
- _initAchievements() {
650
- return {
651
- // Universal achievements
652
- 'first_game': {
653
- name: 'First Steps',
654
- description: 'Play your first game',
655
- icon: '🎮',
656
- xp: 50,
657
- check: (player) => player.totalGamesPlayed >= 1
658
- },
659
- 'level_5': {
660
- name: 'Rising Star',
661
- description: 'Reach level 5',
662
- icon: '⭐',
663
- xp: 100,
664
- check: (player) => player.level >= 5
665
- },
666
- 'level_10': {
667
- name: 'Expert Player',
668
- description: 'Reach level 10',
669
- icon: '🏆',
670
- xp: 250,
671
- check: (player) => player.level >= 10
672
- },
673
- 'streak_3': {
674
- name: 'Dedicated',
675
- description: 'Play 3 days in a row',
676
- icon: '🔥',
677
- xp: 100,
678
- check: (player) => player.streak.current >= 3
679
- },
680
- 'streak_7': {
681
- name: 'Unstoppable',
682
- description: 'Play 7 days in a row',
683
- icon: '💥',
684
- xp: 300,
685
- check: (player) => player.streak.current >= 7
686
- }
687
- };
688
- }
689
639
  }