dopaminejs 3.2.0 → 3.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -0
- package/dist/{DataService-Bd1S-C1N.js → DataService-CydwGT_D.js} +151 -154
- package/dist/DataService-EJeOPnbo.cjs +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.js +1 -2
- package/dist/dopamine.cjs +1 -1
- package/dist/dopamine.global.js +37 -0
- package/dist/dopamine.js +3 -3
- package/dist/games.js +1 -2
- package/dist/{host-CkBQnCdp.js → host-DOvdGHZL.js} +39 -20
- package/dist/host-MPzunSej.cjs +37 -0
- package/dist/style.css +13 -12
- package/dist/testing.cjs +1 -1
- package/dist/testing.js +11 -12
- package/package.json +4 -2
- package/spec/README.md +3 -2
- package/spec/fixtures/merge.json +39 -0
- package/spec/fixtures/migrate.json +43 -0
- package/spec/schema.json +1 -1
- package/src/dopamine/core/RewardSystem.js +37 -13
- package/src/dopamine/core/store.js +2 -2
- package/src/dopamine/ui/RewardUI.js +43 -2
- package/src/dopamine/ui/dopamine.css +13 -12
- package/dist/DataService-GRTvq4BS.cjs +0 -1
- package/dist/host-rQMUJTOU.cjs +0 -37
package/dist/testing.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./host-MPzunSej.cjs"),t=require("./DataService-EJeOPnbo.cjs");let n=require("vitest"),r=require("node:fs"),i=require("node:path"),a=require("node:url");var o={xp_gained:{amount:10,reason:`test`,totalXP:10,leveledUp:!1},level_up:{oldLevel:1,newLevel:2,totalXP:50},achievement_unlocked:{id:`test`,name:`Test`,description:`Test`,icon:``,xp:5},personal_best:{activity:`test`,score:10},streak_updated:{current:1,longest:1},player_reset:{},save_failed:{error:Error(`save failed`)},load_failed:{reason:`corrupt`}},s=[`confetti`,`sparkle`,`fire`,`stars`,`coins`],c=[`xp`,`level_up`,`achievement`,`personal_best`,`click`,`error`],l=[``,`nope`,`__proto__`,`constructor`,`toString`,`hasOwnProperty`,void 0,null,42,{}],u=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/,d=e=>{throw Error(e)},f=(e,t)=>{e||d(t)};function p(e){if(typeof e==`object`&&e)return{clock:e,move:()=>d(`this clock is not a test clock, it cannot advance`)};let n=e===void 0?`2026-01-15T09:00:00`:e;typeof n==`string`&&u.test(n)||d(`clock must be YYYY-MM-DDTHH:MM:SS local time`);let r=new Date(n).getTime();return{clock:{now:()=>r,localDate:(e=r)=>t.s.localDate(e)},move:e=>{r=e(r)}}}function m(n={}){let{clock:r,storage:i,parts:a={},...o}=n||{},{clock:s,move:c}=p(r),l=[],f=[],m=[],h=[],g=[],_=new Set,v=[],y={ui:()=>({root:null,hud:e=>{m.push(e)},popup:e=>{l.push(e)},text:e=>{f.push(e)},destroy(){}}),particles:()=>({burst:(e,t,n)=>{h.push({kind:e,at:t,opts:n})},destroy(){}}),sound:()=>({play:e=>{g.push(e)},register(e){return _.add(e),()=>{_.delete(e)}},destroy(){}}),haptics:()=>({tap:()=>{v.push(`tap`)},double:()=>{v.push(`double`)},setEnabled(){},destroy(){}})},b={};for(let e of Object.keys(y))b[e]=Object.prototype.hasOwnProperty.call(a,e)?a[e]:y[e]();let x=e.n({...o,...b,storage:i||t.n(),clock:s,log:{warn:()=>{},error:()=>{},...o.log||{}}}),S=[],C=x.progress.emit;return x.progress.emit=function(e,t){return S.push({event:e,data:t}),C.call(this,e,t)},{host:x,progress:x.progress,parts:x.parts,ready:x.ready,use:x.use,dispose:()=>{x.dispose(),x.progress.emit=C},clock:s,popups:l,texts:f,huds:m,bursts:h,sounds:g,soundKeys:_,haptics:v,events:{log:S,on:(e,t)=>x.progress.on(e,t),off:(e,t)=>x.progress.off(e,t),emit:(e,t)=>x.progress.emit(e,t)},advance:e=>c(t=>t+e),advanceDays(e){c(t=>{let n=new Date(t);return n.setDate(n.getDate()+e),n.getTime()})},setClock(e){u.test(e)||d(`clock must be YYYY-MM-DDTHH:MM:SS local time`),c(()=>new Date(e).getTime())}}}var h=async e=>{await e},g=()=>typeof document>`u`?null:document.body.innerHTML,_=()=>m().parts,v=e=>[[`draws every burst kind without throwing`,async()=>{let t=e();try{for(let e of s)t.burst(e),t.burst(e,{x:10,y:20}),t.burst(e,{x:10,y:20},{count:3,color:`#fff`})}finally{t.destroy()}}],[`treats an unknown kind as a no-op`,async()=>{let t=e();try{for(let e of l)t.burst(e,{x:1,y:1})}finally{t.destroy()}}],[`has destroy`,async()=>{let t=e();f(typeof t.destroy==`function`,`a particle part needs destroy()`),t.destroy()}]],y=e=>[[`plays every preset key without throwing`,async()=>{let t=e();try{for(let e of c)await h(t.play(e))}finally{t.destroy()}}],[`treats an unknown key as a no-op`,async()=>{let t=e();try{for(let e of l)await h(t.play(e))}finally{t.destroy()}}],[`stops a registered key after its remover runs`,async()=>{let t=e();try{if(typeof t.register!=`function`)return;let e=0,n=t.register(`conformance_key`,()=>{e+=1});f(typeof n==`function`,`register() must return a remover`),n(),await h(t.play(`conformance_key`)),f(e===0,`a removed key still played`)}finally{t.destroy()}}]],b=e=>[[`draws the hud`,async()=>{let t=e(_());try{t.hud({xp:10,level:1,progress:.2,streak:0,next:50}),t.hud({xp:0,level:1,streak:3})}finally{t.destroy()}}],[`shows every popup kind and tier`,async()=>{let t=e(_());try{for(let e of[`achievement`,`level`,`notice`,`custom`])for(let n of[void 0,`common`,`rare`,`legendary`])t.popup({kind:e,title:`T`,body:`B`,icon:`I`,meta:`M`,tier:n})}finally{t.destroy()}}],[`ignores a popup it cannot read`,async()=>{let t=e(_());try{for(let e of[void 0,null,42,`text`,{},{kind:`__proto__`}])t.popup(e)}finally{t.destroy()}}],[`floats text`,async()=>{let t=e(_());try{t.text({text:`hello`,x:5,y:5,color:`#fff`}),t.text({text:`hello`})}finally{t.destroy()}}],[`has a root that is an element or null`,async()=>{let t=e(_());try{let e=t.root;f(e===null||typeof e==`object`&&typeof e.nodeType==`number`,`root must be an element or null`)}finally{t.destroy()}}],[`leaves no DOM behind after destroy`,async()=>{let t=g(),n=e(_());n.hud({xp:1,level:1,streak:1}),n.popup({kind:`achievement`,title:`T`}),n.text({text:`x`}),n.destroy(),f(g()===t,`the page changed after destroy()`)}]],x=`conformance_key`,S=e=>[[`returns null for a missing key`,async()=>{let t=e();for(let e of[x,`__proto__`,`constructor`,`toString`])f(await t.getItem(e)===null,`getItem(${e}) should be null`)}],[`keeps what setItem stores and overwrites it`,async()=>{let t=e();await t.setItem(x,`one`),f(await t.getItem(x)===`one`,`getItem should return the stored value`),await t.setItem(x,`two`),f(await t.getItem(x)===`two`,`setItem should overwrite`)}],[`keeps keys apart`,async()=>{let t=e();await t.setItem(`a`,`1`),await t.setItem(`b`,`2`),f(await t.getItem(`a`)===`1`&&await t.getItem(`b`)===`2`,`keys must not share a value`)}],[`forgets a key after removeItem`,async()=>{let t=e();await t.setItem(x,`one`),await t.removeItem(x),f(await t.getItem(x)===null,`removeItem should clear the key`),await t.removeItem(x)}]];function C(){let e=new Set,t={},n=[`setTimeout`,`setInterval`,`requestAnimationFrame`],r={setTimeout:`clearTimeout`,setInterval:`clearInterval`,requestAnimationFrame:`cancelAnimationFrame`};for(let i of n)t[i]=globalThis[i],t[r[i]]=globalThis[r[i]],typeof t[i]==`function`&&(globalThis[i]=(n,...r)=>{let a=i!==`setInterval`,o;return o=t[i]((...t)=>(a&&e.delete(o),n(...t)),...r),e.add(o),o},typeof t[r[i]]==`function`&&(globalThis[r[i]]=n=>(e.delete(n),t[r[i]](n))));return{live:()=>e.size,stop(){for(let n of e)t.clearTimeout?.(n),t.clearInterval?.(n),t.cancelAnimationFrame?.(n);for(let e of Object.keys(t))typeof t[e]==`function`&&(globalThis[e]=t[e])}}}var w=e=>{let t=0;for(let n of e.listeners.values())t+=n.size;return t};async function T(e,t){let n=C(),r=[],i=console.error;console.error=(...e)=>{r.push(e)};let a=m();try{await a.ready,await t(a,{watch:n,errors:r})}finally{console.error=i,a.dispose(),n.stop()}}var E={particles:v,sound:y,ui:b,storage:S,plugin:e=>[[`has a name, a version and the host api`,async()=>{let t=e();f(typeof t.name==`string`&&t.name!==``,`a plugin needs a name`),f(typeof t.version==`string`&&t.version!==``,`a plugin needs a version`),f(t.api===3,`a plugin needs api 3`),f(typeof t.install==`function`,`a plugin needs install()`)}],[`installs on a host and survives every core event`,async()=>{await T(e,async(t,{errors:n})=>{t.use(e()),await t.ready;for(let e of Object.keys(o))t.progress.emit(e,o[e]);await t.progress.addXP(5,`conformance`),f(n.length===0,`a listener threw: ${String(n[0]?.[1]??n[0]?.[0])}`)})}],[`leaves no listeners, timers or DOM behind once disposed`,async()=>{await T(e,async(t,{watch:n})=>{await t.ready;let r=w(t.progress),i=g(),a=n.live(),s=t.use(e());await t.progress.addXP(1,`conformance`);for(let e of Object.keys(o))t.progress.emit(e,o[e]);await t.ready,s(),f(w(t.progress)===r,`the plugin left listeners on the bus`),f(n.live()<=a,`the plugin left timers running`),f(g()===i,`the plugin left DOM in the page`)})}]]},D=e=>t=>{(0,n.describe)(`conformance.${e}`,()=>{for(let[r,i]of E[e](t))(0,n.it)(r,i)})},O={particles:D(`particles`),sound:D(`sound`),ui:D(`ui`),storage:D(`storage`),plugin:D(`plugin`)};async function k(e,t){Object.prototype.hasOwnProperty.call(E,e)||d(`unknown suite ${String(e)}`);let n=[];for(let[r,i]of E[e](t))try{await i()}catch{n.push(r)}return n}function A(){let e=typeof __dirname==`string`?__dirname:(0,i.dirname)((0,a.fileURLToPath)({}.url));for(let t of[`../spec`,`../../../spec`]){let n=(0,i.resolve)(e,t);if((0,r.existsSync)((0,i.join)(n,`VERSION`)))return n}return d(`spec/ was not found next to this package`)}function j(e){let t=e||A(),n=Number(/contract:\s*(\d+)/.exec((0,r.readFileSync)((0,i.join)(t,`VERSION`),`utf8`))?.[1]),a=JSON.parse((0,r.readFileSync)((0,i.join)(t,`schema.json`),`utf8`)),o={};for(let e of(0,r.readdirSync)((0,i.join)(t,`fixtures`)).sort()){if(!e.endsWith(`.json`))continue;let n=JSON.parse((0,r.readFileSync)((0,i.join)(t,`fixtures`,e),`utf8`));o[n.suite]=n}return{contract:n,schema:a,suites:o}}exports.conformance=O,exports.conformanceFailures=k,exports.createTestHost=m,exports.loadFixtures=j;
|
package/dist/testing.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { n as e
|
|
2
|
-
import { n } from "./
|
|
1
|
+
import { n as e } from "./host-DOvdGHZL.js";
|
|
2
|
+
import { n as t, s as n } from "./DataService-CydwGT_D.js";
|
|
3
3
|
import { describe as r, it as i } from "vitest";
|
|
4
4
|
import { existsSync as a, readFileSync as o, readdirSync as s } from "node:fs";
|
|
5
5
|
import { dirname as c, join as l, resolve as u } from "node:path";
|
|
6
6
|
import { fileURLToPath as d } from "node:url";
|
|
7
|
-
|
|
7
|
+
// src/testing.js
|
|
8
8
|
var f = {
|
|
9
9
|
xp_gained: {
|
|
10
10
|
amount: 10,
|
|
@@ -69,21 +69,21 @@ function y(e) {
|
|
|
69
69
|
clock: e,
|
|
70
70
|
move: () => _("this clock is not a test clock, it cannot advance")
|
|
71
71
|
};
|
|
72
|
-
let
|
|
73
|
-
|
|
74
|
-
let r = new Date(
|
|
72
|
+
let t = e === void 0 ? "2026-01-15T09:00:00" : e;
|
|
73
|
+
typeof t == "string" && g.test(t) || _("clock must be YYYY-MM-DDTHH:MM:SS local time");
|
|
74
|
+
let r = new Date(t).getTime();
|
|
75
75
|
return {
|
|
76
76
|
clock: {
|
|
77
77
|
now: () => r,
|
|
78
|
-
localDate: (e = r) =>
|
|
78
|
+
localDate: (e = r) => n.localDate(e)
|
|
79
79
|
},
|
|
80
80
|
move: (e) => {
|
|
81
81
|
r = e(r);
|
|
82
82
|
}
|
|
83
83
|
};
|
|
84
84
|
}
|
|
85
|
-
function b(
|
|
86
|
-
let { clock: r, storage: i, parts: a = {}, ...o } =
|
|
85
|
+
function b(n = {}) {
|
|
86
|
+
let { clock: r, storage: i, parts: a = {}, ...o } = n || {}, { clock: s, move: c } = y(r), l = [], u = [], d = [], f = [], p = [], m = /* @__PURE__ */ new Set(), h = [], v = {
|
|
87
87
|
ui: () => ({
|
|
88
88
|
root: null,
|
|
89
89
|
hud: (e) => {
|
|
@@ -130,10 +130,10 @@ function b(t = {}) {
|
|
|
130
130
|
})
|
|
131
131
|
}, b = {};
|
|
132
132
|
for (let e of Object.keys(v)) b[e] = Object.prototype.hasOwnProperty.call(a, e) ? a[e] : v[e]();
|
|
133
|
-
let x =
|
|
133
|
+
let x = e({
|
|
134
134
|
...o,
|
|
135
135
|
...b,
|
|
136
|
-
storage: i ||
|
|
136
|
+
storage: i || t(),
|
|
137
137
|
clock: s,
|
|
138
138
|
log: {
|
|
139
139
|
warn: () => {},
|
|
@@ -471,5 +471,4 @@ function L(e) {
|
|
|
471
471
|
suites: i
|
|
472
472
|
};
|
|
473
473
|
}
|
|
474
|
-
//#endregion
|
|
475
474
|
export { P as conformance, F as conformanceFailures, b as createTestHost, L as loadFixtures };
|
package/package.json
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dopaminejs",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.4.0",
|
|
4
4
|
"description": "Progression mechanics for web apps: XP, levels, achievements and timezone-correct daily streaks, with the particles and sound to make them land. Zero dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/dopamine.cjs",
|
|
7
7
|
"module": "./dist/dopamine.js",
|
|
8
|
+
"unpkg": "./dist/dopamine.global.js",
|
|
9
|
+
"jsdelivr": "./dist/dopamine.global.js",
|
|
8
10
|
"exports": {
|
|
9
11
|
".": {
|
|
10
12
|
"types": "./types/index.d.ts",
|
|
@@ -38,7 +40,7 @@
|
|
|
38
40
|
],
|
|
39
41
|
"scripts": {
|
|
40
42
|
"dev": "vite",
|
|
41
|
-
"build": "vite build",
|
|
43
|
+
"build": "vite build && vite build --config vite.config.iife.js",
|
|
42
44
|
"test": "vitest run",
|
|
43
45
|
"test:watch": "vitest",
|
|
44
46
|
"preview": "vite preview"
|
package/spec/README.md
CHANGED
|
@@ -147,7 +147,8 @@ Event names: `xp_gained`, `level_up`, `achievement_unlocked`, `personal_best`
|
|
|
147
147
|
(payload `{ activity, score }`), `streak_updated`, `player_reset` (empty payload), `save_failed` and
|
|
148
148
|
`load_failed`. `load_failed` is covered for a corrupt value and for a document
|
|
149
149
|
the core refuses (`reason` is `corrupt`, `unsupported_version` or
|
|
150
|
-
`too_many_devices`). A
|
|
150
|
+
`too_many_devices`). A saved value that is valid JSON but not an object counts as corrupt, and is kept
|
|
151
|
+
under `player_corrupt`. A read that fails in storage cannot be made by a fixture.
|
|
151
152
|
|
|
152
153
|
Payloads are frozen copies, and `snapshot()` is a frozen deep copy.
|
|
153
154
|
|
|
@@ -196,7 +197,7 @@ More than 20 devices across the per-device maps is refused with a
|
|
|
196
197
|
write: `addXP` and `record` leave the stored save alone and publish `load_failed`
|
|
197
198
|
with reason `too_many_devices`. A document with a `v` other than 3 is refused
|
|
198
199
|
with `unsupported_version`. A value that is not an object is `invalid_document`. Counters and sums stop at
|
|
199
|
-
`Number.MAX_SAFE_INTEGER`.
|
|
200
|
+
`Number.MAX_SAFE_INTEGER`. A negative or non-finite value in a map (`xpBy`, `sumsBy` and the rest) is dropped.
|
|
200
201
|
|
|
201
202
|
### From 2.x
|
|
202
203
|
|
package/spec/fixtures/merge.json
CHANGED
|
@@ -1734,6 +1734,45 @@
|
|
|
1734
1734
|
}
|
|
1735
1735
|
}
|
|
1736
1736
|
]
|
|
1737
|
+
},
|
|
1738
|
+
{
|
|
1739
|
+
"name": "a negative sum is dropped on validate",
|
|
1740
|
+
"clock": "2026-08-07T09:00:00",
|
|
1741
|
+
"device": "me",
|
|
1742
|
+
"note": "Sums only grow, like the other counters. A negative sum is invalid and dropped, so two huge negatives cannot add to a value that is not a finite number.",
|
|
1743
|
+
"steps": [
|
|
1744
|
+
{
|
|
1745
|
+
"op": "validate",
|
|
1746
|
+
"doc": {
|
|
1747
|
+
"v": 3,
|
|
1748
|
+
"sumsBy": {
|
|
1749
|
+
"g": {
|
|
1750
|
+
"kills": {
|
|
1751
|
+
"a": 5,
|
|
1752
|
+
"b": -1
|
|
1753
|
+
},
|
|
1754
|
+
"time": {
|
|
1755
|
+
"a": -1e+308,
|
|
1756
|
+
"b": -1e+308
|
|
1757
|
+
}
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
},
|
|
1761
|
+
"as": "v",
|
|
1762
|
+
"expect": {
|
|
1763
|
+
"returnsExact": {
|
|
1764
|
+
"sumsBy": {
|
|
1765
|
+
"g": {
|
|
1766
|
+
"kills": {
|
|
1767
|
+
"a": 5
|
|
1768
|
+
},
|
|
1769
|
+
"time": {}
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
]
|
|
1737
1776
|
}
|
|
1738
1777
|
]
|
|
1739
1778
|
}
|
|
@@ -952,6 +952,49 @@
|
|
|
952
952
|
},
|
|
953
953
|
"events": []
|
|
954
954
|
}
|
|
955
|
+
},
|
|
956
|
+
{
|
|
957
|
+
"name": "a saved player that is an array is kept as corrupt",
|
|
958
|
+
"clock": "2026-08-07T09:00:00",
|
|
959
|
+
"savedJson": [
|
|
960
|
+
1,
|
|
961
|
+
2
|
|
962
|
+
],
|
|
963
|
+
"note": "Valid JSON that is not an object is treated like unparseable data. The core keeps it under player_corrupt and starts a new player.",
|
|
964
|
+
"afterInit": {
|
|
965
|
+
"player": {
|
|
966
|
+
"name": "Player",
|
|
967
|
+
"xp": 0,
|
|
968
|
+
"level": 1
|
|
969
|
+
},
|
|
970
|
+
"events": [
|
|
971
|
+
{
|
|
972
|
+
"event": "load_failed",
|
|
973
|
+
"reason": "corrupt",
|
|
974
|
+
"backedUp": true
|
|
975
|
+
}
|
|
976
|
+
]
|
|
977
|
+
}
|
|
978
|
+
},
|
|
979
|
+
{
|
|
980
|
+
"name": "a saved player that is a number is kept as corrupt",
|
|
981
|
+
"clock": "2026-08-07T09:00:00",
|
|
982
|
+
"savedJson": 5,
|
|
983
|
+
"note": "Valid JSON that is not an object is treated like unparseable data. The core keeps it under player_corrupt and starts a new player.",
|
|
984
|
+
"afterInit": {
|
|
985
|
+
"player": {
|
|
986
|
+
"name": "Player",
|
|
987
|
+
"xp": 0,
|
|
988
|
+
"level": 1
|
|
989
|
+
},
|
|
990
|
+
"events": [
|
|
991
|
+
{
|
|
992
|
+
"event": "load_failed",
|
|
993
|
+
"reason": "corrupt",
|
|
994
|
+
"backedUp": true
|
|
995
|
+
}
|
|
996
|
+
]
|
|
997
|
+
}
|
|
955
998
|
}
|
|
956
999
|
]
|
|
957
1000
|
}
|
package/spec/schema.json
CHANGED
|
@@ -60,6 +60,10 @@ export class RewardSystem extends EventEmitter {
|
|
|
60
60
|
this._deviceSaved = false;
|
|
61
61
|
this._middleware = new Middleware();
|
|
62
62
|
|
|
63
|
+
// Ids whose unlock is waiting on a hook, so a second call for the
|
|
64
|
+
// same id does not unlock it again.
|
|
65
|
+
this._unlocking = new Set();
|
|
66
|
+
|
|
63
67
|
// Write batching: one record is one write.
|
|
64
68
|
this._batchDepth = 0;
|
|
65
69
|
this._pendingSave = false;
|
|
@@ -133,24 +137,34 @@ export class RewardSystem extends EventEmitter {
|
|
|
133
137
|
this._loadFailed = true;
|
|
134
138
|
try {
|
|
135
139
|
const saved = await this.dataService.load('player', null, { strict: true });
|
|
140
|
+
if (saved !== null && !isRecord(saved)) {
|
|
141
|
+
// Valid JSON that is not a player: keep it like unreadable data.
|
|
142
|
+
return await this._keepCorrupt(saved);
|
|
143
|
+
}
|
|
136
144
|
this._loadFailed = false;
|
|
137
145
|
this._readFailed = false;
|
|
138
146
|
return saved;
|
|
139
147
|
} catch (error) {
|
|
140
|
-
if (error?.code === 'DOPAMINE_CORRUPT')
|
|
141
|
-
// Keep the unreadable value instead of losing it on the next save.
|
|
142
|
-
const kept = await this.dataService.save('player_corrupt', error.raw);
|
|
143
|
-
if (kept) this._loadFailed = false;
|
|
144
|
-
this._readFailed = !kept;
|
|
145
|
-
this._publish('load_failed', { key: 'player', reason: 'corrupt', backedUp: kept });
|
|
146
|
-
return null;
|
|
147
|
-
}
|
|
148
|
+
if (error?.code === 'DOPAMINE_CORRUPT') return this._keepCorrupt(error.raw);
|
|
148
149
|
this._readFailed = true;
|
|
149
150
|
this._publish('load_failed', { key: 'player', reason: 'read', error });
|
|
150
151
|
return null;
|
|
151
152
|
}
|
|
152
153
|
}
|
|
153
154
|
|
|
155
|
+
/**
|
|
156
|
+
* Keep an unreadable value instead of losing it on the next save.
|
|
157
|
+
* @private
|
|
158
|
+
*/
|
|
159
|
+
async _keepCorrupt(raw) {
|
|
160
|
+
this._loadFailed = true;
|
|
161
|
+
const kept = await this.dataService.save('player_corrupt', raw);
|
|
162
|
+
if (kept) this._loadFailed = false;
|
|
163
|
+
this._readFailed = !kept;
|
|
164
|
+
this._publish('load_failed', { key: 'player', reason: 'corrupt', backedUp: kept });
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
|
|
154
168
|
/**
|
|
155
169
|
* Saved state is untrusted: it goes through validate. A document from a
|
|
156
170
|
* newer version or with too many devices is left alone in storage.
|
|
@@ -624,17 +638,26 @@ export class RewardSystem extends EventEmitter {
|
|
|
624
638
|
|
|
625
639
|
// Already unlocked: paying the XP again would let one call farm levels.
|
|
626
640
|
if (hasOwn(this._doc.achievements, achievementId)) return false;
|
|
641
|
+
if (this._unlocking.has(achievementId)) return false;
|
|
627
642
|
|
|
628
643
|
const achievement = this.achievements[achievementId];
|
|
629
644
|
if (!achievement) return false;
|
|
630
645
|
|
|
631
646
|
const { [achievementId]: reward } = rewardsOf(this.achievements);
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
647
|
+
this._unlocking.add(achievementId);
|
|
648
|
+
let context;
|
|
649
|
+
try {
|
|
650
|
+
context = await this._middleware.before(
|
|
651
|
+
'beforeUnlock',
|
|
652
|
+
{ id: achievementId, reward },
|
|
653
|
+
(next) => Number.isFinite(next.reward) && next.reward >= 0
|
|
654
|
+
);
|
|
655
|
+
} finally {
|
|
656
|
+
this._unlocking.delete(achievementId);
|
|
657
|
+
}
|
|
637
658
|
if (context === false) return false;
|
|
659
|
+
// A reset or an import during the hook may have unlocked it already.
|
|
660
|
+
if (hasOwn(this._doc.achievements, achievementId)) return false;
|
|
638
661
|
|
|
639
662
|
const doc = this._doc;
|
|
640
663
|
const oldLevel = levelOf(doc);
|
|
@@ -674,6 +697,7 @@ export class RewardSystem extends EventEmitter {
|
|
|
674
697
|
* Mark achievements as seen
|
|
675
698
|
*/
|
|
676
699
|
async markAchievementsSeen(achievementIds) {
|
|
700
|
+
this._requirePlayer();
|
|
677
701
|
for (const id of achievementIds) {
|
|
678
702
|
if (hasOwn(this._doc.achievements, id)) {
|
|
679
703
|
this._doc.achievements[id].seen = true;
|
|
@@ -110,7 +110,7 @@ function nestedSums(source) {
|
|
|
110
110
|
const map = {};
|
|
111
111
|
if (!isRecord(source)) return map;
|
|
112
112
|
for (const activity of Object.keys(source)) {
|
|
113
|
-
if (isSafeKey(activity)) map[activity] = pickNested(source[activity],
|
|
113
|
+
if (isSafeKey(activity)) map[activity] = pickNested(source[activity], isAmount);
|
|
114
114
|
}
|
|
115
115
|
return map;
|
|
116
116
|
}
|
|
@@ -148,7 +148,7 @@ function read2(input, now, rewards, today) {
|
|
|
148
148
|
doc.best[activity] = isAmount(entry.highScore) ? cap(entry.highScore) : 0;
|
|
149
149
|
doc.sumsBy[activity] = {};
|
|
150
150
|
for (const key of Object.keys(entry)) {
|
|
151
|
-
if (isSafeKey(key) && key !== 'totalPlays' && key !== 'highScore' &&
|
|
151
|
+
if (isSafeKey(key) && key !== 'totalPlays' && key !== 'highScore' && isAmount(entry[key])) {
|
|
152
152
|
doc.sumsBy[activity][key] = { [LEGACY]: cap(entry[key]) };
|
|
153
153
|
}
|
|
154
154
|
}
|
|
@@ -187,6 +187,11 @@ export class RewardUI {
|
|
|
187
187
|
this._timers = new Set();
|
|
188
188
|
this._detached = [];
|
|
189
189
|
|
|
190
|
+
// Achievement and custom cards share one spot, so they show one at a
|
|
191
|
+
// time. Each entry is the arguments of a _card call.
|
|
192
|
+
this._cardQueue = [];
|
|
193
|
+
this._cardActive = false;
|
|
194
|
+
|
|
190
195
|
this._build();
|
|
191
196
|
}
|
|
192
197
|
|
|
@@ -411,8 +416,38 @@ export class RewardUI {
|
|
|
411
416
|
}
|
|
412
417
|
}
|
|
413
418
|
|
|
414
|
-
/**
|
|
419
|
+
/**
|
|
420
|
+
* Queue a card. Two unlocks in the same moment would otherwise mount at the
|
|
421
|
+
* same fixed spot and hide each other.
|
|
422
|
+
* @private
|
|
423
|
+
*/
|
|
415
424
|
_card(popup, withHeading) {
|
|
425
|
+
// Copy the fields now, so a caller that reuses its object cannot change
|
|
426
|
+
// a card that is still waiting.
|
|
427
|
+
const { title, body, meta, icon } = popup;
|
|
428
|
+
this._cardQueue.push([{ title, body, meta, icon }, withHeading]);
|
|
429
|
+
this._nextCard();
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** @private */
|
|
433
|
+
_nextCard() {
|
|
434
|
+
if (this._cardActive) return;
|
|
435
|
+
const next = this._cardQueue.shift();
|
|
436
|
+
if (!next) return;
|
|
437
|
+
this._cardActive = true;
|
|
438
|
+
try {
|
|
439
|
+
this._showCard(next[0], next[1]);
|
|
440
|
+
} catch (error) {
|
|
441
|
+
// A card that fails to build never schedules its removal, so the
|
|
442
|
+
// flag would stay set and every later card would be lost.
|
|
443
|
+
this._cardActive = false;
|
|
444
|
+
this._nextCard();
|
|
445
|
+
throw error;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** @private */
|
|
450
|
+
_showCard(popup, withHeading) {
|
|
416
451
|
const card = document.createElement('div');
|
|
417
452
|
card.className = 'achievement-popup';
|
|
418
453
|
card.innerHTML = `
|
|
@@ -445,7 +480,11 @@ export class RewardUI {
|
|
|
445
480
|
|
|
446
481
|
this._defer(() => {
|
|
447
482
|
card.style.animation = 'slideOut 0.3s ease-in forwards';
|
|
448
|
-
this._defer(() =>
|
|
483
|
+
this._defer(() => {
|
|
484
|
+
this._remove(card);
|
|
485
|
+
this._cardActive = false;
|
|
486
|
+
this._nextCard();
|
|
487
|
+
}, 300);
|
|
449
488
|
}, 4000);
|
|
450
489
|
}
|
|
451
490
|
|
|
@@ -547,6 +586,8 @@ export class RewardUI {
|
|
|
547
586
|
clearTimeout(id);
|
|
548
587
|
}
|
|
549
588
|
this._timers.clear();
|
|
589
|
+
this._cardQueue = [];
|
|
590
|
+
this._cardActive = false;
|
|
550
591
|
|
|
551
592
|
for (const el of this._detached) {
|
|
552
593
|
el.remove();
|
|
@@ -112,15 +112,16 @@
|
|
|
112
112
|
|
|
113
113
|
.achievement-popup {
|
|
114
114
|
position: fixed;
|
|
115
|
-
top: 80px;
|
|
116
|
-
right: 20px;
|
|
117
|
-
|
|
118
|
-
|
|
115
|
+
top: calc(var(--dopamine-toast-top, 80px) + env(safe-area-inset-top, 0px));
|
|
116
|
+
right: var(--dopamine-toast-right, 20px);
|
|
117
|
+
left: var(--dopamine-toast-left, auto);
|
|
118
|
+
background: var(--dopamine-toast-bg, linear-gradient(135deg, #667eea 0%, #764ba2 100%));
|
|
119
|
+
border-radius: var(--dopamine-toast-radius, 16px);
|
|
119
120
|
padding: 16px;
|
|
120
|
-
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
|
|
121
|
+
box-shadow: var(--dopamine-toast-shadow, 0 8px 32px rgba(0, 0, 0, 0.4));
|
|
121
122
|
animation: slideIn 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
|
|
122
123
|
z-index: 10000;
|
|
123
|
-
max-width: 320px;
|
|
124
|
+
max-width: var(--dopamine-toast-max-width, 320px);
|
|
124
125
|
overflow: hidden;
|
|
125
126
|
}
|
|
126
127
|
|
|
@@ -153,7 +154,7 @@
|
|
|
153
154
|
.achievement-title {
|
|
154
155
|
font-size: 12px;
|
|
155
156
|
font-weight: 600;
|
|
156
|
-
color: rgba(255, 255, 255, 0.9);
|
|
157
|
+
color: var(--dopamine-toast-muted, rgba(255, 255, 255, 0.9));
|
|
157
158
|
text-transform: uppercase;
|
|
158
159
|
letter-spacing: 0.5px;
|
|
159
160
|
}
|
|
@@ -161,13 +162,13 @@
|
|
|
161
162
|
.achievement-name {
|
|
162
163
|
font-size: 18px;
|
|
163
164
|
font-weight: 800;
|
|
164
|
-
color: white;
|
|
165
|
+
color: var(--dopamine-toast-text, white);
|
|
165
166
|
margin: 2px 0;
|
|
166
167
|
}
|
|
167
168
|
|
|
168
169
|
.achievement-desc {
|
|
169
170
|
font-size: 13px;
|
|
170
|
-
color: rgba(255, 255, 255, 0.8);
|
|
171
|
+
color: var(--dopamine-toast-muted, rgba(255, 255, 255, 0.8));
|
|
171
172
|
margin-bottom: 4px;
|
|
172
173
|
}
|
|
173
174
|
|
|
@@ -178,7 +179,7 @@
|
|
|
178
179
|
border-radius: 8px;
|
|
179
180
|
font-size: 12px;
|
|
180
181
|
font-weight: 700;
|
|
181
|
-
color: #ffd700;
|
|
182
|
+
color: var(--dopamine-toast-accent, #ffd700);
|
|
182
183
|
}
|
|
183
184
|
|
|
184
185
|
/* ==================== LEVEL UP OVERLAY ==================== */
|
|
@@ -367,8 +368,8 @@
|
|
|
367
368
|
}
|
|
368
369
|
|
|
369
370
|
.achievement-popup {
|
|
370
|
-
right: 12px;
|
|
371
|
-
max-width: calc(100% - 24px);
|
|
371
|
+
right: var(--dopamine-toast-right, 12px);
|
|
372
|
+
max-width: min(var(--dopamine-toast-max-width, 320px), calc(100% - 24px));
|
|
372
373
|
}
|
|
373
374
|
|
|
374
375
|
.level-up-number {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var e=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){this.listeners.has(e)&&this.listeners.get(e).delete(t)}emit(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(n=>{try{n(t)}catch(t){console.error(`Error in listener for event '${e}':`,t)}})}clear(){this.listeners.clear()}},t=class extends Error{constructor(e,t){super(t||e),this.name=`DopamineError`,this.code=e}},n=(e,t=2)=>String(e).padStart(t,`0`),r={now:()=>Date.now(),localDate(e=Date.now()){let t=new Date(e);return`${n(t.getFullYear(),4)}-${n(t.getMonth()+1)}-${n(t.getDate())}`}},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=()=>({first_game:{name:`First Steps`,description:`Play your first game`,icon:`🎮`,xp:50,check:e=>e.totalGamesPlayed>=1},level_5:{name:`Rising Star`,description:`Reach level 5`,icon:`⭐`,xp:100,check:e=>e.level>=5},level_10:{name:`Expert Player`,description:`Reach level 10`,icon:`🏆`,xp:250,check:e=>e.level>=10},streak_3:{name:`Dedicated`,description:`Play 3 days in a row`,icon:`🔥`,xp:100,check:e=>e.streak.current>=3},streak_7:{name:`Unstoppable`,description:`Play 7 days in a row`,icon:`💥`,xp:300,check:e=>e.streak.current>=7}}),s={first_game:50,level_5:100,level_10:250,streak_3:100,streak_7:300},c=e=>{let t={};for(let n of Object.keys(e))t[n]=Number.isFinite(e[n]?.xp)&&e[n].xp>0?e[n].xp:0;return t},l=864e5,u=/^\d{4}-\d{2}-\d{2}$/,d=e=>{let t=new Date(0);return t.setUTCFullYear(+e.slice(0,4),e.slice(5,7)-1,+e.slice(8)),t.getTime()/l},f=e=>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);function h(e,t){let n=[...new Set(e)].sort();if(!t)return n;let r=d(t)-399,i=d(t)+1;return n.filter(e=>d(e)>=r&&d(e)<=i)}function g(e,t){let n=new Set(e),r=n.has(t)?t:m(t,-1),i=0;for(;n.has(r);)i++,r=m(r,-1);return i}function _(e){let t=0,n=0,r=NaN;for(let i of[...e].sort()){let e=d(i);n=e===r+1?n+1:1,r=e,n>t&&(t=n)}return t}var v=(e,t)=>e.reduce((e,n)=>n<=t&&(!e||n>e)?n:e,void 0),y=`legacy`,b=new Set([`__proto__`,`constructor`,`prototype`]),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)=>({v:3,name:`Player`,createdAt:e,lastPlayedAt:e,level:1,longest:0,playDates:[],xpBy:{},xpSpentBy:{},gamesBy:{},playsBy:{},best:{},sumsBy:{},achievements:{}});function j(e,t){let n={};if(!C(e))return n;for(let r of Object.keys(e))x(r)&&t(e[r])&&(n[r]=D(e[r]));return n}function M(e,t){let n={};if(!C(e))return n;for(let r of Object.keys(e))x(r)&&(n[r]=j(e[r],t));return n}function N(e,t){let n={};if(!C(e))return n;for(let r of Object.keys(e)){let i=e[r];x(r)&&C(i)&&(n[r]={unlockedAt:E(i.unlockedAt)?i.unlockedAt:t,seen:i.seen===!0,reward:T(i.reward)?D(i.reward):0})}return n}function P(e){let t=e.sumsBy,n=new Set([...Object.keys(e.playsBy),...Object.keys(e.best),...Object.keys(t)]);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]={});return e}function F(e,t,n){return P({v:3,name:typeof e.name==`string`?e.name:`Player`,createdAt:E(e.createdAt)?e.createdAt:t,lastPlayedAt:E(e.lastPlayedAt)?e.lastPlayedAt:t,level:O(e.level,1,1),longest:O(e.longest,0),playDates:h(Array.isArray(e.playDates)?e.playDates.filter(p):[],n),xpBy:j(e.xpBy,T),xpSpentBy:j(e.xpSpentBy,T),gamesBy:j(e.gamesBy,w),playsBy:M(e.playsBy,w),best:j(e.best,T),sumsBy:I(e.sumsBy),achievements:N(e.achievements,t)})}function I(e){let t={};if(!C(e))return t;for(let n of Object.keys(e))x(n)&&(t[n]=M(e[n],E));return t}function L(e,t,n,r){let a=A(t);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);let o=0;for(let e of Object.keys(a.achievements)){let t=S(n,e)&&T(n[e])?D(n[e]):0;a.achievements[e].reward=t,o+=t}let s=T(e.xp)?D(e.xp):0,c=Math.max(0,s-o);c>0&&(a.xpBy[y]=c),a.level=Math.max(i(s),O(e.level,1,1));let l=O(e.totalGamesPlayed,0);if(l>0&&(a.gamesBy[y]=l),C(e.stats))for(let t of Object.keys(e.stats)){let n=e.stats[t];if(!x(t)||!C(n))continue;let r=O(n.totalPlays,0);a.playsBy[t]=r>0?{[y]:r}:{},a.best[t]=T(n.highScore)?D(n.highScore):0,a.sumsBy[t]={};for(let e of Object.keys(n))x(e)&&e!==`totalPlays`&&e!==`highScore`&&E(n[e])&&(a.sumsBy[t][e]={[y]:D(n[e])})}let u=C(e.streak)?e.streak:{},d=O(u.current,1,1);if(a.longest=Math.max(d,O(u.longest,0)),p(u.lastPlayDate)){for(let e=0;e<Math.min(d,400);e++)a.playDates.push(m(u.lastPlayDate,-e));a.playDates=h(a.playDates,r)}else a.longest=O(u.longest,0);return P(a)}function R(e){let t=new Set([...Object.keys(e.xpBy),...Object.keys(e.xpSpentBy),...Object.keys(e.gamesBy)]);for(let n of Object.keys(e.playsBy))for(let r of Object.keys(e.playsBy[n]))t.add(r);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);return t}function z(e){if(R(e).size>20)throw new t(`too_many_devices`,`[DopamineJS] a save holds at most 20 devices`)}function B(e,n={}){if(!C(e))throw new t(`invalid_document`,`[DopamineJS] a save must be an object`);if(e.v!==void 0&&e.v!==3)throw new t(`unsupported_version`,`[DopamineJS] save version ${String(e.v)} is not 3`);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);return z(a),a}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)));function U(e,t){let n={};for(let t of Object.keys(e.playsBy)){let r={plays:k(e.playsBy[t]),best:e.best[t]};for(let n of Object.keys(e.sumsBy[t]))n!==`plays`&&n!==`best`&&(r[n]=k(e.sumsBy[t][n]));n[t]=r}let r={};for(let t of Object.keys(e.achievements))r[t]={...e.achievements[t]};let i={current:g(e.playDates,t),longest:Math.max(e.longest,_(e.playDates))},a=v(e.playDates,t);return a&&(i.lastPlayDate=a),{name:e.name,xp:V(e),level:H(e),totalGamesPlayed:k(e.gamesBy),createdAt:e.createdAt,lastPlayedAt:e.lastPlayedAt,streak:i,achievements:r,stats:n}}var W=e=>JSON.parse(JSON.stringify(e));function G(e){if(typeof e==`object`&&e&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))G(e[t])}return e}var K=[`beforeXP`,`afterXP`,`beforeRecord`,`afterRecord`,`beforeUnlock`,`afterUnlock`],q=class{constructor(){this._list=[]}use(e){if(!C(e)||!K.some(t=>typeof e[t]==`function`))throw TypeError(`[DopamineJS] use expects an object with one of: ${K.join(`, `)}`);return this._list.push(e),()=>{let t=this._list.indexOf(e);t>=0&&this._list.splice(t,1)}}async before(e,t,n=()=>!0){for(let r of[...this._list]){if(typeof r[e]!=`function`)continue;let i;try{i=await r[e](Object.freeze({...t}))}catch(t){console.error(`[DopamineJS] ${e} hook threw:`,t);continue}if(i===!1)return!1;if(!C(i))continue;let a={...t};for(let e of Object.keys(t))Object.prototype.hasOwnProperty.call(i,e)&&(a[e]=i[e]);n(a)&&(t=a)}return t}async after(e,t){for(let n of[...this._list])if(typeof n[e]==`function`)try{await n[e](Object.freeze({...t}))}catch(t){console.error(`[DopamineJS] ${e} hook threw:`,t)}}};function J(e,t,n){let r={};for(let i of new Set([...Object.keys(e),...Object.keys(t)])){let a=S(e,i)?e[i]:void 0,o=S(t,i)?t[i]:void 0;r[i]=n>0?J(a||{},o||{},n-1):a===void 0?o:o===void 0?a:Math.max(a,o)}return r}function ee(e,t){let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let i=S(e,r)?e[r]:void 0,a=S(t,r)?t[r]:void 0;if(!i||!a){n[r]={...i||a};continue}let o=i.unlockedAt<a.unlockedAt||i.unlockedAt===a.unlockedAt&&i.reward>=a.reward?i:a;n[r]={unlockedAt:o.unlockedAt,seen:i.seen||a.seen,reward:o.reward}}return n}var te=(e,t)=>e>0&&t>0?Math.min(e,t):Math.max(e,t);function Y(e,t,n){let r=B(e,n),i=B(t,n),a={v:3,name:(r.lastPlayedAt===i.lastPlayedAt?r.name>=i.name?r:i:r.lastPlayedAt>i.lastPlayedAt?r:i).name,createdAt:te(r.createdAt,i.createdAt),lastPlayedAt:Math.max(r.lastPlayedAt,i.lastPlayedAt),level:Math.max(r.level,i.level),longest:Math.max(r.longest,i.longest),playDates:h([...r.playDates,...i.playDates],p(n?.today)?n.today:void 0),xpBy:J(r.xpBy,i.xpBy,0),xpSpentBy:J(r.xpSpentBy,i.xpSpentBy,0),gamesBy:J(r.gamesBy,i.gamesBy,0),playsBy:J(r.playsBy,i.playsBy,1),best:J(r.best,i.best,0),sumsBy:J(r.sumsBy,i.sumsBy,2),achievements:ee(r.achievements,i.achievements)};return z(a),a}var X=`device`,Z=()=>{let e=new Uint8Array(8),t=globalThis.crypto;if(typeof t?.getRandomValues==`function`)t.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)},ne=e=>x(e)&&e!==`legacy`,re=class extends e{constructor(e,t={}){super(),this.dataService=e,this.clock=t.clock&&typeof t.clock.now==`function`&&typeof t.clock.localDate==`function`?t.clock:r,this.achievements={...t.builtinAchievements===!1?{}:o(),...t.achievements||{}},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}get loadFailed(){return this._readFailed}_publish(e,t){let n=Object.freeze({...t});this.emit(e,n)}async _batch(e){this._batchDepth++;try{return await e()}finally{this._batchDepth--,this._batchDepth===0&&this._pendingSave&&(this._pendingSave=!1,await this._write())}}_options(){return{now:this.clock.now(),today:this.clock.localDate(),rewards:{...s,...c(this.achievements)}}}async init(){let e=await this._readSaved();return this._loadFailed&&this._doc||(this._doc=this._load(e)),await this._readDevice(),await this.save(),this.snapshot()}async _readSaved(){this._loadFailed=!0;try{let e=await this.dataService.load(`player`,null,{strict:!0});return this._loadFailed=!1,this._readFailed=!1,e}catch(e){if(e?.code===`DOPAMINE_CORRUPT`){let t=await this.dataService.save(`player_corrupt`,e.raw);return t&&(this._loadFailed=!1),this._readFailed=!t,this._publish(`load_failed`,{key:`player`,reason:`corrupt`,backedUp:t}),null}return this._readFailed=!0,this._publish(`load_failed`,{key:`player`,reason:`read`,error:e}),null}}_load(e){if(!C(e))return A(this.clock.now());try{return B(e,this._options())}catch(e){if(!(e instanceof t))throw e;return this._loadFailed=!0,this._readFailed=!0,this._publish(`load_failed`,{key:`player`,reason:e.code,error:e}),A(this.clock.now())}}async _readDevice(){if(this._deviceId)return;let e=null;try{e=await this.dataService.load(X,null,{strict:!0})}catch{this._deviceId=Z();return}ne(e)?(this._deviceId=e,this._deviceSaved=!0):this._deviceId=Z()}_hasSlot(){let e=R(this._doc);return e.has(this._deviceId)||e.size<20?!0:(this._publish(`load_failed`,{key:`player`,reason:`too_many_devices`}),!1)}_requirePlayer(){if(!this._doc)throw Error(`[DopamineJS] RewardSystem.init() must be awaited before use`)}snapshot(){return this._requirePlayer(),G(U(this._doc,this.clock.localDate()))}export(){return this._requirePlayer(),W(this._doc)}async import(e,{silent:t=!1}={}){this._requirePlayer();let n=this.snapshot(),r=B(e,this._options()),i=Y(this._doc,r,this._options());i.level=H(i),this._doc=i;let a=this.snapshot();if(await this.save(),t)return a;let o=a.xp-n.xp,s=a.level>n.level;o>0&&this._publish(`xp_gained`,{amount:o,reason:`import`,leveledUp:s,newLevel:a.level,total:a.xp}),s&&this._publish(`level_up`,{oldLevel:n.level,newLevel:a.level,totalXP:a.xp});for(let e of Object.keys(a.achievements))!S(n.achievements,e)&&S(this.achievements,e)&&this._publish(`achievement_unlocked`,{...this.achievements[e],id:e});return a}async reset(e){let t=e?.overwrite;if(e!==void 0&&(typeof e!=`object`||!e||Array.isArray(e))||t!==void 0&&typeof t!=`boolean`)throw TypeError(`[DopamineJS] reset expects { overwrite?: boolean }`);return this._requirePlayer(),t===!1&&this._readFailed?(this._doc=A(this.clock.now()),this._publish(`player_reset`,{}),this.snapshot()):(await this._batch(async()=>{this._doc=A(this.clock.now()),this._loadFailed=!1,this._readFailed=!1,await this.save()}),this._publish(`player_reset`,{}),this.snapshot())}use(e){return this._middleware.use(e)}defineAchievement(e,t){if(!x(e))throw TypeError(`[DopamineJS] defineAchievement expects an id, received ${String(e)}`);if(!C(t)||typeof t.check!=`function`)throw TypeError(`[DopamineJS] defineAchievement expects a definition with a check function`);let n=S(this.achievements,e)?this.achievements[e]:void 0;return this.achievements[e]=t,()=>{this.achievements[e]===t&&(n?this.achievements[e]=n:delete this.achievements[e])}}async save(){if(this._doc){if(this._batchDepth>0){this._pendingSave=!0;return}await this._write()}}async _write(){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`}))}async addXP(e,t=``){if(!Number.isFinite(e))throw TypeError(`[DopamineJS] addXP expects a finite number, received ${e}`);if(this._requirePlayer(),!this._hasSlot())return{leveledUp:!1,newLevel:H(this._doc),xpGained:0};let n=await this._middleware.before(`beforeXP`,{amount:e,reason:t},e=>Number.isFinite(e.amount));if(n===!1)return{leveledUp:!1,newLevel:H(this._doc),xpGained:0};this.streakDays===`any`&&n.amount>0&&this._markDay();let r=await this._applyXP(n.amount,n.reason,(e,t)=>{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)});return await this._middleware.after(`afterXP`,{amount:r.xpGained,reason:n.reason,total:V(this._doc),level:r.newLevel}),r}async _applyXP(e,t,n){let r=this._doc,i=H(r);return e=Math.max(e,-V(r)),n(r,e),this._announceXP(i,e,t)}async _announceXP(e,t,n){let r=this._doc,a=V(r),o=Math.max(e,i(a)),s=o>e;return o>r.level&&(r.level=o),await this.save(),this._publish(`xp_gained`,{amount:t,reason:n,leveledUp:s,newLevel:o,total:a}),s&&this._publish(`level_up`,{oldLevel:e,newLevel:o,totalXP:a}),{leveledUp:s,newLevel:o,xpGained:t}}getXPForNextLevel(){this._requirePlayer();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;return{total:n,needed:Math.max(0,n-t),progress:o}}_checkRecord(e,t){if(!x(e))throw TypeError(`[DopamineJS] record expects an activity name, received ${String(e)}`);if(!C(t))throw TypeError(`[DopamineJS] record expects a result object`);if(t.score!==void 0&&!Number.isFinite(t.score))throw TypeError(`[DopamineJS] record expects a finite score, received ${String(t.score)}`)}async record(e,t={}){if(this._requirePlayer(),this._checkRecord(e,t),!this._hasSlot())return!1;let n=await this._middleware.before(`beforeRecord`,{activity:e,result:t},e=>{try{return this._checkRecord(e.activity,e.result),!0}catch{return!1}});if(n===!1)return!1;let r=await this._batch(()=>this._record(n.activity,n.result));return await this._middleware.after(`afterRecord`,{activity:n.activity,result:n.result,xp:r}),!0}_markDay(){let e=this._doc,t=this.clock.localDate();if(e.playDates.includes(t))return;let n=e.playDates.length===0;e.playDates=h([...e.playDates,t],t),e.longest=Math.max(e.longest,_(e.playDates)),n||this._publish(`streak_updated`,{current:g(e.playDates,t),longest:Math.max(e.longest,_(e.playDates))})}async _record(e,t){let n=this._doc,r=this._deviceId,i=(e,t)=>{e[r]=D((S(e,r)?e[r]:0)+t)};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`,{activity:e,score:t.score}));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));let a=10;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}async checkAchievements(e,t){let n=[];for(let[r,i]of Object.entries(this.achievements)){if(S(this._doc.achievements,r))continue;let a=!1;try{a=i.check(this.snapshot(),e,t)}catch(e){console.error(`[DopamineJS] Achievement "${r}" check threw:`,e);continue}a&&await this.unlockAchievement(r)&&n.push(i)}return n}async unlockAchievement(e){if(this._requirePlayer(),!x(e)||!S(this.achievements,e)||S(this._doc.achievements,e))return!1;let t=this.achievements[e];if(!t)return!1;let{[e]:n}=c(this.achievements),r=await this._middleware.before(`beforeUnlock`,{id:e,reward:n},e=>Number.isFinite(e.reward)&&e.reward>=0);if(r===!1)return!1;let i=this._doc,a=H(i);return i.achievements[e]={unlockedAt:this.clock.now(),seen:!1,reward:r.reward},await this._announceXP(a,r.reward,`Achievement: ${t.name}`),this._publish(`achievement_unlocked`,{...t,id:e}),await this.save(),await this._middleware.after(`afterUnlock`,{id:e,reward:r.reward}),!0}getUnlockedAchievements(){return this._requirePlayer(),Object.entries(this._doc.achievements).map(([e,t])=>({...this.achievements[e],id:e,...t}))}getUnseenAchievements(){return this.getUnlockedAchievements().filter(e=>!e.seen)}async markAchievementsSeen(e){for(let t of e)S(this._doc.achievements,t)&&(this._doc.achievements[t].seen=!0);await this.save()}getStreakMultiplier(){let e=this.snapshot().streak.current;return e>=7?2:e>=5?1.5:e>=3?1.25:1}};function Q(){let e=new Map;return{getItem:t=>e.has(t)?e.get(t):null,setItem:(t,n)=>{e.set(t,String(n))},removeItem:t=>{e.delete(t)},clear:()=>{e.clear()}}}function $(){try{if(typeof localStorage>`u`)return Q();let e=`__dopamine_probe__`;return localStorage.setItem(e,`1`),localStorage.removeItem(e),localStorage}catch{return Q()}}var ie=class{constructor(e={}){this.storage=e.storage||$(),this.prefix=e.prefix||`dopamine_`,this._tail=null}_write(e){let t=this._tail?this._tail.then(e):e();if(typeof t?.then==`function`){let e=Promise.resolve(t).catch(()=>{}).then(()=>{this._tail===e&&(this._tail=null)});this._tail=e}return t}async save(e,t){try{let n=JSON.stringify(t);return await this._write(()=>this.storage.setItem(this.prefix+e,n)),!0}catch(e){return console.error(`Error saving data:`,e),!1}}async load(e,t=null,n={}){let r;try{await this._tail,r=await this.storage.getItem(this.prefix+e)}catch(e){if(n.strict)throw e;return console.error(`Error loading data:`,e),t}if(!r)return t;try{return JSON.parse(r)}catch(i){if(n.strict)throw Object.assign(Error(`[DopamineJS] saved "${e}" is not valid JSON`),{code:`DOPAMINE_CORRUPT`,raw:r});return console.error(`Error loading data:`,i),t}}async clear(e){await this._write(()=>this.storage.removeItem(this.prefix+e))}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return ie}});
|