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/spec/schema.json CHANGED
@@ -2,10 +2,10 @@
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
3
  "$id": "https://github.com/BaryoDev/dopaminejs/spec/schema.json",
4
4
  "title": "DopamineJS player document, contract 3",
5
- "description": "What export() returns and what validate() and merge() accept. Only v is required on input; validate fills in the rest. Keys inside the per-device maps are device ids, which are never __proto__, constructor or prototype, and a document holds at most 20 of them across xpBy, xpSpentBy, gamesBy, playsBy and sumsBy.",
5
+ "description": "What export() returns and what validate() and merge() accept. Only v is required on input; validate fills in the rest. Any other top level field is kept as read (never __proto__, constructor or prototype). merge joins such a field by value: the larger number if both sides hold a finite number, otherwise the larger canonical JSON text. Recency is not used, since no field has its own timestamp and merge must not depend on order. Keys inside the per-device maps are device ids, which are never __proto__, constructor or prototype, and a document holds at most 20 of them across xpBy, xpSpentBy, gamesBy, playsBy and sumsBy.",
6
6
  "type": "object",
7
7
  "required": ["v"],
8
- "additionalProperties": false,
8
+ "additionalProperties": true,
9
9
  "properties": {
10
10
  "v": { "const": 3 },
11
11
  "name": { "type": "string" },
@@ -0,0 +1,208 @@
1
+ /**
2
+ * The `dopaminejs/celebrate` subpath: one call shows a toast, fires confetti
3
+ * and plays a sound. It works without createDopamine(). Pass `parts` to send
4
+ * the three through a host instead. Nothing in the main entry imports it.
5
+ */
6
+
7
+ import { ParticleSystem } from './dopamine/effects/ParticleSystem.js';
8
+ import { SoundManager } from './dopamine/audio/SoundManager.js';
9
+ import { prefersReducedMotion } from './dopamine/feel/motion.js';
10
+
11
+ const preset = (title, icon, sound, count) => Object.freeze({ title, icon, sound, count });
12
+
13
+ const PRESETS = Object.freeze(Object.assign(Object.create(null), {
14
+ complete: preset('Complete!', '\u{2705}', 'achievement', 40),
15
+ milestone: preset('Milestone reached', '\u{1F3C1}', 'level_up', 60),
16
+ streak: preset('Streak kept', '\u{1F525}', 'achievement', 40),
17
+ certificate: preset('Certificate earned', '\u{1F393}', 'level_up', 80)
18
+ }));
19
+
20
+ const TOAST_MS = 3000;
21
+ const TOAST_STYLE = 'position:fixed;top:16px;left:50%;transform:translateX(-50%);z-index:10000;'
22
+ + 'display:flex;align-items:center;gap:12px;max-width:min(90vw,420px);padding:12px 18px;'
23
+ + 'border-radius:10px;background:#1f2937;color:#fff;border:1px solid rgba(255,255,255,0.25);'
24
+ + 'box-shadow:0 6px 24px rgba(0,0,0,0.35);font:16px/1.3 system-ui,sans-serif;pointer-events:none';
25
+
26
+ const hasBody = (body) => body !== undefined && body !== null && body !== '';
27
+
28
+ const REGION_STYLE = 'position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap';
29
+
30
+ // Options come from callers, so an inherited property must not count. A local
31
+ // copy: importing hasOwn from core/store.js splits a shared chunk and grows the main CJS bundle.
32
+ const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
33
+ const ownValue = (object, key) =>
34
+ (object !== null && typeof object === 'object' && hasOwn(object, key) ? object[key] : undefined);
35
+
36
+ // What the standalone route made, until destroyCelebrations().
37
+ let particles = null;
38
+ let sound = null;
39
+ let toast = null;
40
+ let timer = null;
41
+ let region = null;
42
+ let regionTimer = null;
43
+
44
+ // A part that throws or rejects is logged, so the other two still run.
45
+ const attempt = (fn) => {
46
+ try {
47
+ const result = fn();
48
+ if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
49
+ result.then(undefined, (error) => console.error(error));
50
+ }
51
+ } catch (error) {
52
+ console.error(error);
53
+ }
54
+ };
55
+
56
+ // Where the confetti goes: the middle of the target, else the viewport.
57
+ function centreOf(target) {
58
+ if (typeof target?.getBoundingClientRect === 'function') {
59
+ const { left, top, width, height } = target.getBoundingClientRect();
60
+ if ((width !== 0 || height !== 0) && Number.isFinite(left + top + width + height)) {
61
+ return { x: left + width / 2, y: top + height / 2 };
62
+ }
63
+ }
64
+ return { x: window.innerWidth / 2, y: window.innerHeight / 2 };
65
+ }
66
+
67
+ function removeToast() {
68
+ clearTimeout(timer);
69
+ timer = null;
70
+ toast?.remove();
71
+ toast = null;
72
+ }
73
+
74
+ // A live region that arrives with its text is often skipped, so one hidden
75
+ // region is put in the page empty and its text is always set a tick later.
76
+ // A page that replaces its body leaves the old region detached, so that one
77
+ // counts as missing.
78
+ function announce(message) {
79
+ clearTimeout(regionTimer);
80
+ if (region && !region.isConnected) region = null;
81
+ // The same text set again may send no live-region event, so empty it first.
82
+ if (region) region.textContent = '';
83
+ if (!region) {
84
+ region = document.createElement('div');
85
+ region.className = 'dopamine-celebrate-live';
86
+ region.setAttribute('role', 'status');
87
+ region.setAttribute('aria-live', 'polite');
88
+ region.style.cssText = REGION_STYLE;
89
+ document.body.appendChild(region);
90
+ }
91
+ regionTimer = setTimeout(() => {
92
+ regionTimer = null;
93
+ if (region) region.textContent = message;
94
+ }, 0);
95
+ }
96
+
97
+ function showToast(title, body, icon) {
98
+ removeToast();
99
+ const el = document.createElement('div');
100
+ el.className = 'dopamine-celebrate-toast';
101
+ el.setAttribute('aria-hidden', 'true');
102
+ el.style.cssText = TOAST_STYLE;
103
+
104
+ const add = (text) => {
105
+ const child = document.createElement('div');
106
+ child.textContent = text;
107
+ return child;
108
+ };
109
+ if (typeof Node !== 'undefined' && icon instanceof Node) {
110
+ const holder = document.createElement('div');
111
+ holder.appendChild(icon);
112
+ el.appendChild(holder);
113
+ } else if (typeof icon === 'string' && icon !== '') {
114
+ const holder = add(icon);
115
+ holder.style.fontSize = '28px';
116
+ el.appendChild(holder);
117
+ }
118
+ const text = document.createElement('div');
119
+ const name = add(title);
120
+ name.style.fontWeight = '600';
121
+ text.appendChild(name);
122
+ if (hasBody(body)) text.appendChild(add(body));
123
+ el.appendChild(text);
124
+
125
+ document.body.appendChild(el);
126
+ toast = el;
127
+ timer = setTimeout(removeToast, TOAST_MS);
128
+ announce(hasBody(body) ? `${title}. ${body}` : String(title));
129
+ }
130
+
131
+ /**
132
+ * Show a toast, fire confetti and play a sound. Presets: complete, milestone,
133
+ * streak, certificate. An unknown preset does nothing. Never throws.
134
+ *
135
+ * @param {'complete'|'milestone'|'streak'|'certificate'} name
136
+ * @param {{ title?: string, body?: string, icon?: string|Node, target?: Element,
137
+ * sound?: string|false, parts?: Object }} [options] - `parts` sends the toast,
138
+ * confetti and sound through a host's parts.
139
+ * A part the host does not have is skipped, with no standalone fallback.
140
+ * @returns {undefined}
141
+ */
142
+ export function celebrate(name, options) {
143
+ if (typeof name !== 'string' || !hasOwn(PRESETS, name)) return;
144
+ const { title, icon, sound: presetSound, count } = PRESETS[name];
145
+ let shownTitle, body, shownIcon, key, given, target;
146
+ try {
147
+ // A getter on the options can throw, so the reads sit inside the guard.
148
+ shownTitle = ownValue(options, 'title') ?? title;
149
+ body = ownValue(options, 'body');
150
+ shownIcon = ownValue(options, 'icon') ?? icon;
151
+ const soundOption = ownValue(options, 'sound');
152
+ key = soundOption === false ? null : (typeof soundOption === 'string' ? soundOption : presetSound);
153
+ given = ownValue(options, 'parts');
154
+ target = ownValue(options, 'target');
155
+ } catch (error) {
156
+ console.error(error);
157
+ return;
158
+ }
159
+ const routed = given !== null && typeof given === 'object';
160
+
161
+ if (typeof document === 'undefined' || typeof window === 'undefined') {
162
+ // No DOM: only a host's parts can still do something.
163
+ if (!routed) return;
164
+ }
165
+ const hasDom = typeof document !== 'undefined' && typeof window !== 'undefined';
166
+ const motionAllowed = () => prefersReducedMotion(window).matches !== true;
167
+
168
+ attempt(() => {
169
+ if (routed) {
170
+ return given.ui?.popup({ kind: 'custom', title: shownTitle, body, icon: shownIcon, burst: false });
171
+ }
172
+ showToast(shownTitle, body, shownIcon);
173
+ });
174
+ attempt(() => {
175
+ if (!hasDom || !motionAllowed()) return;
176
+ const at = centreOf(target);
177
+ if (routed) return given.particles?.burst?.('confetti', at, { count });
178
+ // A body replace detaches the canvas, so confetti would draw where nobody sees it.
179
+ if (particles && !particles.canvas.isConnected) {
180
+ const old = particles;
181
+ particles = null;
182
+ attempt(() => old.destroy());
183
+ }
184
+ particles ??= new ParticleSystem({ canvasId: 'dopamine-celebrate-canvas' });
185
+ particles.burst('confetti', at, { count });
186
+ });
187
+ if (key === null) return;
188
+ attempt(() => {
189
+ if (routed) return given.sound?.play?.(key);
190
+ sound ??= new SoundManager();
191
+ // The manager reads the mute flag once, so take a mute made elsewhere.
192
+ sound.muted = sound.storage.getItem(sound.storageKey) === 'true';
193
+ return sound.play(key);
194
+ });
195
+ }
196
+
197
+ /** Remove the toast, the live region, the timers, and the particle system and sound manager the standalone route made. */
198
+ export function destroyCelebrations() {
199
+ removeToast();
200
+ clearTimeout(regionTimer);
201
+ regionTimer = null;
202
+ region?.remove();
203
+ region = null;
204
+ const made = [particles, sound];
205
+ particles = null;
206
+ sound = null;
207
+ for (const part of made) attempt(() => part?.destroy());
208
+ }
@@ -12,10 +12,10 @@ import { systemClock } from './clock.js';
12
12
  import { levelFor, thresholdFor } from './levels.js';
