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
@@ -0,0 +1,737 @@
1
+ //#region 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 v = (e, t) => e.reduce((e, n) => n <= t && (!e || n > e) ? n : e, void 0), y = "legacy", b = /* @__PURE__ */ new Set([
104
+ "__proto__",
105
+ "constructor",
106
+ "prototype"
107
+ ]), x = (e) => typeof e == "string" && e.length > 0 && !b.has(e), S = (e, t) => Object.prototype.hasOwnProperty.call(e, t), C = (e) => typeof e == "object" && !!e && !Array.isArray(e), w = (e) => Number.isInteger(e) && e >= 0, T = (e) => Number.isFinite(e) && e >= 0, E = (e) => Number.isFinite(e), D = (e) => Math.min(e, 2 ** 53 - 1), O = (e, t, n = 0) => Number.isInteger(e) && e >= n ? D(e) : t, k = (e, t = (e) => e) => Object.keys(e).sort().reduce((n, r) => D(n + t(e[r])), 0), A = (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 j(e, t) {
124
+ let n = {};
125
+ if (!C(e)) return n;
126
+ for (let r of Object.keys(e)) x(r) && t(e[r]) && (n[r] = D(e[r]));
127
+ return n;
128
+ }
129
+ function M(e, t) {
130
+ let n = {};
131
+ if (!C(e)) return n;
132
+ for (let r of Object.keys(e)) x(r) && (n[r] = j(e[r], t));
133
+ return n;
134
+ }
135
+ function N(e, t) {
136
+ let n = {};
137
+ if (!C(e)) return n;
138
+ for (let r of Object.keys(e)) {
139
+ let i = e[r];
140
+ x(r) && C(i) && (n[r] = {
141
+ unlockedAt: E(i.unlockedAt) ? i.unlockedAt : t,
142
+ seen: i.seen === !0,
143
+ reward: T(i.reward) ? D(i.reward) : 0
144
+ });
145
+ }
146
+ return n;
147
+ }
148
+ function P(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) S(e.playsBy, r) || (e.playsBy[r] = {}), S(e.best, r) || (e.best[r] = 0), S(t, r) || (t[r] = {});
155
+ return e;
156
+ }
157
+ function F(e, t, n) {
158
+ return P({
159
+ v: 3,
160
+ name: typeof e.name == "string" ? e.name : "Player",
161
+ createdAt: E(e.createdAt) ? e.createdAt : t,
162
+ lastPlayedAt: E(e.lastPlayedAt) ? e.lastPlayedAt : t,
163
+ level: O(e.level, 1, 1),
164
+ longest: O(e.longest, 0),
165
+ playDates: h(Array.isArray(e.playDates) ? e.playDates.filter(p) : [], n),
166
+ xpBy: j(e.xpBy, T),
167
+ xpSpentBy: j(e.xpSpentBy, T),
168
+ gamesBy: j(e.gamesBy, w),
169
+ playsBy: M(e.playsBy, w),
170
+ best: j(e.best, T),
171
+ sumsBy: I(e.sumsBy),
172
+ achievements: N(e.achievements, t)
173
+ });
174
+ }
175
+ function I(e) {
176
+ let t = {};
177
+ if (!C(e)) return t;
178
+ for (let n of Object.keys(e)) x(n) && (t[n] = M(e[n], E));
179
+ return t;
180
+ }
181
+ function L(e, t, n, r) {
182
+ let a = A(t);
183
+ a.name = typeof e.name == "string" ? e.name : "Player", a.createdAt = E(e.createdAt) ? e.createdAt : t, a.lastPlayedAt = E(e.lastPlayedAt) ? e.lastPlayedAt : t, a.achievements = N(e.achievements, t);
184
+ let o = 0;
185
+ for (let e of Object.keys(a.achievements)) {
186
+ let t = S(n, e) && T(n[e]) ? D(n[e]) : 0;
187
+ a.achievements[e].reward = t, o += t;
188
+ }
189
+ let s = T(e.xp) ? D(e.xp) : 0, c = Math.max(0, s - o);
190
+ c > 0 && (a.xpBy[y] = c), a.level = Math.max(i(s), O(e.level, 1, 1));
191
+ let l = O(e.totalGamesPlayed, 0);
192
+ if (l > 0 && (a.gamesBy[y] = l), C(e.stats)) for (let t of Object.keys(e.stats)) {
193
+ let n = e.stats[t];
194
+ if (!x(t) || !C(n)) continue;
195
+ let r = O(n.totalPlays, 0);
196
+ a.playsBy[t] = r > 0 ? { [y]: r } : {}, a.best[t] = T(n.highScore) ? D(n.highScore) : 0, a.sumsBy[t] = {};
197
+ for (let e of Object.keys(n)) x(e) && e !== "totalPlays" && e !== "highScore" && E(n[e]) && (a.sumsBy[t][e] = { [y]: D(n[e]) });
198
+ }
199
+ let u = C(e.streak) ? e.streak : {}, d = O(u.current, 1, 1);
200
+ if (a.longest = Math.max(d, O(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 = O(u.longest, 0);
204
+ return P(a);
205
+ }
206
+ function R(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 z(e) {
217
+ if (R(e).size > 20) throw new t("too_many_devices", "[DopamineJS] a save holds at most 20 devices");
218
+ }
219
+ function B(e, n = {}) {
220
+ if (!C(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 = E(n.now) ? n.now : 0, i = p(n.today) ? n.today : void 0, a = e.v === 3 ? F(e, r, i) : L(e, r, C(n.rewards) ? n.rewards : s, i);
223
+ return z(a), a;
224
+ }
225
+ var V = (e) => D(Math.max(0, k(e.xpBy) + k(e.achievements, (e) => e.reward) - k(e.xpSpentBy))), H = (e) => Math.max(e.level, i(V(e)));
226
+ function U(e, t) {
227
+ let n = {};
228
+ for (let t of Object.keys(e.playsBy)) {
229
+ let r = {
230
+ plays: k(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] = k(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 = v(e.playDates, t);
242
+ return a && (i.lastPlayDate = a), {
243
+ name: e.name,
244
+ xp: V(e),
245
+ level: H(e),
246
+ totalGamesPlayed: k(e.gamesBy),
247
+ createdAt: e.createdAt,
248
+ lastPlayedAt: e.lastPlayedAt,
249
+ streak: i,
250
+ achievements: r,
251
+ stats: n
252
+ };
253
+ }
254
+ var W = (e) => JSON.parse(JSON.stringify(e));
255
+ function G(e) {
256
+ if (typeof e == "object" && e && !Object.isFrozen(e)) {
257
+ Object.freeze(e);
258
+ for (let t of Object.keys(e)) G(e[t]);
259
+ }
260
+ return e;
261
+ }
262
+ //#endregion
263
+ //#region src/dopamine/core/middleware.js
264
+ var K = [
265
+ "beforeXP",
266
+ "afterXP",
267
+ "beforeRecord",
268
+ "afterRecord",
269
+ "beforeUnlock",
270
+ "afterUnlock"
271
+ ], q = class {
272
+ constructor() {
273
+ this._list = [];
274
+ }
275
+ use(e) {
276
+ if (!C(e) || !K.some((t) => typeof e[t] == "function")) throw TypeError(`[DopamineJS] use expects an object with one of: ${K.join(", ")}`);
277
+ return this._list.push(e), () => {
278
+ let t = this._list.indexOf(e);
279
+ t >= 0 && this._list.splice(t, 1);
280
+ };
281
+ }
282
+ async before(e, t, n = () => !0) {
283
+ for (let r of [...this._list]) {
284
+ if (typeof r[e] != "function") continue;
285
+ let i;
286
+ try {
287
+ i = await r[e](Object.freeze({ ...t }));
288
+ } catch (t) {
289
+ console.error(`[DopamineJS] ${e} hook threw:`, t);
290
+ continue;
291
+ }
292
+ if (i === !1) return !1;
293
+ if (!C(i)) continue;
294
+ let a = { ...t };
295
+ for (let e of Object.keys(t)) Object.prototype.hasOwnProperty.call(i, e) && (a[e] = i[e]);
296
+ n(a) && (t = a);
297
+ }
298
+ return t;
299
+ }
300
+ async after(e, t) {
301
+ for (let n of [...this._list]) if (typeof n[e] == "function") try {
302
+ await n[e](Object.freeze({ ...t }));
303
+ } catch (t) {
304
+ console.error(`[DopamineJS] ${e} hook threw:`, t);
305
+ }
306
+ }
307
+ };
308
+ //#endregion
309
+ //#region src/dopamine/core/merge.js
310
+ function J(e, t, n) {
311
+ let r = {};
312
+ for (let i of /* @__PURE__ */ new Set([...Object.keys(e), ...Object.keys(t)])) {
313
+ let a = S(e, i) ? e[i] : void 0, o = S(t, i) ? t[i] : void 0;
314
+ r[i] = n > 0 ? J(a || {}, o || {}, n - 1) : a === void 0 ? o : o === void 0 ? a : Math.max(a, o);
315
+ }
316
+ return r;
317
+ }
318
+ function ee(e, t) {
319
+ let n = {};
320
+ for (let r of /* @__PURE__ */ new Set([...Object.keys(e), ...Object.keys(t)])) {
321
+ let i = S(e, r) ? e[r] : void 0, a = S(t, r) ? t[r] : void 0;
322
+ if (!i || !a) {
323
+ n[r] = { ...i || a };
324
+ continue;
325
+ }
326
+ let o = i.unlockedAt < a.unlockedAt || i.unlockedAt === a.unlockedAt && i.reward >= a.reward ? i : a;
327
+ n[r] = {
328
+ unlockedAt: o.unlockedAt,
329
+ seen: i.seen || a.seen,
330
+ reward: o.reward
331
+ };
332
+ }
333
+ return n;
334
+ }
335
+ var te = (e, t) => e > 0 && t > 0 ? Math.min(e, t) : Math.max(e, t);
336
+ function Y(e, t, n) {
337
+ let r = B(e, n), i = B(t, n), a = {
338
+ v: 3,
339
+ name: (r.lastPlayedAt === i.lastPlayedAt ? r.name >= i.name ? r : i : r.lastPlayedAt > i.lastPlayedAt ? r : i).name,
340
+ createdAt: te(r.createdAt, i.createdAt),
341
+ lastPlayedAt: Math.max(r.lastPlayedAt, i.lastPlayedAt),
342
+ level: Math.max(r.level, i.level),
343
+ longest: Math.max(r.longest, i.longest),
344
+ playDates: h([...r.playDates, ...i.playDates], p(n?.today) ? n.today : void 0),
345
+ xpBy: J(r.xpBy, i.xpBy, 0),
346
+ xpSpentBy: J(r.xpSpentBy, i.xpSpentBy, 0),
347
+ gamesBy: J(r.gamesBy, i.gamesBy, 0),
348
+ playsBy: J(r.playsBy, i.playsBy, 1),
349
+ best: J(r.best, i.best, 0),
350
+ sumsBy: J(r.sumsBy, i.sumsBy, 2),
351
+ achievements: ee(r.achievements, i.achievements)
352
+ };
353
+ return z(a), a;
354
+ }
355
+ //#endregion
356
+ //#region src/dopamine/core/RewardSystem.js
357
+ var X = "device", Z = () => {
358
+ let e = /* @__PURE__ */ new Uint8Array(8), t = globalThis.crypto;
359
+ if (typeof t?.getRandomValues == "function") t.getRandomValues(e);
360
+ else for (let t = 0; t < e.length; t++) e[t] = Math.floor(Math.random() * 256);
361
+ return Array.from(e, (e) => e.toString(16).padStart(2, "0")).join("");
362
+ }, ne = (e) => x(e) && e !== "legacy", re = class extends e {
363
+ constructor(e, t = {}) {
364
+ super(), this.dataService = e, this.clock = t.clock && typeof t.clock.now == "function" && typeof t.clock.localDate == "function" ? t.clock : r, this.achievements = {
365
+ ...o(),
366
+ ...t.achievements || {}
367
+ }, this.streakDays = t.streakDays === "record" ? "record" : "any", this._doc = null, this._deviceId = null, this._deviceSaved = !1, this._middleware = new q(), this._batchDepth = 0, this._pendingSave = !1, this._loadFailed = !1, this._readFailed = !1;
368
+ }
369
+ get loadFailed() {
370
+ return this._readFailed;
371
+ }
372
+ _publish(e, t) {
373
+ let n = Object.freeze({ ...t });
374
+ this.emit(e, n);
375
+ }
376
+ async _batch(e) {
377
+ this._batchDepth++;
378
+ try {
379
+ return await e();
380
+ } finally {
381
+ this._batchDepth--, this._batchDepth === 0 && this._pendingSave && (this._pendingSave = !1, await this._write());
382
+ }
383
+ }
384
+ _options() {
385
+ return {
386
+ now: this.clock.now(),
387
+ today: this.clock.localDate(),
388
+ rewards: c(this.achievements)
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 this._loadFailed = !1, this._readFailed = !1, e;
400
+ } catch (e) {
401
+ if (e?.code === "DOPAMINE_CORRUPT") {
402
+ let t = await this.dataService.save("player_corrupt", e.raw);
403
+ return t && (this._loadFailed = !1), this._readFailed = !t, this._publish("load_failed", {
404
+ key: "player",
405
+ reason: "corrupt",
406
+ backedUp: t
407
+ }), null;
408
+ }
409
+ return this._readFailed = !0, this._publish("load_failed", {
410
+ key: "player",
411
+ reason: "read",
412
+ error: e
413
+ }), null;
414
+ }
415
+ }
416
+ _load(e) {
417
+ if (!C(e)) return A(this.clock.now());
418
+ try {
419
+ return B(e, this._options());
420
+ } catch (e) {
421
+ if (!(e instanceof t)) throw e;
422
+ return this._loadFailed = !0, this._readFailed = !0, this._publish("load_failed", {
423
+ key: "player",
424
+ reason: e.code,
425
+ error: e
426
+ }), A(this.clock.now());
427
+ }
428
+ }
429
+ async _readDevice() {
430
+ if (this._deviceId) return;
431
+ let e = null;
432
+ try {
433
+ e = await this.dataService.load(X, null, { strict: !0 });
434
+ } catch {
435
+ this._deviceId = Z();
436
+ return;
437
+ }
438
+ ne(e) ? (this._deviceId = e, this._deviceSaved = !0) : this._deviceId = Z();
439
+ }
440
+ _hasSlot() {
441
+ let e = R(this._doc);
442
+ return e.has(this._deviceId) || e.size < 20 ? !0 : (this._publish("load_failed", {
443
+ key: "player",
444
+ reason: "too_many_devices"
445
+ }), !1);
446
+ }
447
+ _requirePlayer() {
448
+ if (!this._doc) throw Error("[DopamineJS] RewardSystem.init() must be awaited before use");
449
+ }
450
+ snapshot() {
451
+ return this._requirePlayer(), G(U(this._doc, this.clock.localDate()));
452
+ }
453
+ export() {
454
+ return this._requirePlayer(), W(this._doc);
455
+ }
456
+ async import(e, { silent: t = !1 } = {}) {
457
+ this._requirePlayer();
458
+ let n = this.snapshot(), r = B(e, this._options()), i = Y(this._doc, r, this._options());
459
+ i.level = H(i), this._doc = i;
460
+ let a = this.snapshot();
461
+ if (await this.save(), t) return a;
462
+ let o = a.xp - n.xp, s = a.level > n.level;
463
+ o > 0 && this._publish("xp_gained", {
464
+ amount: o,
465
+ reason: "import",
466
+ leveledUp: s,
467
+ newLevel: a.level,
468
+ total: a.xp
469
+ }), s && this._publish("level_up", {
470
+ oldLevel: n.level,
471
+ newLevel: a.level,
472
+ totalXP: a.xp
473
+ });
474
+ for (let e of Object.keys(a.achievements)) S(n.achievements, e) || this._publish("achievement_unlocked", {
475
+ ...this.achievements[e],
476
+ id: e
477
+ });
478
+ return a;
479
+ }
480
+ use(e) {
481
+ return this._middleware.use(e);
482
+ }
483
+ defineAchievement(e, t) {
484
+ if (!x(e)) throw TypeError(`[DopamineJS] defineAchievement expects an id, received ${String(e)}`);
485
+ if (!C(t) || typeof t.check != "function") throw TypeError("[DopamineJS] defineAchievement expects a definition with a check function");
486
+ let n = S(this.achievements, e) ? this.achievements[e] : void 0;
487
+ return this.achievements[e] = t, () => {
488
+ this.achievements[e] === t && (n ? this.achievements[e] = n : delete this.achievements[e]);
489
+ };
490
+ }
491
+ async save() {
492
+ if (this._doc) {
493
+ if (this._batchDepth > 0) {
494
+ this._pendingSave = !0;
495
+ return;
496
+ }
497
+ await this._write();
498
+ }
499
+ }
500
+ async _write() {
501
+ 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" }));
502
+ }
503
+ async addXP(e, t = "") {
504
+ if (!Number.isFinite(e)) throw TypeError(`[DopamineJS] addXP expects a finite number, received ${e}`);
505
+ if (this._requirePlayer(), !this._hasSlot()) return {
506
+ leveledUp: !1,
507
+ newLevel: H(this._doc),
508
+ xpGained: 0
509
+ };
510
+ let n = await this._middleware.before("beforeXP", {
511
+ amount: e,
512
+ reason: t
513
+ }, (e) => Number.isFinite(e.amount));
514
+ if (n === !1) return {
515
+ leveledUp: !1,
516
+ newLevel: H(this._doc),
517
+ xpGained: 0
518
+ };
519
+ this.streakDays === "any" && n.amount > 0 && this._markDay();
520
+ let r = await this._applyXP(n.amount, n.reason, (e, t) => {
521
+ t >= 0 ? e.xpBy[this._deviceId] = D((S(e.xpBy, this._deviceId) ? e.xpBy[this._deviceId] : 0) + t) : e.xpSpentBy[this._deviceId] = D((S(e.xpSpentBy, this._deviceId) ? e.xpSpentBy[this._deviceId] : 0) - t);
522
+ });
523
+ return await this._middleware.after("afterXP", {
524
+ amount: r.xpGained,
525
+ reason: n.reason,
526
+ total: V(this._doc),
527
+ level: r.newLevel
528
+ }), r;
529
+ }
530
+ async _applyXP(e, t, n) {
531
+ let r = this._doc, i = H(r);
532
+ return e = Math.max(e, -V(r)), n(r, e), this._announceXP(i, e, t);
533
+ }
534
+ async _announceXP(e, t, n) {
535
+ let r = this._doc, a = V(r), o = Math.max(e, i(a)), s = o > e;
536
+ return o > r.level && (r.level = o), await this.save(), this._publish("xp_gained", {
537
+ amount: t,
538
+ reason: n,
539
+ leveledUp: s,
540
+ newLevel: o,
541
+ total: a
542
+ }), s && this._publish("level_up", {
543
+ oldLevel: e,
544
+ newLevel: o,
545
+ totalXP: a
546
+ }), {
547
+ leveledUp: s,
548
+ newLevel: o,
549
+ xpGained: t
550
+ };
551
+ }
552
+ getXPForNextLevel() {
553
+ this._requirePlayer();
554
+ let e = H(this._doc), t = V(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;
555
+ return {
556
+ total: n,
557
+ needed: Math.max(0, n - t),
558
+ progress: o
559
+ };
560
+ }
561
+ _checkRecord(e, t) {
562
+ if (!x(e)) throw TypeError(`[DopamineJS] record expects an activity name, received ${String(e)}`);
563
+ if (!C(t)) throw TypeError("[DopamineJS] record expects a result object");
564
+ if (t.score !== void 0 && !Number.isFinite(t.score)) throw TypeError(`[DopamineJS] record expects a finite score, received ${String(t.score)}`);
565
+ }
566
+ async record(e, t = {}) {
567
+ if (this._requirePlayer(), this._checkRecord(e, t), !this._hasSlot()) return !1;
568
+ let n = await this._middleware.before("beforeRecord", {
569
+ activity: e,
570
+ result: t
571
+ }, (e) => {
572
+ try {
573
+ return this._checkRecord(e.activity, e.result), !0;
574
+ } catch {
575
+ return !1;
576
+ }
577
+ });
578
+ if (n === !1) return !1;
579
+ let r = await this._batch(() => this._record(n.activity, n.result));
580
+ return await this._middleware.after("afterRecord", {
581
+ activity: n.activity,
582
+ result: n.result,
583
+ xp: r
584
+ }), !0;
585
+ }
586
+ _markDay() {
587
+ let e = this._doc, t = this.clock.localDate();
588
+ if (e.playDates.includes(t)) return;
589
+ let n = e.playDates.length === 0;
590
+ e.playDates = h([...e.playDates, t], t), e.longest = Math.max(e.longest, _(e.playDates)), n || this._publish("streak_updated", {
591
+ current: g(e.playDates, t),
592
+ longest: Math.max(e.longest, _(e.playDates))
593
+ });
594
+ }
595
+ async _record(e, t) {
596
+ let n = this._doc, r = this._deviceId, i = (e, t) => {
597
+ e[r] = D((S(e, r) ? e[r] : 0) + t);
598
+ };
599
+ this._markDay(), S(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", {
600
+ activity: e,
601
+ score: t.score
602
+ }));
603
+ for (let r of Object.keys(t)) r !== "score" && r !== "plays" && r !== "best" && x(r) && (S(n.sumsBy[e], r) || (n.sumsBy[e][r] = {}), i(n.sumsBy[e][r], Number.isFinite(t[r]) && t[r] > 0 ? t[r] : 0));
604
+ let a = 10;
605
+ 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;
606
+ }
607
+ async checkAchievements(e, t) {
608
+ let n = [];
609
+ for (let [r, i] of Object.entries(this.achievements)) {
610
+ if (S(this._doc.achievements, r)) continue;
611
+ let a = !1;
612
+ try {
613
+ a = i.check(this.snapshot(), e, t);
614
+ } catch (e) {
615
+ console.error(`[DopamineJS] Achievement "${r}" check threw:`, e);
616
+ continue;
617
+ }
618
+ a && await this.unlockAchievement(r) && n.push(i);
619
+ }
620
+ return n;
621
+ }
622
+ async unlockAchievement(e) {
623
+ if (this._requirePlayer(), !x(e) || !S(this.achievements, e) || S(this._doc.achievements, e)) return !1;
624
+ let t = this.achievements[e];
625
+ if (!t) return !1;
626
+ let { [e]: n } = c(this.achievements), r = await this._middleware.before("beforeUnlock", {
627
+ id: e,
628
+ reward: n
629
+ }, (e) => Number.isFinite(e.reward) && e.reward >= 0);
630
+ if (r === !1) return !1;
631
+ let i = this._doc, a = H(i);
632
+ return i.achievements[e] = {
633
+ unlockedAt: this.clock.now(),
634
+ seen: !1,
635
+ reward: r.reward
636
+ }, await this._announceXP(a, r.reward, `Achievement: ${t.name}`), this._publish("achievement_unlocked", {
637
+ ...t,
638
+ id: e
639
+ }), await this.save(), await this._middleware.after("afterUnlock", {
640
+ id: e,
641
+ reward: r.reward
642
+ }), !0;
643
+ }
644
+ getUnlockedAchievements() {
645
+ return this._requirePlayer(), Object.entries(this._doc.achievements).map(([e, t]) => ({
646
+ ...this.achievements[e],
647
+ id: e,
648
+ ...t
649
+ }));
650
+ }
651
+ getUnseenAchievements() {
652
+ return this.getUnlockedAchievements().filter((e) => !e.seen);
653
+ }
654
+ async markAchievementsSeen(e) {
655
+ for (let t of e) S(this._doc.achievements, t) && (this._doc.achievements[t].seen = !0);
656
+ await this.save();
657
+ }
658
+ getStreakMultiplier() {
659
+ let e = this.snapshot().streak.current;
660
+ return e >= 7 ? 2 : e >= 5 ? 1.5 : e >= 3 ? 1.25 : 1;
661
+ }
662
+ };
663
+ //#endregion
664
+ //#region src/dopamine/utils/storage.js
665
+ function Q() {
666
+ let e = /* @__PURE__ */ new Map();
667
+ return {
668
+ getItem: (t) => e.has(t) ? e.get(t) : null,
669
+ setItem: (t, n) => {
670
+ e.set(t, String(n));
671
+ },
672
+ removeItem: (t) => {
673
+ e.delete(t);
674
+ },
675
+ clear: () => {
676
+ e.clear();
677
+ }
678
+ };
679
+ }
680
+ function $() {
681
+ try {
682
+ if (typeof localStorage > "u") return Q();
683
+ let e = "__dopamine_probe__";
684
+ return localStorage.setItem(e, "1"), localStorage.removeItem(e), localStorage;
685
+ } catch {
686
+ return Q();
687
+ }
688
+ }
689
+ //#endregion
690
+ //#region src/dopamine/core/DataService.js
691
+ var ie = class {
692
+ constructor(e = {}) {
693
+ this.storage = e.storage || $(), this.prefix = e.prefix || "dopamine_", this._tail = null;
694
+ }
695
+ _write(e) {
696
+ let t = this._tail ? this._tail.then(e) : e();
697
+ if (typeof t?.then == "function") {
698
+ let e = Promise.resolve(t).catch(() => {}).then(() => {
699
+ this._tail === e && (this._tail = null);
700
+ });
701
+ this._tail = e;
702
+ }
703
+ return t;
704
+ }
705
+ async save(e, t) {
706
+ try {
707
+ let n = JSON.stringify(t);
708
+ return await this._write(() => this.storage.setItem(this.prefix + e, n)), !0;
709
+ } catch (e) {
710
+ return console.error("Error saving data:", e), !1;
711
+ }
712
+ }
713
+ async load(e, t = null, n = {}) {
714
+ let r;
715
+ try {
716
+ await this._tail, r = await this.storage.getItem(this.prefix + e);
717
+ } catch (e) {
718
+ if (n.strict) throw e;
719
+ return console.error("Error loading data:", e), t;
720
+ }
721
+ if (!r) return t;
722
+ try {
723
+ return JSON.parse(r);
724
+ } catch (i) {
725
+ if (n.strict) throw Object.assign(/* @__PURE__ */ Error(`[DopamineJS] saved "${e}" is not valid JSON`), {
726
+ code: "DOPAMINE_CORRUPT",
727
+ raw: r
728
+ });
729
+ return console.error("Error loading data:", i), t;
730
+ }
731
+ }
732
+ async clear(e) {
733
+ await this._write(() => this.storage.removeItem(this.prefix + e));
734
+ }
735
+ };
736
+ //#endregion
737
+ export { Y as a, t as c, re as i, e as l, Q as n, B as o, $ as r, r as s, ie as t };