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