dopaminejs 3.4.0 → 3.6.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.
@@ -1,744 +0,0 @@
1
- // src/dopamine/core/EventEmitter.js
2
- var e = class {
3
- constructor() {
4
- this.listeners = /* @__PURE__ */ new Map();
5
- }
6
- on(e, t) {
7
- return this.listeners.has(e) || this.listeners.set(e, /* @__PURE__ */ new Set()), this.listeners.get(e).add(t), () => this.off(e, t);
8
- }
9
- off(e, t) {
10
- this.listeners.has(e) && this.listeners.get(e).delete(t);
11
- }
12
- emit(e, t) {
13
- this.listeners.has(e) && this.listeners.get(e).forEach((n) => {
14
- try {
15
- n(t);
16
- } catch (t) {
17
- console.error(`Error in listener for event '${e}':`, t);
18
- }
19
- });
20
- }
21
- clear() {
22
- this.listeners.clear();
23
- }
24
- }, t = class extends Error {
25
- constructor(e, t) {
26
- super(t || e), this.name = "DopamineError", this.code = e;
27
- }
28
- }, n = (e, t = 2) => String(e).padStart(t, "0"), r = {
29
- now: () => Date.now(),
30
- localDate(e = Date.now()) {
31
- let t = new Date(e);
32
- return `${n(t.getFullYear(), 4)}-${n(t.getMonth() + 1)}-${n(t.getDate())}`;
33
- }
34
- }, i = (e) => e > 0 ? Math.max(1, Math.floor((1 + Math.sqrt(1 + 4 * e / 50)) / 2)) : 1, a = (e) => 50 * e * (e - 1), o = () => ({
35
- first_game: {
36
- name: "First Steps",
37
- description: "Play your first game",
38
- icon: "🎮",
39
- xp: 50,
40
- check: (e) => e.totalGamesPlayed >= 1
41
- },
42
- level_5: {
43
- name: "Rising Star",
44
- description: "Reach level 5",
45
- icon: "⭐",
46
- xp: 100,
47
- check: (e) => e.level >= 5
48
- },
49
- level_10: {
50
- name: "Expert Player",
51
- description: "Reach level 10",
52
- icon: "🏆",
53
- xp: 250,
54
- check: (e) => e.level >= 10
55
- },
56
- streak_3: {
57
- name: "Dedicated",
58
- description: "Play 3 days in a row",
59
- icon: "🔥",
60
- xp: 100,
61
- check: (e) => e.streak.current >= 3
62
- },
63
- streak_7: {
64
- name: "Unstoppable",
65
- description: "Play 7 days in a row",
66
- icon: "💥",
67
- xp: 300,
68
- check: (e) => e.streak.current >= 7
69
- }
70
- }), s = {
71
- first_game: 50,
72
- level_5: 100,
73
- level_10: 250,
74
- streak_3: 100,
75
- streak_7: 300
76
- }, c = (e) => {
77
- let t = {};
78
- for (let n of Object.keys(e)) t[n] = Number.isFinite(e[n]?.xp) && e[n].xp > 0 ? e[n].xp : 0;
79
- return t;
80
- }, l = 864e5, u = /^\d{4}-\d{2}-\d{2}$/, d = (e) => {
81
- let t = /* @__PURE__ */ new Date(0);
82
- return t.setUTCFullYear(+e.slice(0, 4), e.slice(5, 7) - 1, +e.slice(8)), t.getTime() / l;
83
- }, f = (e) => (/* @__PURE__ */ new Date(e * l)).toISOString().slice(0, 10), p = (e) => typeof e == "string" && u.test(e) && f(d(e)) === e, m = (e, t) => f(d(e) + t);
84
- function h(e, t) {
85
- let n = [...new Set(e)].sort();
86
- if (!t) return n;
87
- let r = d(t) - 399, i = d(t) + 1;
88
- return n.filter((e) => d(e) >= r && d(e) <= i);
89
- }
90
- function g(e, t) {
91
- let n = new Set(e), r = n.has(t) ? t : m(t, -1), i = 0;
92
- for (; n.has(r);) i++, r = m(r, -1);
93
- return i;
94
- }
95
- function _(e) {
96
- let t = 0, n = 0, r = NaN;
97
- for (let i of [...e].sort()) {
98
- let e = d(i);
99
- n = e === r + 1 ? n + 1 : 1, r = e, n > t && (t = n);
100
- }
101
- return t;
102
- }
103
- var ee = (e, t) => e.reduce((e, n) => n <= t && (!e || n > e) ? n : e, void 0), v = "legacy", te = /* @__PURE__ */ new Set([
104
- "__proto__",
105
- "constructor",
106
- "prototype"
107
- ]), y = (e) => typeof e == "string" && e.length > 0 && !te.has(e), b = (e, t) => Object.prototype.hasOwnProperty.call(e, t), x = (e) => typeof e == "object" && !!e && !Array.isArray(e), S = (e) => Number.isInteger(e) && e >= 0, C = (e) => Number.isFinite(e) && e >= 0, w = (e) => Number.isFinite(e), T = (e) => Math.min(e, 2 ** 53 - 1), E = (e, t, n = 0) => Number.isInteger(e) && e >= n ? T(e) : t, D = (e, t = (e) => e) => Object.keys(e).sort().reduce((n, r) => T(n + t(e[r])), 0), O = (e = 0) => ({
108
- v: 3,
109
- name: "Player",
110
- createdAt: e,
111
- lastPlayedAt: e,
112
- level: 1,
113
- longest: 0,
114
- playDates: [],
115
- xpBy: {},
116
- xpSpentBy: {},
117
- gamesBy: {},
118
- playsBy: {},
119
- best: {},
120
- sumsBy: {},
121
- achievements: {}
122
- });
123
- function k(e, t) {
124
- let n = {};
125
- if (!x(e)) return n;
126
- for (let r of Object.keys(e)) y(r) && t(e[r]) && (n[r] = T(e[r]));
127
- return n;
128
- }
129
- function A(e, t) {
130
- let n = {};
131
- if (!x(e)) return n;
132
- for (let r of Object.keys(e)) y(r) && (n[r] = k(e[r], t));
133
- return n;
134
- }
135
- function j(e, t) {
136
- let n = {};
137
- if (!x(e)) return n;
138
- for (let r of Object.keys(e)) {
139
- let i = e[r];
140
- y(r) && x(i) && (n[r] = {
141
- unlockedAt: w(i.unlockedAt) ? i.unlockedAt : t,
142
- seen: i.seen === !0,
143
- reward: C(i.reward) ? T(i.reward) : 0
144
- });
145
- }
146
- return n;
147
- }
148
- function M(e) {
149
- let t = e.sumsBy, n = /* @__PURE__ */ new Set([
150
- ...Object.keys(e.playsBy),
151
- ...Object.keys(e.best),
152
- ...Object.keys(t)
153
- ]);
154
- for (let r of n) b(e.playsBy, r) || (e.playsBy[r] = {}), b(e.best, r) || (e.best[r] = 0), b(t, r) || (t[r] = {});
155
- return e;
156
- }
157
- function N(e, t, n) {
158
- return M({
159
- v: 3,
160
- name: typeof e.name == "string" ? e.name : "Player",
161
- createdAt: w(e.createdAt) ? e.createdAt : t,
162
- lastPlayedAt: w(e.lastPlayedAt) ? e.lastPlayedAt : t,
163
- level: E(e.level, 1, 1),
164
- longest: E(e.longest, 0),
165
- playDates: h(Array.isArray(e.playDates) ? e.playDates.filter(p) : [], n),
166
- xpBy: k(e.xpBy, C),
167
- xpSpentBy: k(e.xpSpentBy, C),
168
- gamesBy: k(e.gamesBy, S),
169
- playsBy: A(e.playsBy, S),
170
- best: k(e.best, C),
171
- sumsBy: P(e.sumsBy),
172
- achievements: j(e.achievements, t)
173
- });
174
- }
175
- function P(e) {
176
- let t = {};
177
- if (!x(e)) return t;
178
- for (let n of Object.keys(e)) y(n) && (t[n] = A(e[n], C));
179
- return t;
180
- }
181
- function F(e, t, n, r) {
182
- let a = O(t);
183
- a.name = typeof e.name == "string" ? e.name : "Player", a.createdAt = w(e.createdAt) ? e.createdAt : t, a.lastPlayedAt = w(e.lastPlayedAt) ? e.lastPlayedAt : t, a.achievements = j(e.achievements, t);
184
- let o = 0;
185
- for (let e of Object.keys(a.achievements)) {
186
- let t = b(n, e) && C(n[e]) ? T(n[e]) : 0;
187
- a.achievements[e].reward = t, o += t;
188
- }
189
- let s = C(e.xp) ? T(e.xp) : 0, c = Math.max(0, s - o);
190
- c > 0 && (a.xpBy[v] = c), a.level = Math.max(i(s), E(e.level, 1, 1));
191
- let l = E(e.totalGamesPlayed, 0);
192
- if (l > 0 && (a.gamesBy[v] = l), x(e.stats)) for (let t of Object.keys(e.stats)) {
193
- let n = e.stats[t];
194
- if (!y(t) || !x(n)) continue;
195
- let r = E(n.totalPlays, 0);
196
- a.playsBy[t] = r > 0 ? { [v]: r } : {}, a.best[t] = C(n.highScore) ? T(n.highScore) : 0, a.sumsBy[t] = {};
197
- for (let e of Object.keys(n)) y(e) && e !== "totalPlays" && e !== "highScore" && C(n[e]) && (a.sumsBy[t][e] = { [v]: T(n[e]) });
198
- }
199
- let u = x(e.streak) ? e.streak : {}, d = E(u.current, 1, 1);
200
- if (a.longest = Math.max(d, E(u.longest, 0)), p(u.lastPlayDate)) {
201
- for (let e = 0; e < Math.min(d, 400); e++) a.playDates.push(m(u.lastPlayDate, -e));
202
- a.playDates = h(a.playDates, r);
203
- } else a.longest = E(u.longest, 0);
204
- return M(a);
205
- }
206
- function I(e) {
207
- let t = /* @__PURE__ */ new Set([
208
- ...Object.keys(e.xpBy),
209
- ...Object.keys(e.xpSpentBy),
210
- ...Object.keys(e.gamesBy)
211
- ]);
212
- for (let n of Object.keys(e.playsBy)) for (let r of Object.keys(e.playsBy[n])) t.add(r);
213
- for (let n of Object.keys(e.sumsBy)) for (let r of Object.keys(e.sumsBy[n])) for (let i of Object.keys(e.sumsBy[n][r])) t.add(i);
214
- return t;
215
- }
216
- function L(e) {
217
- if (I(e).size > 20) throw new t("too_many_devices", "[DopamineJS] a save holds at most 20 devices");
218
- }
219
- function R(e, n = {}) {
220
- if (!x(e)) throw new t("invalid_document", "[DopamineJS] a save must be an object");
221
- if (e.v !== void 0 && e.v !== 3) throw new t("unsupported_version", `[DopamineJS] save version ${String(e.v)} is not 3`);
222
- let r = w(n.now) ? n.now : 0, i = p(n.today) ? n.today : void 0, a = e.v === 3 ? N(e, r, i) : F(e, r, x(n.rewards) ? n.rewards : s, i);
223
- return L(a), a;
224
- }
225
- var z = (e) => T(Math.max(0, D(e.xpBy) + D(e.achievements, (e) => e.reward) - D(e.xpSpentBy))), B = (e) => Math.max(e.level, i(z(e)));
226
- function V(e, t) {
227
- let n = {};
228
- for (let t of Object.keys(e.playsBy)) {
229
- let r = {
230
- plays: D(e.playsBy[t]),
231
- best: e.best[t]
232
- };
233
- for (let n of Object.keys(e.sumsBy[t])) n !== "plays" && n !== "best" && (r[n] = D(e.sumsBy[t][n]));
234
- n[t] = r;
235
- }
236
- let r = {};
237
- for (let t of Object.keys(e.achievements)) r[t] = { ...e.achievements[t] };
238
- let i = {
239
- current: g(e.playDates, t),
240
- longest: Math.max(e.longest, _(e.playDates))
241
- }, a = ee(e.playDates, t);
242
- return a && (i.lastPlayDate = a), {
243
- name: e.name,
244
- xp: z(e),
245
- level: B(e),
246
- totalGamesPlayed: D(e.gamesBy),
247
- createdAt: e.createdAt,
248
- lastPlayedAt: e.lastPlayedAt,
249
- streak: i,
250
- achievements: r,
251
- stats: n
252
- };
253
- }
254
- var H = (e) => JSON.parse(JSON.stringify(e));
255
- function U(e) {
256
- if (typeof e == "object" && e && !Object.isFrozen(e)) {
257
- Object.freeze(e);
258
- for (let t of Object.keys(e)) U(e[t]);
259
- }
260
- return e;
261
- }
262
- // src/dopamine/core/middleware.js
263
- var W = [
264
- "beforeXP",
265
- "afterXP",
266
- "beforeRecord",
267
- "afterRecord",
268
- "beforeUnlock",
269
- "afterUnlock"
270
- ], G = class {
271
- constructor() {
272
- this._list = [];
273
- }
274
- use(e) {
275
- if (!x(e) || !W.some((t) => typeof e[t] == "function")) throw TypeError(`[DopamineJS] use expects an object with one of: ${W.join(", ")}`);
276
- return this._list.push(e), () => {
277
- let t = this._list.indexOf(e);
278
- t >= 0 && this._list.splice(t, 1);
279
- };
280
- }
281
- async before(e, t, n = () => !0) {
282
- for (let r of [...this._list]) {
283
- if (typeof r[e] != "function") continue;
284
- let i;
285
- try {
286
- i = await r[e](Object.freeze({ ...t }));
287
- } catch (t) {
288
- console.error(`[DopamineJS] ${e} hook threw:`, t);
289
- continue;
290
- }
291
- if (i === !1) return !1;
292
- if (!x(i)) continue;
293
- let a = { ...t };
294
- for (let e of Object.keys(t)) Object.prototype.hasOwnProperty.call(i, e) && (a[e] = i[e]);
295
- n(a) && (t = a);
296
- }
297
- return t;
298
- }
299
- async after(e, t) {
300
- for (let n of [...this._list]) if (typeof n[e] == "function") try {
301
- await n[e](Object.freeze({ ...t }));
302
- } catch (t) {
303
- console.error(`[DopamineJS] ${e} hook threw:`, t);
304
- }
305
- }
306
- };
307
- // src/dopamine/core/merge.js
308
- function K(e, t, n) {
309
- let r = {};
310
- for (let i of /* @__PURE__ */ new Set([...Object.keys(e), ...Object.keys(t)])) {
311
- let a = b(e, i) ? e[i] : void 0, o = b(t, i) ? t[i] : void 0;
312
- r[i] = n > 0 ? K(a || {}, o || {}, n - 1) : a === void 0 ? o : o === void 0 ? a : Math.max(a, o);
313
- }
314
- return r;
315
- }
316
- function q(e, t) {
317
- let n = {};
318
- for (let r of /* @__PURE__ */ new Set([...Object.keys(e), ...Object.keys(t)])) {
319
- let i = b(e, r) ? e[r] : void 0, a = b(t, r) ? t[r] : void 0;
320
- if (!i || !a) {
321
- n[r] = { ...i || a };
322
- continue;
323
- }
324
- let o = i.unlockedAt < a.unlockedAt || i.unlockedAt === a.unlockedAt && i.reward >= a.reward ? i : a;
325
- n[r] = {
326
- unlockedAt: o.unlockedAt,
327
- seen: i.seen || a.seen,
328
- reward: o.reward
329
- };
330
- }
331
- return n;
332
- }
333
- var J = (e, t) => e > 0 && t > 0 ? Math.min(e, t) : Math.max(e, t);
334
- function Y(e, t, n) {
335
- let r = R(e, n), i = R(t, n), a = {
336
- v: 3,
337
- name: (r.lastPlayedAt === i.lastPlayedAt ? r.name >= i.name ? r : i : r.lastPlayedAt > i.lastPlayedAt ? r : i).name,
338
- createdAt: J(r.createdAt, i.createdAt),
339
- lastPlayedAt: Math.max(r.lastPlayedAt, i.lastPlayedAt),
340
- level: Math.max(r.level, i.level),
341
- longest: Math.max(r.longest, i.longest),
342
- playDates: h([...r.playDates, ...i.playDates], p(n?.today) ? n.today : void 0),
343
- xpBy: K(r.xpBy, i.xpBy, 0),
344
- xpSpentBy: K(r.xpSpentBy, i.xpSpentBy, 0),
345
- gamesBy: K(r.gamesBy, i.gamesBy, 0),
346
- playsBy: K(r.playsBy, i.playsBy, 1),
347
- best: K(r.best, i.best, 0),
348
- sumsBy: K(r.sumsBy, i.sumsBy, 2),
349
- achievements: q(r.achievements, i.achievements)
350
- };
351
- return L(a), a;
352
- }
353
- // src/dopamine/core/RewardSystem.js
354
- var X = "device", Z = () => {
355
- let e = /* @__PURE__ */ new Uint8Array(8), t = globalThis.crypto;
356
- if (typeof t?.getRandomValues == "function") t.getRandomValues(e);
357
- else for (let t = 0; t < e.length; t++) e[t] = Math.floor(Math.random() * 256);
358
- return Array.from(e, (e) => e.toString(16).padStart(2, "0")).join("");
359
- }, ne = (e) => y(e) && e !== "legacy", re = class extends e {
360
- constructor(e, t = {}) {
361
- super(), this.dataService = e, this.clock = t.clock && typeof t.clock.now == "function" && typeof t.clock.localDate == "function" ? t.clock : r, this.achievements = {
362
- ...t.builtinAchievements === !1 ? {} : o(),
363
- ...t.achievements || {}
364
- }, this.streakDays = t.streakDays === "record" ? "record" : "any", this._doc = null, this._deviceId = null, this._deviceSaved = !1, this._middleware = new G(), this._unlocking = /* @__PURE__ */ new Set(), this._batchDepth = 0, this._pendingSave = !1, this._loadFailed = !1, this._readFailed = !1;
365
- }
366
- get loadFailed() {
367
- return this._readFailed;
368
- }
369
- _publish(e, t) {
370
- let n = Object.freeze({ ...t });
371
- this.emit(e, n);
372
- }
373
- async _batch(e) {
374
- this._batchDepth++;
375
- try {
376
- return await e();
377
- } finally {
378
- this._batchDepth--, this._batchDepth === 0 && this._pendingSave && (this._pendingSave = !1, await this._write());
379
- }
380
- }
381
- _options() {
382
- return {
383
- now: this.clock.now(),
384
- today: this.clock.localDate(),
385
- rewards: {
386
- ...s,
387
- ...c(this.achievements)
388
- }
389
- };
390
- }
391
- async init() {
392
- let e = await this._readSaved();
393
- return this._loadFailed && this._doc || (this._doc = this._load(e)), await this._readDevice(), await this.save(), this.snapshot();
394
- }
395
- async _readSaved() {
396
- this._loadFailed = !0;
397
- try {
398
- let e = await this.dataService.load("player", null, { strict: !0 });
399
- return e !== null && !x(e) ? await this._keepCorrupt(e) : (this._loadFailed = !1, this._readFailed = !1, e);
400
- } catch (e) {
401
- return e?.code === "DOPAMINE_CORRUPT" ? this._keepCorrupt(e.raw) : (this._readFailed = !0, this._publish("load_failed", {
402
- key: "player",
403
- reason: "read",
404
- error: e
405
- }), null);
406
- }
407
- }
408
- async _keepCorrupt(e) {
409
- this._loadFailed = !0;
410
- let t = await this.dataService.save("player_corrupt", e);
411
- return t && (this._loadFailed = !1), this._readFailed = !t, this._publish("load_failed", {
412
- key: "player",
413
- reason: "corrupt",
414
- backedUp: t
415
- }), null;
416
- }
417
- _load(e) {
418
- if (!x(e)) return O(this.clock.now());
419
- try {
420
- return R(e, this._options());
421
- } catch (e) {
422
- if (!(e instanceof t)) throw e;
423
- return this._loadFailed = !0, this._readFailed = !0, this._publish("load_failed", {
424
- key: "player",
425
- reason: e.code,
426
- error: e
427
- }), O(this.clock.now());
428
- }
429
- }
430
- async _readDevice() {
431
- if (this._deviceId) return;
432
- let e = null;
433
- try {
434
- e = await this.dataService.load(X, null, { strict: !0 });
435
- } catch {
436
- this._deviceId = Z();
437
- return;
438
- }
439
- ne(e) ? (this._deviceId = e, this._deviceSaved = !0) : this._deviceId = Z();
440
- }
441
- _hasSlot() {
442
- let e = I(this._doc);
443
- return e.has(this._deviceId) || e.size < 20 ? !0 : (this._publish("load_failed", {
444
- key: "player",
445
- reason: "too_many_devices"
446
- }), !1);
447
- }
448
- _requirePlayer() {
449
- if (!this._doc) throw Error("[DopamineJS] RewardSystem.init() must be awaited before use");
450
- }
451
- snapshot() {
452
- return this._requirePlayer(), U(V(this._doc, this.clock.localDate()));
453
- }
454
- export() {
455
- return this._requirePlayer(), H(this._doc);
456
- }
457
- async import(e, { silent: t = !1 } = {}) {
458
- this._requirePlayer();
459
- let n = this.snapshot(), r = R(e, this._options()), i = Y(this._doc, r, this._options());
460
- i.level = B(i), this._doc = i;
461
- let a = this.snapshot();
462
- if (await this.save(), t) return a;
463
- let o = a.xp - n.xp, s = a.level > n.level;
464
- o > 0 && this._publish("xp_gained", {
465
- amount: o,
466
- reason: "import",
467
- leveledUp: s,
468
- newLevel: a.level,
469
- total: a.xp
470
- }), s && this._publish("level_up", {
471
- oldLevel: n.level,
472
- newLevel: a.level,
473
- totalXP: a.xp
474
- });
475
- for (let e of Object.keys(a.achievements)) !b(n.achievements, e) && b(this.achievements, e) && this._publish("achievement_unlocked", {
476
- ...this.achievements[e],
477
- id: e
478
- });
479
- return a;
480
- }
481
- async reset(e) {
482
- let t = e?.overwrite;
483
- if (e !== void 0 && (typeof e != "object" || !e || Array.isArray(e)) || t !== void 0 && typeof t != "boolean") throw TypeError("[DopamineJS] reset expects { overwrite?: boolean }");
484
- return this._requirePlayer(), t === !1 && this._readFailed ? (this._doc = O(this.clock.now()), this._publish("player_reset", {}), this.snapshot()) : (await this._batch(async () => {
485
- this._doc = O(this.clock.now()), this._loadFailed = !1, this._readFailed = !1, await this.save();
486
- }), this._publish("player_reset", {}), this.snapshot());
487
- }
488
- use(e) {
489
- return this._middleware.use(e);
490
- }
491
- defineAchievement(e, t) {
492
- if (!y(e)) throw TypeError(`[DopamineJS] defineAchievement expects an id, received ${String(e)}`);
493
- if (!x(t) || typeof t.check != "function") throw TypeError("[DopamineJS] defineAchievement expects a definition with a check function");
494
- let n = b(this.achievements, e) ? this.achievements[e] : void 0;
495
- return this.achievements[e] = t, () => {
496
- this.achievements[e] === t && (n ? this.achievements[e] = n : delete this.achievements[e]);
497
- };
498
- }
499
- async save() {
500
- this._doc && (this._batchDepth > 0 ? this._pendingSave = !0 : await this._write());
501
- }
502
- async _write() {
503
- this._loadFailed || (this._doc.lastPlayedAt = this.clock.now(), this._deviceSaved ||= await this.dataService.save(X, this._deviceId) !== !1, await this.dataService.save("player", this._doc) === !1 && this._publish("save_failed", { key: "player" }));
504
- }
505
- async addXP(e, t = "") {
506
- if (!Number.isFinite(e)) throw TypeError(`[DopamineJS] addXP expects a finite number, received ${e}`);
507
- if (this._requirePlayer(), !this._hasSlot()) return {
508
- leveledUp: !1,
509
- newLevel: B(this._doc),
510
- xpGained: 0
511
- };
512
- let n = await this._middleware.before("beforeXP", {
513
- amount: e,
514
- reason: t
515
- }, (e) => Number.isFinite(e.amount));
516
- if (n === !1) return {
517
- leveledUp: !1,
518
- newLevel: B(this._doc),
519
- xpGained: 0
520
- };
521
- this.streakDays === "any" && n.amount > 0 && this._markDay();
522
- let r = await this._applyXP(n.amount, n.reason, (e, t) => {
523
- t >= 0 ? e.xpBy[this._deviceId] = T((b(e.xpBy, this._deviceId) ? e.xpBy[this._deviceId] : 0) + t) : e.xpSpentBy[this._deviceId] = T((b(e.xpSpentBy, this._deviceId) ? e.xpSpentBy[this._deviceId] : 0) - t);
524
- });
525
- return await this._middleware.after("afterXP", {
526
- amount: r.xpGained,
527
- reason: n.reason,
528
- total: z(this._doc),
529
- level: r.newLevel
530
- }), r;
531
- }
532
- async _applyXP(e, t, n) {
533
- let r = this._doc, i = B(r);
534
- return e = Math.max(e, -z(r)), n(r, e), this._announceXP(i, e, t);
535
- }
536
- async _announceXP(e, t, n) {
537
- let r = this._doc, a = z(r), o = Math.max(e, i(a)), s = o > e;
538
- return o > r.level && (r.level = o), await this.save(), this._publish("xp_gained", {
539
- amount: t,
540
- reason: n,
541
- leveledUp: s,
542
- newLevel: o,
543
- total: a
544
- }), s && this._publish("level_up", {
545
- oldLevel: e,
546
- newLevel: o,
547
- totalXP: a
548
- }), {
549
- leveledUp: s,
550
- newLevel: o,
551
- xpGained: t
552
- };
553
- }
554
- getXPForNextLevel() {
555
- this._requirePlayer();
556
- let e = B(this._doc), t = z(this._doc), n = a(e + 1), r = a(e), i = n - r, o = i > 0 ? Math.max(0, Math.min(1, (t - r) / i)) : 0;
557
- return {
558
- total: n,
559
- needed: Math.max(0, n - t),
560
- progress: o
561
- };
562
- }
563
- _checkRecord(e, t) {
564
- if (!y(e)) throw TypeError(`[DopamineJS] record expects an activity name, received ${String(e)}`);
565
- if (!x(t)) throw TypeError("[DopamineJS] record expects a result object");
566
- if (t.score !== void 0 && !Number.isFinite(t.score)) throw TypeError(`[DopamineJS] record expects a finite score, received ${String(t.score)}`);
567
- }
568
- async record(e, t = {}) {
569
- if (this._requirePlayer(), this._checkRecord(e, t), !this._hasSlot()) return !1;
570
- let n = await this._middleware.before("beforeRecord", {
571
- activity: e,
572
- result: t
573
- }, (e) => {
574
- try {
575
- return this._checkRecord(e.activity, e.result), !0;
576
- } catch {
577
- return !1;
578
- }
579
- });
580
- if (n === !1) return !1;
581
- let r = await this._batch(() => this._record(n.activity, n.result));
582
- return await this._middleware.after("afterRecord", {
583
- activity: n.activity,
584
- result: n.result,
585
- xp: r
586
- }), !0;
587
- }
588
- _markDay() {
589
- let e = this._doc, t = this.clock.localDate();
590
- if (e.playDates.includes(t)) return;
591
- let n = e.playDates.length === 0;
592
- e.playDates = h([...e.playDates, t], t), e.longest = Math.max(e.longest, _(e.playDates)), n || this._publish("streak_updated", {
593
- current: g(e.playDates, t),
594
- longest: Math.max(e.longest, _(e.playDates))
595
- });
596
- }
597
- async _record(e, t) {
598
- let n = this._doc, r = this._deviceId, i = (e, t) => {
599
- e[r] = T((b(e, r) ? e[r] : 0) + t);
600
- };
601
- this._markDay(), b(n.playsBy, e) || (n.playsBy[e] = {}, n.best[e] = 0, n.sumsBy[e] = {}), i(n.playsBy[e], 1), i(n.gamesBy, 1), t.score !== void 0 && t.score > n.best[e] && (n.best[e] = t.score, this._publish("personal_best", {
602
- activity: e,
603
- score: t.score
604
- }));
605
- for (let r of Object.keys(t)) r !== "score" && r !== "plays" && r !== "best" && y(r) && (b(n.sumsBy[e], r) || (n.sumsBy[e][r] = {}), i(n.sumsBy[e][r], Number.isFinite(t[r]) && t[r] > 0 ? t[r] : 0));
606
- let a = 10;
607
- return t.score && (a += Math.max(0, Math.floor(t.score / 5))), a = Math.floor(a * this.getStreakMultiplier()), await this.addXP(a, `Played ${e}`), await this.checkAchievements(e, t), await this.save(), a;
608
- }
609
- async checkAchievements(e, t) {
610
- let n = [];
611
- for (let [r, i] of Object.entries(this.achievements)) {
612
- if (b(this._doc.achievements, r)) continue;
613
- let a = !1;
614
- try {
615
- a = i.check(this.snapshot(), e, t);
616
- } catch (e) {
617
- console.error(`[DopamineJS] Achievement "${r}" check threw:`, e);
618
- continue;
619
- }
620
- a && await this.unlockAchievement(r) && n.push(i);
621
- }
622
- return n;
623
- }
624
- async unlockAchievement(e) {
625
- if (this._requirePlayer(), !y(e) || !b(this.achievements, e) || b(this._doc.achievements, e) || this._unlocking.has(e)) return !1;
626
- let t = this.achievements[e];
627
- if (!t) return !1;
628
- let { [e]: n } = c(this.achievements);
629
- this._unlocking.add(e);
630
- let r;
631
- try {
632
- r = await this._middleware.before("beforeUnlock", {
633
- id: e,
634
- reward: n
635
- }, (e) => Number.isFinite(e.reward) && e.reward >= 0);
636
- } finally {
637
- this._unlocking.delete(e);
638
- }
639
- if (r === !1 || b(this._doc.achievements, e)) return !1;
640
- let i = this._doc, a = B(i);
641
- return i.achievements[e] = {
642
- unlockedAt: this.clock.now(),
643
- seen: !1,
644
- reward: r.reward
645
- }, await this._announceXP(a, r.reward, `Achievement: ${t.name}`), this._publish("achievement_unlocked", {
646
- ...t,
647
- id: e
648
- }), await this.save(), await this._middleware.after("afterUnlock", {
649
- id: e,
650
- reward: r.reward
651
- }), !0;
652
- }
653
- getUnlockedAchievements() {
654
- return this._requirePlayer(), Object.entries(this._doc.achievements).map(([e, t]) => ({
655
- ...this.achievements[e],
656
- id: e,
657
- ...t
658
- }));
659
- }
660
- getUnseenAchievements() {
661
- return this.getUnlockedAchievements().filter((e) => !e.seen);
662
- }
663
- async markAchievementsSeen(e) {
664
- this._requirePlayer();
665
- for (let t of e) b(this._doc.achievements, t) && (this._doc.achievements[t].seen = !0);
666
- await this.save();
667
- }
668
- getStreakMultiplier() {
669
- let e = this.snapshot().streak.current;
670
- return e >= 7 ? 2 : e >= 5 ? 1.5 : e >= 3 ? 1.25 : 1;
671
- }
672
- };
673
- // src/dopamine/utils/storage.js
674
- function Q() {
675
- let e = /* @__PURE__ */ new Map();
676
- return {
677
- getItem: (t) => e.has(t) ? e.get(t) : null,
678
- setItem: (t, n) => {
679
- e.set(t, String(n));
680
- },
681
- removeItem: (t) => {
682
- e.delete(t);
683
- },
684
- clear: () => {
685
- e.clear();
686
- }
687
- };
688
- }
689
- function $() {
690
- try {
691
- if (typeof localStorage > "u") return Q();
692
- let e = "__dopamine_probe__";
693
- return localStorage.setItem(e, "1"), localStorage.removeItem(e), localStorage;
694
- } catch {
695
- return Q();
696
- }
697
- }
698
- // src/dopamine/core/DataService.js
699
- var ie = class {
700
- constructor(e = {}) {
701
- this.storage = e.storage || $(), this.prefix = e.prefix || "dopamine_", this._tail = null;
702
- }
703
- _write(e) {
704
- let t = this._tail ? this._tail.then(e) : e();
705
- if (typeof t?.then == "function") {
706
- let e = Promise.resolve(t).catch(() => {}).then(() => {
707
- this._tail === e && (this._tail = null);
708
- });
709
- this._tail = e;
710
- }
711
- return t;
712
- }
713
- async save(e, t) {
714
- try {
715
- let n = JSON.stringify(t);
716
- return await this._write(() => this.storage.setItem(this.prefix + e, n)), !0;
717
- } catch (e) {
718
- return console.error("Error saving data:", e), !1;
719
- }
720
- }
721
- async load(e, t = null, n = {}) {
722
- let r;
723
- try {
724
- await this._tail, r = await this.storage.getItem(this.prefix + e);
725
- } catch (e) {
726
- if (n.strict) throw e;
727
- return console.error("Error loading data:", e), t;
728
- }
729
- if (!r) return t;
730
- try {
731
- return JSON.parse(r);
732
- } catch (i) {
733
- if (n.strict) throw Object.assign(/* @__PURE__ */ Error(`[DopamineJS] saved "${e}" is not valid JSON`), {
734
- code: "DOPAMINE_CORRUPT",
735
- raw: r
736
- });
737
- return console.error("Error loading data:", i), t;
738
- }
739
- }
740
- async clear(e) {
741
- await this._write(() => this.storage.removeItem(this.prefix + e));
742
- }
743
- };
744
- export { Y as a, t as c, re as i, e as l, Q as n, R as o, $ as r, r as s, ie as t };