13
13
  import { BUILTIN_REWARDS, builtinAchievements, rewardsOf } from './achievements.js';
14
14
  import { Middleware } from './middleware.js';
15
- import { merge } from './merge.js';
15
+ import { merge, mergeSession, rekey, ownCounters, raiseOwn, countedDevices } from './merge.js';
16
16
  import { currentStreak, longestRun, trimDays } from './streaks.js';
17
17
  import {
18
- LEGACY, MAX_DEVICES, cap, deviceIds, emptyDoc, validate, view, xpOf, levelOf, clone, freeze, isSafeKey, hasOwn, isRecord
18
+ LEGACY, MAX_DEVICES, cap, checkDevices, deviceIds, emptyDoc, validate, view, xpOf, levelOf, clone, freeze, isSafeKey, hasOwn, isRecord
19
19
  } from './store.js';
20
20
 
21
21
  const DEVICE_KEY = 'device';
@@ -45,6 +45,8 @@ export class RewardSystem extends EventEmitter {
45
45
  * @param {'any'|'record'} [config.streakDays] - What marks today as a play day.
46
46
  * 'any' (default): record() or addXP(). 'record': record() only. XP from an
47
47
  * achievement reward never marks a day.
48
+ * @param {number} [config.loadRetryMs] - After a failed read, a blocked save retries the
49
+ * read at most this often, in ms of the clock. Default 30000. 0 retries on every blocked save.
48
50
  */
49
51
  constructor(dataService, config = {}) {
50
52
  super();
@@ -73,11 +75,26 @@ export class RewardSystem extends EventEmitter {
73
75
  // never replaced by accident.
74
76
  this._loadFailed = false;
75
77
  this._readFailed = false;
78
+
79
+ // Retry of a failed read: when it last read, the retry in flight, and a
80
+ // counter that lets init() cancel a retry it overtakes.
81
+ this.loadRetryMs = Number.isFinite(config.loadRetryMs) && config.loadRetryMs >= 0 ? config.loadRetryMs : 30000;
82
+ this._lastRead = 0;
83
+ this._reading = false;
84
+ this._recovering = null;
85
+ this._epoch = 0;
86
+
87
+ // What imports and good reads put into this device's counters while the
88
+ // read is blocked. It is not progress made here, so a recovery does not add it.
89
+ this._forgetImports();
90
+ this._recoveries = 0;
76
91
  }
77
92
 
78
93
  /**
79
94
  * True when the last init() could not read the saved player, so nothing
80
- * is saved until init() is called again and the read works, or reset() is called.
95
+ * is saved until a retry or init() reads it, or reset() is called. A blocked
96
+ * save retries the read (see `loadRetryMs`) and, when it works, merges the
97
+ * progress made since into the saved player, saves it and fires `load_recovered`.
81
98
  * @returns {boolean}
82
99
  */
83
100
  get loadFailed() {
@@ -117,9 +134,16 @@ export class RewardSystem extends EventEmitter {
117
134
  * @returns {Promise<Object>} Frozen snapshot of the player
118
135
  */
119
136
  async init() {
137
+ const known = this._doc && !this._loadFailed && ownCounters(this._doc, this._deviceId);
120
138
  const saved = await this._readSaved();
121
139
  // A failed retry keeps the progress made since the first init.
122
- if (!(this._loadFailed && this._doc)) this._doc = this._load(saved);
140
+ if (!(this._loadFailed && this._doc)) {
141
+ this._doc = this._load(saved);
142
+ this._forgetImports();
143
+ } else if (known) {
144
+ // That player came from storage, so what it held is not new progress.
145
+ known.forEach((value, path) => this._base.set(path, Math.max(this._base.get(path) ?? 0, value)));
146
+ }
123
147
  await this._readDevice();
124
148
  await this.save();
125
149
  return this.snapshot();
@@ -135,6 +159,10 @@ export class RewardSystem extends EventEmitter {
135
159
  // Stay blocked until the read succeeds, so a write made while a
136
160
  // retry is in flight cannot land.
137
161
  this._loadFailed = true;
162
+ this._reading = true;
163
+ this._epoch++;
164
+ this._recovering = null;
165
+ this._lastRead = this.clock.now();
138
166
  try {
139
167
  const saved = await this.dataService.load('player', null, { strict: true });
140
168
  if (saved !== null && !isRecord(saved)) {
@@ -149,7 +177,82 @@ export class RewardSystem extends EventEmitter {
149
177
  this._readFailed = true;
150
178
  this._publish('load_failed', { key: 'player', reason: 'read', error });
151
179
  return null;
180
+ } finally {
181
+ this._reading = false;
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Retry the read for a blocked save, at most once per interval, and merge
187
+ * the session player into what it finds. Resolves true when it saved. A
188
+ * retry already in flight is reused. Any failure leaves saving blocked and
189
+ * the session player as it is.
190
+ * @private
191
+ */
192
+ _recover() {
193
+ // A retry in flight belongs to the call that started it. Others return
194
+ // at once, as a blocked save always did, so a read that never settles
195
+ // stalls only that one call.
196
+ if (this._recovering || !this._readFailed || this._reading) return Promise.resolve(false);
197
+ const since = this.clock.now() - this._lastRead;
198
+ if (since >= 0 && since < this.loadRetryMs) return Promise.resolve(false);
199
+ this._lastRead = this.clock.now();
200
+ const retry = this._retryRead(this._epoch).finally(() => {
201
+ if (this._recovering === retry) this._recovering = null;
202
+ });
203
+ this._recovering = retry;
204
+ return retry;
205
+ }
206
+
207
+ async _retryRead(epoch) {
208
+ let saved;
209
+ let adopt = null;
210
+ try {
211
+ saved = await this.dataService.load('player', null, { strict: true });
212
+ if (saved !== null && !isRecord(saved)) return false;
213
+ if (!this._deviceSaved) {
214
+ const stored = await this.dataService.load(DEVICE_KEY, null, { strict: true });
215
+ if (isDeviceId(stored) && stored !== this._deviceId) adopt = stored;
216
+ }
217
+ } catch {
218
+ return false;
219
+ }
220
+ // init() or reset() ran meanwhile and owns the state now.
221
+ if (epoch !== this._epoch || !this._loadFailed) return false;
222
+ // Entries under the stored id that came from an import or from a read
223
+ // cannot be told from progress made here, so the move would count them twice.
224
+ if (countedDevices(this._doc).has(adopt)) return false;
225
+
226
+ // No await from here to the assignment, so the session player is
227
+ // merged as it stands, including any XP added while the read was out.
228
+ let merged;
229
+ try {
230
+ const options = this._options();
231
+ const device = adopt ?? this._deviceId;
232
+ const session = adopt ? rekey(this._doc, this._deviceId, adopt) : this._doc;
233
+ merged = saved === null ? clone(session) : mergeSession(saved, session, device, options, this._base);
234
+ checkDevices(merged);
235
+ merged.level = levelOf(merged);
236
+ } catch {
237
+ return false;
238
+ }
239
+ if (adopt) {
240
+ this._deviceId = adopt;
241
+ this._deviceSaved = true;
152
242
  }
243
+ this._doc = merged;
244
+ this._recoveries++;
245
+ this._savedLevel = Number(saved?.level) || 0;
246
+ this._loadFailed = false;
247
+ this._readFailed = false;
248
+ this._forgetImports();
249
+ await this._write();
250
+ this._publish('load_recovered', { key: 'player' });
251
+ return true;
252
+ }
253
+
254
+ _forgetImports() {
255
+ this._base = new Map();
153
256
  }
154
257
 
155
258
  /**
@@ -253,9 +356,28 @@ export class RewardSystem extends EventEmitter {
253
356
  this._requirePlayer();
254
357
  const before = this.snapshot();
255
358
  const incoming = validate(doc, this._options());
256
- const merged = merge(this._doc, incoming, this._options());
359
+ let session = this._doc;
360
+ let base = null;
361
+ if (this._readFailed) {
362
+ // This device's counters in the import are not new progress. Count them
363
+ // as a baseline so a recovery adds only what the session earned on top.
364
+ base = new Map(this._base);
365
+ const raise = new Map();
366
+ const have = ownCounters(this._doc, this._deviceId);
367
+ ownCounters(incoming, this._deviceId).forEach((value, path) => {
368
+ // At or below what the session holds, it is the session's own export or older.
369
+ if (value > (have.get(path) ?? 0)) {
370
+ raise.set(path, value - (base.get(path) ?? 0));
371
+ base.set(path, value);
372
+ }
373
+ });
374
+ session = clone(this._doc);
375
+ raiseOwn(session, this._deviceId, raise);
376
+ }
377
+ const merged = merge(session, incoming, this._options());
257
378
  merged.level = levelOf(merged);
258
379
  this._doc = merged;
380
+ if (base) this._base = base;
259
381
 
260
382
  const after = this.snapshot();
261
383
  await this.save();
@@ -292,8 +414,9 @@ export class RewardSystem extends EventEmitter {
292
414
  * Pass `{ overwrite: false }` to keep the stored player when the last
293
415
  * init() could not read it (an unsupported newer version, or a read that
294
416
  * keeps failing). The player in memory is replaced by a new empty one,
295
- * nothing is written, `loadFailed` stays true so later writes stay
296
- * blocked, and `player_reset` is still emitted. When the last init() did
417
+ * nothing is written, `loadFailed` stays true and `player_reset` is still
418
+ * emitted. A later write may retry the read and, when it returns a
419
+ * player, merges the new session into it (see `loadRetryMs`). When the last init() did
297
420
  * read the saved player, `overwrite: false` changes nothing: it saves
298
421
  * like a plain reset(). A corrupt save that init() backed up to `player_corrupt` counts as loaded, so `overwrite: false` saves like a plain reset().
299
422
  * If the backup failed, it counts as a failed load and nothing is written.
@@ -316,6 +439,7 @@ export class RewardSystem extends EventEmitter {
316
439
  this._requirePlayer();
317
440
  if (overwrite === false && this._readFailed) {
318
441
  this._doc = emptyDoc(this.clock.now());
442
+ this._forgetImports();
319
443
  this._publish('player_reset', {});
320
444
  return this.snapshot();
321
445
  }
@@ -323,6 +447,7 @@ export class RewardSystem extends EventEmitter {
323
447
  this._doc = emptyDoc(this.clock.now());
324
448
  this._loadFailed = false;
325
449
  this._readFailed = false;
450
+ this._forgetImports();
326
451
  await this.save();
327
452
  });
328
453
  this._publish('player_reset', {});
@@ -378,7 +503,11 @@ export class RewardSystem extends EventEmitter {
378
503
  * @private
379
504
  */
380
505
  async _write() {
381
- if (this._loadFailed) return;
506
+ if (this._loadFailed) {
507
+ // The retry saves everything changed before it merged.
508
+ await this._recover();
509
+ return;
510
+ }
382
511
  this._doc.lastPlayedAt = this.clock.now();
383
512
  if (!this._deviceSaved) {
384
513
  this._deviceSaved = (await this.dataService.save(DEVICE_KEY, this._deviceId)) !== false;
@@ -448,13 +577,23 @@ export class RewardSystem extends EventEmitter {
448
577
 
449
578
  async _announceXP(oldLevel, amount, reason) {
450
579
  const doc = this._doc;
451
- const total = xpOf(doc);
452
- const newLevel = Math.max(oldLevel, levelFor(total));
453
- const leveledUp = newLevel > oldLevel;
580
+ let total = xpOf(doc);
581
+ let newLevel = Math.max(oldLevel, levelFor(total));
454
582
  if (newLevel > doc.level) doc.level = newLevel;
455
583
 
584
+ const recoveries = this._recoveries;
456
585
  await this.save();
457
586
 
587
+ // A save that recovered a failed read replaced the document with the
588
+ // merged one. Report that, and compare with the merged level before
589
+ // this gain, so a level the saved player already had is not announced.
590
+ if (this._recoveries !== recoveries) {
591
+ total = xpOf(this._doc);
592
+ newLevel = Math.max(newLevel, levelOf(this._doc));
593
+ oldLevel = Math.max(oldLevel, this._savedLevel, levelFor(total - amount));
594
+ }
595
+ const leveledUp = newLevel > oldLevel;
596
+
458
597
  this._publish('xp_gained', { amount, reason, leveledUp, newLevel, total });
459
598
  if (leveledUp) {
460
599
  this._publish('level_up', { oldLevel, newLevel, totalXP: total });
@@ -1,4 +1,4 @@
1
- import { validate, checkDevices, hasOwn, VERSION } from './store.js';
1
+ import { validate, checkDevices, hasOwn, extraKeys, cap, clone, VERSION } from './store.js';
2
2
  import { isDay, trimDays } from './streaks.js';
3
3
 
4
4
  // Join two maps that are `depth` levels deep, taking the larger number at the
@@ -30,6 +30,28 @@ function joinAchievements(a, b) {
30
30
  return out;
31
31
  }
32
32
 
33
+ // Same text for the same value whatever the key order, so the choice below does
34
+ // not depend on which side a value came from.
35
+ const stable = (value) => {
36
+ if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`;
37
+ if (value !== null && typeof value === 'object') {
38
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stable(value[key])}`).join(',')}}`;
39
+ }
40
+ return JSON.stringify(value);
41
+ };
42
+
43
+ // A field the core does not know has no rule to join by. One side only: kept.
44
+ // Both: the larger number, else the larger text, the same in any order.
45
+ const larger = (a, b) => (Number.isFinite(a) && Number.isFinite(b) && a !== b ? a > b : stable(a) >= stable(b)) ? a : b;
46
+
47
+ function joinExtras(x, y, doc) {
48
+ for (const key of new Set([...extraKeys(x), ...extraKeys(y)])) {
49
+ const a = hasOwn(x, key) ? x[key] : undefined;
50
+ const b = hasOwn(y, key) ? y[key] : undefined;
51
+ doc[key] = a === undefined ? b : b === undefined ? a : larger(a, b);
52
+ }
53
+ }
54
+
33
55
  const positive = (a, b) => (a > 0 && b > 0 ? Math.min(a, b) : Math.max(a, b));
34
56
 
35
57
  /**
@@ -63,6 +85,99 @@ export function merge(a, b, options) {
63
85
  sumsBy: join(x.sumsBy, y.sumsBy, 2),
64
86
  achievements: joinAchievements(x.achievements, y.achievements)
65
87
  };
88
+ joinExtras(x, y, doc);
66
89
  checkDevices(doc);
67
90
  return doc;
68
91
  }
92
+
93
+ // Every counter map of a document by path, as a JSON array of keys.
94
+ function counterMaps(doc) {
95
+ const maps = new Map([[JSON.stringify(['xpBy']), doc.xpBy], [JSON.stringify(['xpSpentBy']), doc.xpSpentBy], [JSON.stringify(['gamesBy']), doc.gamesBy]]);
96
+ for (const activity of Object.keys(doc.playsBy)) maps.set(JSON.stringify(['playsBy', activity]), doc.playsBy[activity]);
97
+ for (const activity of Object.keys(doc.sumsBy)) {
98
+ for (const key of Object.keys(doc.sumsBy[activity])) {
99
+ maps.set(JSON.stringify(['sumsBy', activity, key]), doc.sumsBy[activity][key]);
100
+ }
101
+ }
102
+ return maps;
103
+ }
104
+
105
+ /** The device ids that hold a counter above zero. */
106
+ export function countedDevices(doc) {
107
+ const ids = new Set();
108
+ for (const map of counterMaps(doc).values()) {
109
+ for (const id in map) if (map[id] > 0) ids.add(id);
110
+ }
111
+ return ids;
112
+ }
113
+
114
+ /** This device's counters in a document, by path. */
115
+ export function ownCounters(doc, device) {
116
+ const out = new Map();
117
+ for (const [path, map] of counterMaps(doc)) {
118
+ if (hasOwn(map, device)) out.set(path, map[device]);
119
+ }
120
+ return out;
121
+ }
122
+
123
+ /** Add `by` (a path to amount map) to this device's counters in `doc`, in place. */
124
+ export function raiseOwn(doc, device, by) {
125
+ for (const [path, amount] of by) {
126
+ let node = doc;
127
+ for (const key of JSON.parse(path)) {
128
+ if (!hasOwn(node, key)) node[key] = {};
129
+ node = node[key];
130
+ }
131
+ node[device] = cap((hasOwn(node, device) ? node[device] : 0) + amount);
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Fold a session player into the saved one it could not read earlier. The
137
+ * session started empty, so its counters for this device are new progress and
138
+ * are added, not joined by max. Everything else joins like `merge`. The saved
139
+ * player keeps its name and its unknown fields. Pure.
140
+ *
141
+ * `base` holds what an import put into this device's session counters (path to
142
+ * amount, see `ownCounters`). That is not new progress, so it is joined by max
143
+ * with the saved counter, and only what the session added on top is added.
144
+ *
145
+ * @param {*} saved the player read from storage
146
+ * @param {*} session the player made since the failed read
147
+ * @param {string} device this device's id
148
+ * @param {{ today?: string, rewards?: Object }} [options] see validate
149
+ * @param {Map<string, number>} [base]
150
+ */
151
+ export function mergeSession(saved, session, device, options, base = new Map()) {
152
+ const x = validate(saved, options);
153
+ const y = validate(session, options);
154
+ const doc = merge(x, y, options);
155
+ doc.name = x.name;
156
+ for (const key of extraKeys(x)) doc[key] = x[key];
157
+
158
+ const mine = counterMaps(doc);
159
+ const was = counterMaps(x);
160
+ for (const [path, map] of counterMaps(y)) {
161
+ if (!hasOwn(map, device)) continue;
162
+ const imported = Math.min(base.get(path) ?? 0, map[device]);
163
+ const stored = was.has(path) && hasOwn(was.get(path), device) ? was.get(path)[device] : 0;
164
+ mine.get(path)[device] = cap(Math.max(stored, imported) + (map[device] - imported));
165
+ }
166
+ return doc;
167
+ }
168
+
169
+ /** A copy of a document with one device's entries moved under another id. */
170
+ export function rekey(doc, from, to) {
171
+ const out = clone(doc);
172
+ const move = (map) => {
173
+ if (!hasOwn(map, from)) return;
174
+ map[to] = hasOwn(map, to) ? Math.max(map[to], map[from]) : map[from];
175
+ delete map[from];
176
+ };
177
+ for (const map of [out.xpBy, out.xpSpentBy, out.gamesBy]) move(map);
178
+ for (const activity of Object.keys(out.playsBy)) move(out.playsBy[activity]);
179
+ for (const activity of Object.keys(out.sumsBy)) {
180
+ for (const key of Object.keys(out.sumsBy[activity])) move(out.sumsBy[activity][key]);
181
+ }
182
+ return out;
183
+ }