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.
- package/README.md +13 -2
- package/dist/DataService-B5noGvMr.js +894 -0
- package/dist/DataService-DKCk0nOu.cjs +1 -0
- package/dist/SoundManager-C6VdZEFo.js +308 -0
- package/dist/SoundManager-DBGDYIkz.cjs +1 -0
- package/dist/celebrate.cjs +1 -0
- package/dist/celebrate.js +100 -0
- package/dist/core.cjs +1 -1
- package/dist/core.js +3 -1
- package/dist/dopamine.cjs +1 -1
- package/dist/dopamine.global.js +4 -4
- package/dist/dopamine.js +5 -3
- package/dist/host-B-Gn-Zg_.js +537 -0
- package/dist/host-D6suk7Ci.cjs +37 -0
- package/dist/storage-B6z-zaBe.cjs +1 -0
- package/dist/storage-C2s4Da9b.js +26 -0
- package/dist/testing.cjs +1 -1
- package/dist/testing.js +5 -3
- package/package.json +10 -3
- package/spec/README.md +113 -14
- package/spec/fixtures/merge.json +345 -0
- package/spec/fixtures/migrate.json +345 -22
- package/spec/fixtures/recovery.json +1861 -0
- package/spec/schema.json +2 -2
- package/src/celebrate.js +208 -0
- package/src/dopamine/core/RewardSystem.js +150 -11
- package/src/dopamine/core/merge.js +116 -1
- package/src/dopamine/core/store.js +90 -32
- package/src/dopamine/effects/ParticleSystem.js +5 -1
- package/src/dopamine/host.js +3 -1
- package/src/dopamine/ui/RewardUI.js +10 -6
- package/src/testing.js +2 -1
- package/types/celebrate.d.ts +31 -0
- package/types/index.d.ts +27 -4
- package/dist/DataService-CydwGT_D.js +0 -744
- package/dist/DataService-EJeOPnbo.cjs +0 -1
- package/dist/host-DOvdGHZL.js +0 -834
- package/dist/host-MPzunSej.cjs +0 -37
|
@@ -15,11 +15,33 @@ export const isSafeKey = (key) => typeof key === 'string' && key.length > 0 && !
|
|
|
15
15
|
export const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
|
|
16
16
|
export const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
17
17
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
18
|
+
// A number read from storage: a finite number, or a plain decimal string
|
|
19
|
+
// ("250", " -12 ", "1.5"). Hex, exponents, signs and the like are not read.
|
|
20
|
+
// Anything else is undefined and falls back to the default.
|
|
21
|
+
const DECIMAL = /^\s*-?\d+(\.\d+)?\s*$/;
|
|
22
|
+
export function toNumber(value) {
|
|
23
|
+
if (typeof value === 'string') value = DECIMAL.test(value) ? Number(value) : undefined;
|
|
24
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
21
27
|
export const cap = (value) => Math.min(value, Number.MAX_SAFE_INTEGER);
|
|
22
|
-
|
|
28
|
+
|
|
29
|
+
// Each reader returns the number, or undefined when the value does not fit.
|
|
30
|
+
const asNumber = toNumber;
|
|
31
|
+
const asAmount = (value) => {
|
|
32
|
+
const number = toNumber(value);
|
|
33
|
+
return number !== undefined && number >= 0 ? number : undefined;
|
|
34
|
+
};
|
|
35
|
+
const asCount = (value) => {
|
|
36
|
+
const number = toNumber(value);
|
|
37
|
+
return Number.isInteger(number) && number >= 0 ? number : undefined;
|
|
38
|
+
};
|
|
39
|
+
const numberOr = (value, fallback) => asNumber(value) ?? fallback;
|
|
40
|
+
const amountOr = (value, fallback) => asAmount(value) ?? fallback;
|
|
41
|
+
const count = (value, fallback, min = 0) => {
|
|
42
|
+
const number = toNumber(value);
|
|
43
|
+
return Number.isInteger(number) && number >= min ? cap(number) : fallback;
|
|
44
|
+
};
|
|
23
45
|
|
|
24
46
|
// Summed in key order, so the same document always gives the same float.
|
|
25
47
|
export const sum = (map, pick = (value) => value) => Object.keys(map).sort().reduce((total, key) => cap(total + pick(map[key])), 0);
|
|
@@ -41,20 +63,21 @@ export const emptyDoc = (now = 0) => ({
|
|
|
41
63
|
achievements: {}
|
|
42
64
|
});
|
|
43
65
|
|
|
44
|
-
function pickMap(source,
|
|
66
|
+
function pickMap(source, read) {
|
|
45
67
|
const map = {};
|
|
46
68
|
if (!isRecord(source)) return map;
|
|
47
69
|
for (const key of Object.keys(source)) {
|
|
48
|
-
|
|
70
|
+
const number = isSafeKey(key) ? read(source[key]) : undefined;
|
|
71
|
+
if (number !== undefined) map[key] = cap(number);
|
|
49
72
|
}
|
|
50
73
|
return map;
|
|
51
74
|
}
|
|
52
75
|
|
|
53
|
-
function pickNested(source,
|
|
76
|
+
function pickNested(source, read) {
|
|
54
77
|
const map = {};
|
|
55
78
|
if (!isRecord(source)) return map;
|
|
56
79
|
for (const key of Object.keys(source)) {
|
|
57
|
-
if (isSafeKey(key)) map[key] = pickMap(source[key],
|
|
80
|
+
if (isSafeKey(key)) map[key] = pickMap(source[key], read);
|
|
58
81
|
}
|
|
59
82
|
return map;
|
|
60
83
|
}
|
|
@@ -66,14 +89,46 @@ function pickAchievements(source, now) {
|
|
|
66
89
|
const entry = source[id];
|
|
67
90
|
if (!isSafeKey(id) || !isRecord(entry)) continue;
|
|
68
91
|
map[id] = {
|
|
69
|
-
unlockedAt:
|
|
92
|
+
unlockedAt: numberOr(entry.unlockedAt, now),
|
|
70
93
|
seen: entry.seen === true,
|
|
71
|
-
reward:
|
|
94
|
+
reward: cap(amountOr(entry.reward, 0))
|
|
72
95
|
};
|
|
73
96
|
}
|
|
74
97
|
return map;
|
|
75
98
|
}
|
|
76
99
|
|
|
100
|
+
// Fields of a document, and of a 2.x save, that the core reads. Any other
|
|
101
|
+
// top level field is kept as it was read, so a newer version's data survives.
|
|
102
|
+
export const DOC_KEYS = new Set(['v', 'name', 'createdAt', 'lastPlayedAt', 'level', 'longest', 'playDates', 'xpBy', 'xpSpentBy', 'gamesBy', 'playsBy', 'best', 'sumsBy', 'achievements']);
|
|
103
|
+
const READ_KEYS = new Set([...DOC_KEYS, 'xp', 'totalGamesPlayed', 'stats', 'streak']);
|
|
104
|
+
|
|
105
|
+
// A copy that holds only what JSON can: unsafe keys, functions, undefined and
|
|
106
|
+
// non-finite numbers are dropped. Deep input stops at 32 levels.
|
|
107
|
+
function plain(value, depth = 0) {
|
|
108
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;
|
|
109
|
+
if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;
|
|
110
|
+
if (depth >= 32) return undefined;
|
|
111
|
+
if (Array.isArray(value)) return value.map((item) => plain(item, depth + 1) ?? null);
|
|
112
|
+
if (!isRecord(value)) return undefined;
|
|
113
|
+
const copy = {};
|
|
114
|
+
for (const key of Object.keys(value)) {
|
|
115
|
+
const item = isSafeKey(key) ? plain(value[key], depth + 1) : undefined;
|
|
116
|
+
if (item !== undefined) copy[key] = item;
|
|
117
|
+
}
|
|
118
|
+
return copy;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function keepExtras(input, doc) {
|
|
122
|
+
for (const key of Object.keys(input)) {
|
|
123
|
+
if (READ_KEYS.has(key) || !isSafeKey(key)) continue;
|
|
124
|
+
const value = plain(input[key]);
|
|
125
|
+
if (value !== undefined) doc[key] = value;
|
|
126
|
+
}
|
|
127
|
+
return doc;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export const extraKeys = (doc) => Object.keys(doc).filter((key) => !DOC_KEYS.has(key));
|
|
131
|
+
|
|
77
132
|
// Every activity has a play map, a best and a sum map, so merge never has to
|
|
78
133
|
// ask whether one exists.
|
|
79
134
|
function finish(doc) {
|
|
@@ -88,29 +143,29 @@ function finish(doc) {
|
|
|
88
143
|
}
|
|
89
144
|
|
|
90
145
|
function read3(input, now, today) {
|
|
91
|
-
return finish({
|
|
146
|
+
return keepExtras(input, finish({
|
|
92
147
|
v: VERSION,
|
|
93
148
|
name: typeof input.name === 'string' ? input.name : 'Player',
|
|
94
|
-
createdAt:
|
|
95
|
-
lastPlayedAt:
|
|
149
|
+
createdAt: numberOr(input.createdAt, now),
|
|
150
|
+
lastPlayedAt: numberOr(input.lastPlayedAt, now),
|
|
96
151
|
level: count(input.level, 1, 1),
|
|
97
152
|
longest: count(input.longest, 0),
|
|
98
153
|
playDates: trimDays(Array.isArray(input.playDates) ? input.playDates.filter(isDay) : [], today),
|
|
99
|
-
xpBy: pickMap(input.xpBy,
|
|
100
|
-
xpSpentBy: pickMap(input.xpSpentBy,
|
|
101
|
-
gamesBy: pickMap(input.gamesBy,
|
|
102
|
-
playsBy: pickNested(input.playsBy,
|
|
103
|
-
best: pickMap(input.best,
|
|
154
|
+
xpBy: pickMap(input.xpBy, asAmount),
|
|
155
|
+
xpSpentBy: pickMap(input.xpSpentBy, asAmount),
|
|
156
|
+
gamesBy: pickMap(input.gamesBy, asCount),
|
|
157
|
+
playsBy: pickNested(input.playsBy, asCount),
|
|
158
|
+
best: pickMap(input.best, asAmount),
|
|
104
159
|
sumsBy: nestedSums(input.sumsBy),
|
|
105
160
|
achievements: pickAchievements(input.achievements, now)
|
|
106
|
-
});
|
|
161
|
+
}));
|
|
107
162
|
}
|
|
108
163
|
|
|
109
164
|
function nestedSums(source) {
|
|
110
165
|
const map = {};
|
|
111
166
|
if (!isRecord(source)) return map;
|
|
112
167
|
for (const activity of Object.keys(source)) {
|
|
113
|
-
if (isSafeKey(activity)) map[activity] = pickNested(source[activity],
|
|
168
|
+
if (isSafeKey(activity)) map[activity] = pickNested(source[activity], asAmount);
|
|
114
169
|
}
|
|
115
170
|
return map;
|
|
116
171
|
}
|
|
@@ -120,19 +175,19 @@ function nestedSums(source) {
|
|
|
120
175
|
function read2(input, now, rewards, today) {
|
|
121
176
|
const doc = emptyDoc(now);
|
|
122
177
|
doc.name = typeof input.name === 'string' ? input.name : 'Player';
|
|
123
|
-
doc.createdAt =
|
|
124
|
-
doc.lastPlayedAt =
|
|
178
|
+
doc.createdAt = numberOr(input.createdAt, now);
|
|
179
|
+
doc.lastPlayedAt = numberOr(input.lastPlayedAt, now);
|
|
125
180
|
doc.achievements = pickAchievements(input.achievements, now);
|
|
126
181
|
|
|
127
182
|
let granted = 0;
|
|
128
183
|
for (const id of Object.keys(doc.achievements)) {
|
|
129
|
-
const reward = hasOwn(rewards, id)
|
|
184
|
+
const reward = hasOwn(rewards, id) ? cap(amountOr(rewards[id], 0)) : 0;
|
|
130
185
|
doc.achievements[id].reward = reward;
|
|
131
186
|
granted += reward;
|
|
132
187
|
}
|
|
133
188
|
|
|
134
189
|
// The old xp already holds the rewards of the unlocked achievements.
|
|
135
|
-
const xp =
|
|
190
|
+
const xp = cap(amountOr(input.xp, 0));
|
|
136
191
|
const own = Math.max(0, xp - granted);
|
|
137
192
|
if (own > 0) doc.xpBy[LEGACY] = own;
|
|
138
193
|
doc.level = Math.max(levelFor(xp), count(input.level, 1, 1));
|
|
@@ -145,12 +200,12 @@ function read2(input, now, rewards, today) {
|
|
|
145
200
|
if (!isSafeKey(activity) || !isRecord(entry)) continue;
|
|
146
201
|
const plays = count(entry.totalPlays, 0);
|
|
147
202
|
doc.playsBy[activity] = plays > 0 ? { [LEGACY]: plays } : {};
|
|
148
|
-
doc.best[activity] =
|
|
203
|
+
doc.best[activity] = cap(amountOr(entry.highScore, 0));
|
|
149
204
|
doc.sumsBy[activity] = {};
|
|
150
205
|
for (const key of Object.keys(entry)) {
|
|
151
|
-
if (isSafeKey(key)
|
|
152
|
-
|
|
153
|
-
}
|
|
206
|
+
if (!isSafeKey(key) || key === 'totalPlays' || key === 'highScore') continue;
|
|
207
|
+
const amount = asAmount(entry[key]);
|
|
208
|
+
if (amount !== undefined) doc.sumsBy[activity][key] = { [LEGACY]: cap(amount) };
|
|
154
209
|
}
|
|
155
210
|
}
|
|
156
211
|
}
|
|
@@ -159,13 +214,16 @@ function read2(input, now, rewards, today) {
|
|
|
159
214
|
const current = count(streak.current, 1, 1);
|
|
160
215
|
doc.longest = Math.max(current, count(streak.longest, 0));
|
|
161
216
|
if (isDay(streak.lastPlayDate)) {
|
|
162
|
-
|
|
217
|
+
// A date after today (a clock change) counts as today, so the streak stays.
|
|
218
|
+
const last = today && streak.lastPlayDate > today ? today : streak.lastPlayDate;
|
|
219
|
+
for (let back = 0; back < Math.min(current, 400); back++) doc.playDates.push(shiftDay(last, -back));
|
|
163
220
|
doc.playDates = trimDays(doc.playDates, today);
|
|
164
221
|
} else {
|
|
165
|
-
|
|
222
|
+
// No real date, so no current run. The counts stay as the best run.
|
|
223
|
+
doc.longest = Math.max(count(streak.current, 0), count(streak.longest, 0));
|
|
166
224
|
}
|
|
167
225
|
|
|
168
|
-
return finish(doc);
|
|
226
|
+
return keepExtras(input, finish(doc));
|
|
169
227
|
}
|
|
170
228
|
|
|
171
229
|
export function deviceIds(doc) {
|
|
@@ -203,7 +261,7 @@ export function validate(input, options = {}) {
|
|
|
203
261
|
if (input.v !== undefined && input.v !== VERSION) {
|
|
204
262
|
throw new DopamineError('unsupported_version', `[DopamineJS] save version ${String(input.v)} is not ${VERSION}`);
|
|
205
263
|
}
|
|
206
|
-
const now =
|
|
264
|
+
const now = Number.isFinite(options.now) ? options.now : 0;
|
|
207
265
|
const today = isDay(options.today) ? options.today : undefined;
|
|
208
266
|
const doc = input.v === VERSION
|
|
209
267
|
? read3(input, now, today)
|
|
@@ -60,9 +60,13 @@ export class ParticleSystem {
|
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
+
// Ask for the context before the canvas goes into the page, so a
|
|
64
|
+
// constructor that fails leaves no node and no listener behind.
|
|
65
|
+
const ctx = this.canvas.getContext('2d');
|
|
66
|
+
if (!ctx) throw new Error('[DopamineJS] This canvas has no 2d context');
|
|
63
67
|
this.container.appendChild(this.canvas);
|
|
64
68
|
|
|
65
|
-
this.ctx =
|
|
69
|
+
this.ctx = ctx;
|
|
66
70
|
this.particles = [];
|
|
67
71
|
this.pool = []; // Object pool
|
|
68
72
|
this.sprites = new Map(); // key -> Image
|
package/src/dopamine/host.js
CHANGED
|
@@ -63,6 +63,7 @@ function namespacedStorage(storage, name) {
|
|
|
63
63
|
* @param {{ now(): number, localDate(ms?: number): string }} [options.clock]
|
|
64
64
|
* @param {'any'|'record'} [options.streakDays] - For the default progress object
|
|
65
65
|
* @param {boolean} [options.builtinAchievements] - For the default progress object, false defines no built-ins
|
|
66
|
+
* @param {number} [options.loadRetryMs] - For the default progress object, see RewardSystem
|
|
66
67
|
* @param {Object[]} [options.plugins]
|
|
67
68
|
* @param {{ debug?: Function, info?: Function, warn?: Function, error?: Function }} [options.log]
|
|
68
69
|
*/
|
|
@@ -90,7 +91,7 @@ export function createDopamine(options = {}) {
|
|
|
90
91
|
|
|
91
92
|
const factoryEnv = { ...env, parts, storage, clock };
|
|
92
93
|
|
|
93
|
-
const progress = resolvePart(opts.progress, factoryEnv, () => new RewardSystem(new DataService({ storage }), { clock, streakDays: opts.streakDays, builtinAchievements: opts.builtinAchievements }));
|
|
94
|
+
const progress = resolvePart(opts.progress, factoryEnv, () => new RewardSystem(new DataService({ storage }), { clock, streakDays: opts.streakDays, builtinAchievements: opts.builtinAchievements, loadRetryMs: opts.loadRetryMs }));
|
|
94
95
|
if (typeof progress?.on !== 'function' || typeof progress?.off !== 'function') {
|
|
95
96
|
throw new DopamineError('invalid_progress', 'progress needs on() and off()');
|
|
96
97
|
}
|
|
@@ -157,6 +158,7 @@ export function createDopamine(options = {}) {
|
|
|
157
158
|
})),
|
|
158
159
|
events.on('streak_updated', react(sync)),
|
|
159
160
|
events.on('player_reset', react(sync)),
|
|
161
|
+
events.on('load_recovered', react(sync)),
|
|
160
162
|
events.on('personal_best', react((e) => {
|
|
161
163
|
slots.ui?.popup({ kind: 'notice', title: `New High Score: ${e.score}!`, tier: 'legendary' });
|
|
162
164
|
slots.sound?.play('personal_best');
|
|
@@ -402,7 +402,9 @@ export class RewardUI {
|
|
|
402
402
|
* - `custom` (and any other kind): the achievement layout without the heading.
|
|
403
403
|
*
|
|
404
404
|
* @param {{ kind: string, title?: string, body?: string, icon?: string|Node,
|
|
405
|
-
* meta?: string, tier?: 'common'|'rare'|'legendary' }} popup
|
|
405
|
+
* meta?: string, tier?: 'common'|'rare'|'legendary', burst?: boolean }} popup
|
|
406
|
+
* `burst: false` on a card skips the confetti it fires after 300 ms. Any
|
|
407
|
+
* other value keeps it.
|
|
406
408
|
*/
|
|
407
409
|
popup(popup) {
|
|
408
410
|
if (!this.container || !popup || typeof popup !== 'object') return;
|
|
@@ -425,7 +427,7 @@ export class RewardUI {
|
|
|
425
427
|
// Copy the fields now, so a caller that reuses its object cannot change
|
|
426
428
|
// a card that is still waiting.
|
|
427
429
|
const { title, body, meta, icon } = popup;
|
|
428
|
-
this._cardQueue.push([{ title, body, meta, icon }, withHeading]);
|
|
430
|
+
this._cardQueue.push([{ title, body, meta, icon, burst: ownValue(popup, 'burst') }, withHeading]);
|
|
429
431
|
this._nextCard();
|
|
430
432
|
}
|
|
431
433
|
|
|
@@ -473,10 +475,12 @@ export class RewardUI {
|
|
|
473
475
|
this._mount(card);
|
|
474
476
|
this._announce(withHeading ? `${this.strings.achievementUnlocked}: ${title}` : title);
|
|
475
477
|
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
478
|
+
if (popup.burst !== false) {
|
|
479
|
+
this._defer(() => {
|
|
480
|
+
const rect = card.getBoundingClientRect();
|
|
481
|
+
this._burst('confetti', { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }, { count: 40 });
|
|
482
|
+
}, 300);
|
|
483
|
+
}
|
|
480
484
|
|
|
481
485
|
this._defer(() => {
|
|
482
486
|
card.style.animation = 'slideOut 0.3s ease-in forwards';
|
package/src/testing.js
CHANGED
|
@@ -20,7 +20,8 @@ const CORE_EVENTS = {
|
|
|
20
20
|
streak_updated: { current: 1, longest: 1 },
|
|
21
21
|
player_reset: {},
|
|
22
22
|
save_failed: { error: new Error('save failed') },
|
|
23
|
-
load_failed: { reason: 'corrupt' }
|
|
23
|
+
load_failed: { reason: 'corrupt' },
|
|
24
|
+
load_recovered: { key: 'player' }
|
|
24
25
|
};
|
|
25
26
|
const BURST_KINDS = ['confetti', 'sparkle', 'fire', 'stars', 'coins'];
|
|
26
27
|
const SOUND_KEYS = ['xp', 'level_up', 'achievement', 'personal_best', 'click', 'error'];
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Parts } from './index';
|
|
2
|
+
|
|
3
|
+
export type CelebratePreset = 'complete' | 'milestone' | 'streak' | 'certificate';
|
|
4
|
+
|
|
5
|
+
export interface CelebrateOptions {
|
|
6
|
+
/** Replaces the preset title. Rendered as text. */
|
|
7
|
+
title?: string;
|
|
8
|
+
/** A line under the title. Rendered as text. */
|
|
9
|
+
body?: string;
|
|
10
|
+
/** Replaces the preset icon. A string is shown as text, a Node is appended. Through `parts` it follows `safeIcons`. */
|
|
11
|
+
icon?: string | Node;
|
|
12
|
+
/** Confetti is centred on this element, else on the viewport. */
|
|
13
|
+
target?: Element;
|
|
14
|
+
/** A sound key to play. `false` plays nothing. Default is the preset sound. */
|
|
15
|
+
sound?: string | false;
|
|
16
|
+
/**
|
|
17
|
+
* Send the toast, confetti and sound through a host's parts, such as `dopamine.parts`.
|
|
18
|
+
* A part the host does not have is skipped, with no standalone fallback.
|
|
19
|
+
*/
|
|
20
|
+
parts?: Partial<Parts>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Show a toast, fire confetti and play a sound. Works without createDopamine().
|
|
25
|
+
* An unknown preset does nothing. With reduced motion on there is no confetti.
|
|
26
|
+
* Never throws.
|
|
27
|
+
*/
|
|
28
|
+
export function celebrate(preset: CelebratePreset, options?: CelebrateOptions): void;
|
|
29
|
+
|
|
30
|
+
/** Remove the toast, its timer and what the standalone route created. */
|
|
31
|
+
export function destroyCelebrations(): void;
|
package/types/index.d.ts
CHANGED
|
@@ -40,7 +40,8 @@ export interface Player {
|
|
|
40
40
|
|
|
41
41
|
/**
|
|
42
42
|
* The saved document. It merges: see `merge`. Treat it as opaque and pass it
|
|
43
|
-
* to `merge`, `validate` and `import`.
|
|
43
|
+
* to `merge`, `validate` and `import`. A save can also hold top level fields
|
|
44
|
+
* this version does not know. They are kept as read.
|
|
44
45
|
*/
|
|
45
46
|
export interface PlayerDocument {
|
|
46
47
|
v: 3;
|
|
@@ -152,6 +153,12 @@ export interface RewardSystemConfig {
|
|
|
152
153
|
* never marks a day.
|
|
153
154
|
*/
|
|
154
155
|
streakDays?: 'any' | 'record';
|
|
156
|
+
/**
|
|
157
|
+
* After a failed read of the saved player, a blocked save retries the read
|
|
158
|
+
* at most this often, in milliseconds of `clock`. Default 30000. 0 retries
|
|
159
|
+
* on every blocked save.
|
|
160
|
+
*/
|
|
161
|
+
loadRetryMs?: number;
|
|
155
162
|
}
|
|
156
163
|
|
|
157
164
|
export type RewardEvent =
|
|
@@ -175,7 +182,13 @@ export type RewardEvent =
|
|
|
175
182
|
* A `load()` override must pass its third argument on, or a failed read
|
|
176
183
|
* looks like an empty one.
|
|
177
184
|
*/
|
|
178
|
-
| 'load_failed'
|
|
185
|
+
| 'load_failed'
|
|
186
|
+
/**
|
|
187
|
+
* Payload `{ key }`. After a `load_failed` with `reason: 'read'`, a retry read
|
|
188
|
+
* the saved player, merged the progress made since into it and saved it.
|
|
189
|
+
* `loadFailed` is false again.
|
|
190
|
+
*/
|
|
191
|
+
| 'load_recovered';
|
|
179
192
|
|
|
180
193
|
export class EventEmitter {
|
|
181
194
|
on(event: string, callback: (data?: unknown) => void): () => void;
|
|
@@ -190,9 +203,13 @@ export class RewardSystem extends EventEmitter {
|
|
|
190
203
|
achievements: Record<string, AchievementDefinition>;
|
|
191
204
|
/**
|
|
192
205
|
* True when the last `init()` could not read the saved player, so nothing
|
|
193
|
-
* is saved until `init()`
|
|
206
|
+
* is saved until a retry or `init()` reads it, or `reset()` is called. A blocked
|
|
207
|
+
* save retries the read (see `loadRetryMs`); on success it merges the session
|
|
208
|
+
* into the saved player, saves it and fires `load_recovered`.
|
|
194
209
|
*/
|
|
195
210
|
readonly loadFailed: boolean;
|
|
211
|
+
/** Minimum clock time between read retries after a failed read. Default 30000. */
|
|
212
|
+
readonly loadRetryMs: number;
|
|
196
213
|
|
|
197
214
|
init(): Promise<Player>;
|
|
198
215
|
/** A frozen copy of the player with the derived values. */
|
|
@@ -214,7 +231,9 @@ export class RewardSystem extends EventEmitter {
|
|
|
214
231
|
*
|
|
215
232
|
* With `{ overwrite: false }` and a failed load, the stored player is kept:
|
|
216
233
|
* the player in memory is replaced by a new empty one, nothing is written,
|
|
217
|
-
* `loadFailed` stays true and `player_reset` is still emitted.
|
|
234
|
+
* `loadFailed` stays true and `player_reset` is still emitted. A later write
|
|
235
|
+
* may retry the read and, when it returns a player, merges the new session
|
|
236
|
+
* into it (see `loadRetryMs`). After a load
|
|
218
237
|
* that worked, `overwrite: false` behaves like a plain `reset()` and saves.
|
|
219
238
|
* A corrupt save that init() backed up to `player_corrupt` counts as loaded, so `overwrite: false` saves like a plain reset(). If the backup failed, it counts as a failed load and nothing is written.
|
|
220
239
|
* A non-object `options` or a non-boolean `overwrite` throws a `TypeError`.
|
|
@@ -366,6 +385,8 @@ export interface Popup {
|
|
|
366
385
|
/** An extra line under an achievement, such as `+50 XP`. */
|
|
367
386
|
meta?: string;
|
|
368
387
|
tier?: 'common' | 'rare' | 'legendary';
|
|
388
|
+
/** On a card, `false` skips the confetti it fires after 300 ms. Any other value keeps it. */
|
|
389
|
+
burst?: boolean;
|
|
369
390
|
}
|
|
370
391
|
|
|
371
392
|
export interface FloatingText {
|
|
@@ -622,6 +643,8 @@ export interface DopamineOptions {
|
|
|
622
643
|
streakDays?: 'any' | 'record';
|
|
623
644
|
/** Passed to the default progress object. See `RewardSystemConfig`. */
|
|
624
645
|
builtinAchievements?: boolean;
|
|
646
|
+
/** Passed to the default progress object. See `RewardSystemConfig`. */
|
|
647
|
+
loadRetryMs?: number;
|
|
625
648
|
plugins?: DopaminePlugin[];
|
|
626
649
|
log?: Partial<Logger>;
|
|
627
650
|
}
|