@usions/sdk 2.25.0 → 2.27.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 CHANGED
@@ -47,7 +47,13 @@ Usion.user.getToken() // Auth JWT
47
47
  Usion.user.getProfile() // Promise<{ id, name, avatar }>
48
48
  ```
49
49
 
50
- ### Storage (persistent, per-user, per-service)
50
+ ### Storage (durable, per-user, per-service)
51
+
52
+ `Usion.storage` is database-backed and survives logout, reinstall, and device
53
+ changes. Host local storage is an offline cache, not the source of truth.
54
+ Values written by SDK versions before 2.27 are imported once on the first
55
+ online storage call. Database acknowledgement is required before
56
+ `set`, `remove`, or `clear` resolves.
51
57
 
52
58
  ```javascript
53
59
  await Usion.storage.set('highscore', 1500)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usions/sdk",
3
- "version": "2.25.0",
3
+ "version": "2.27.0",
4
4
  "description": "Usion Mini App SDK for iframe games and services",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/src/browser.js CHANGED
@@ -191,7 +191,7 @@ var Usion = (function () {
191
191
  * Core Usion object with init, _post, _request
192
192
  */
193
193
  const core = {
194
- version: '2.25.0', // synced from package.json by scripts/sync-version.mjs
194
+ version: '2.27.0', // synced from package.json by scripts/sync-version.mjs
195
195
  config: {},
196
196
  _initialized: false,
197
197
  _initCallback: null,
@@ -618,67 +618,160 @@ var Usion = (function () {
618
618
  }
619
619
 
620
620
  /**
621
- * Usion SDK Storage Module — persistent storage (per-user, per-service)
621
+ * Usion SDK Storage Module — durable storage (per-user, per-service).
622
+ *
623
+ * The database `storage` scope is authoritative. Host-provided local storage
624
+ * remains a best-effort offline cache and a one-time migration source for
625
+ * values written by SDKs before 2.27.
622
626
  */
623
627
 
628
+ var DATA_PREFIX = '_d:';
629
+ var MIGRATION_KEY = '_migrated_v2';
630
+
631
+ function dbKey(key) {
632
+ return DATA_PREFIX + key;
633
+ }
634
+
635
+ function emit(Usion, event, extra) {
636
+ return Usion._backendEmit(event, Object.assign({
637
+ service_id: Usion.config && Usion.config.serviceId,
638
+ scope: 'storage',
639
+ }, extra));
640
+ }
641
+
642
+ function localGet(Usion, key) {
643
+ return Usion._request('STORAGE_GET', { key: key }).then(function (response) {
644
+ return response ? response.value : null;
645
+ });
646
+ }
647
+
648
+ function localSet(Usion, key, value) {
649
+ return Usion._request('STORAGE_SET', { key: key, value: value });
650
+ }
651
+
652
+ function localRemove(Usion, key) {
653
+ return Usion._request('STORAGE_REMOVE', { key: key });
654
+ }
655
+
656
+ function localKeys(Usion) {
657
+ return Usion._request('STORAGE_KEYS', {}).then(function (response) {
658
+ return (response && response.keys) || [];
659
+ });
660
+ }
661
+
662
+ function bestEffort(promise) {
663
+ return promise.catch(function () { return; });
664
+ }
665
+
624
666
  /**
625
667
  * @param {object} Usion - Reference to the main Usion object
626
668
  */
627
669
  function createStorageModule(Usion) {
670
+ var migrationPromise = null;
671
+
672
+ /**
673
+ * Import the complete legacy cache once, then persist a database sentinel.
674
+ * The sentinel prevents a removed database key from being recreated later
675
+ * by a stale device cache.
676
+ */
677
+ function ensureMigrated() {
678
+ if (migrationPromise) return migrationPromise;
679
+ migrationPromise = emit(Usion, 'kv:get', { key: MIGRATION_KEY }).then(function (result) {
680
+ if (result && result.exists && result.value === true) return;
681
+ return Promise.all([
682
+ emit(Usion, 'kv:keys', {}),
683
+ localKeys(Usion),
684
+ ]).then(function (results) {
685
+ var durableKeys = new Set((results[0] && results[0].keys) || []);
686
+ return Promise.all(results[1].map(function (key) {
687
+ var target = dbKey(key);
688
+ if (durableKeys.has(target)) return;
689
+ return localGet(Usion, key).then(function (legacyValue) {
690
+ if (legacyValue == null) return;
691
+ return emit(Usion, 'kv:set', { key: target, value: legacyValue });
692
+ });
693
+ }));
694
+ }).then(function () {
695
+ return emit(Usion, 'kv:set', { key: MIGRATION_KEY, value: true });
696
+ });
697
+ }).catch(function (error) {
698
+ migrationPromise = null;
699
+ throw error;
700
+ });
701
+ return migrationPromise;
702
+ }
703
+
628
704
  return {
629
705
  /**
630
- * Get a stored value
631
- * @param {string} key - Storage key
632
- * @returns {Promise<any>} Stored value or null
706
+ * Read from the database, falling back to the device cache only when the
707
+ * database is unavailable.
633
708
  */
634
- get: function(key) {
635
- return Usion._request('STORAGE_GET', { key: key }).then(function(response) {
636
- return response.value;
709
+ get: function (key) {
710
+ return ensureMigrated().then(function () {
711
+ return emit(Usion, 'kv:get', { key: dbKey(key) });
712
+ }).then(function (result) {
713
+ if (result && result.exists) {
714
+ return bestEffort(localSet(Usion, key, result.value)).then(function () {
715
+ return result.value;
716
+ });
717
+ }
718
+ // Absence after the migration sentinel is authoritative.
719
+ return bestEffort(localRemove(Usion, key)).then(function () {
720
+ return null;
721
+ });
722
+ }).catch(function (databaseError) {
723
+ return localGet(Usion, key).then(function (cachedValue) {
724
+ if (cachedValue != null) return cachedValue;
725
+ throw databaseError;
726
+ }, function () {
727
+ throw databaseError;
728
+ });
637
729
  });
638
730
  },
639
731
 
640
- /**
641
- * Set a stored value
642
- * @param {string} key - Storage key
643
- * @param {any} value - Value to store (will be JSON serialized)
644
- * @returns {Promise<void>}
645
- */
646
- set: function(key, value) {
647
- return Usion._request('STORAGE_SET', { key: key, value: value }).then(function() {
648
- return;
732
+ /** Persist to the database before refreshing the local cache. */
733
+ set: function (key, value) {
734
+ return ensureMigrated().then(function () {
735
+ return emit(Usion, 'kv:set', { key: dbKey(key), value: value });
736
+ }).then(function () {
737
+ return bestEffort(localSet(Usion, key, value));
649
738
  });
650
739
  },
651
740
 
652
- /**
653
- * Remove a stored value
654
- * @param {string} key - Storage key
655
- * @returns {Promise<void>}
656
- */
657
- remove: function(key) {
658
- return Usion._request('STORAGE_REMOVE', { key: key }).then(function() {
659
- return;
741
+ /** Delete from the database before evicting the local cache. */
742
+ remove: function (key) {
743
+ return ensureMigrated().then(function () {
744
+ return emit(Usion, 'kv:remove', { key: dbKey(key) });
745
+ }).then(function () {
746
+ return bestEffort(localRemove(Usion, key));
660
747
  });
661
748
  },
662
749
 
663
- /**
664
- * Clear all stored values for this service
665
- * @returns {Promise<void>}
666
- */
667
- clear: function() {
668
- return Usion._request('STORAGE_CLEAR', {}).then(function() {
669
- return;
750
+ /** Clear only the storage data namespace, preserving the migration guard. */
751
+ clear: function () {
752
+ return ensureMigrated().then(function () {
753
+ return emit(Usion, 'kv:clear', { prefix: DATA_PREFIX });
754
+ }).then(function () {
755
+ return bestEffort(Usion._request('STORAGE_CLEAR', {}));
670
756
  });
671
757
  },
672
758
 
673
- /**
674
- * Get all keys
675
- * @returns {Promise<string[]>}
676
- */
677
- keys: function() {
678
- return Usion._request('STORAGE_KEYS', {}).then(function(response) {
679
- return response.keys || [];
759
+ /** List durable keys; internal metadata is never exposed. */
760
+ keys: function () {
761
+ return ensureMigrated().then(function () {
762
+ return emit(Usion, 'kv:keys', {});
763
+ }).then(function (result) {
764
+ return ((result && result.keys) || []).filter(function (key) {
765
+ return key.indexOf(DATA_PREFIX) === 0;
766
+ }).map(function (key) {
767
+ return key.slice(DATA_PREFIX.length);
768
+ });
769
+ }).catch(function (databaseError) {
770
+ return localKeys(Usion).catch(function () {
771
+ throw databaseError;
772
+ });
680
773
  });
681
- }
774
+ },
682
775
  };
683
776
  }
684
777
 
@@ -2997,6 +3090,70 @@ var Usion = (function () {
2997
3090
  });
2998
3091
  };
2999
3092
 
3093
+ /**
3094
+ * Report a finished 2–8 player match to Game Center. Call ONCE from the host
3095
+ * (config.playerIds[0]) at match end; pass an EXPLICIT winnerId (never
3096
+ * inferred from scores).
3097
+ *
3098
+ * WHERE the result lands follows where the game was launched from:
3099
+ * • started in a GROUP CHAT → one ranked standings card in that group
3100
+ * (1-on-1 included — the group sees who beat who);
3101
+ * • anywhere else (GameTok / invite / matchmaking) → cards in the DMs:
3102
+ * "You beat Bob — 3 : 1" / "Bob beat you — 1 : 3" for 1-on-1, and a
3103
+ * standings card across the host↔guest DMs for 3–8 players.
3104
+ *
3105
+ * `standings` is how a 3+ player game declares the finishing ORDER (best
3106
+ * first). Pass it whenever there IS a ranking: it cannot be derived from
3107
+ * `scores`, because a high score wins in some games and a low one wins in
3108
+ * others. Accepts ids or {userId} objects. Omit for 1-on-1.
3109
+ *
3110
+ * result: { winnerId | draw, standings?, scores?, displayScore?, metric?,
3111
+ * matchId?, roomId? }. Returns Promise<{ ok, notified? }>. See
3112
+ * types/index.d.ts + the usion-app skill for the full contract.
3113
+ */
3114
+ game.reportResult = function(result, opts) {
3115
+ const self = this;
3116
+ result = result || {};
3117
+ opts = opts || {};
3118
+
3119
+ if (!result.draw && (typeof result.winnerId !== 'string' || !result.winnerId)) {
3120
+ return Promise.reject(new UsionError(
3121
+ ERROR_CODES.INVALID_INPUT,
3122
+ 'reportResult needs a winnerId (or draw: true)'));
3123
+ }
3124
+
3125
+ const roomId = result.roomId || self.roomId || (Usion.config && Usion.config.roomId) || null;
3126
+ if (!roomId) {
3127
+ return Promise.reject(new UsionError(
3128
+ ERROR_CODES.NO_ROOM, 'reportResult needs a room — join a game first'));
3129
+ }
3130
+
3131
+ // Normalize standings to a plain id array. The server drops anything that
3132
+ // isn't actually in the room, so a stray entry can't fabricate a player.
3133
+ let standings = null;
3134
+ if (Array.isArray(result.standings)) {
3135
+ standings = result.standings
3136
+ .map(function(e) {
3137
+ if (typeof e === 'string') return e;
3138
+ return (e && (e.userId || e.user_id)) || null;
3139
+ })
3140
+ .filter(function(id) { return typeof id === 'string' && id; });
3141
+ if (!standings.length) standings = null;
3142
+ }
3143
+
3144
+ return Usion._backendEmit('gc:match_result', {
3145
+ service_id: opts.serviceId || (Usion.config && Usion.config.serviceId),
3146
+ room_id: roomId,
3147
+ winner_id: result.draw ? null : result.winnerId,
3148
+ draw: !!result.draw,
3149
+ standings: standings,
3150
+ scores: (result.scores && typeof result.scores === 'object') ? result.scores : null,
3151
+ display_score: result.displayScore != null ? String(result.displayScore) : null,
3152
+ metric: result.metric != null ? String(result.metric) : null,
3153
+ match_id: result.matchId != null ? String(result.matchId) : null,
3154
+ });
3155
+ };
3156
+
3000
3157
  /**
3001
3158
  * Invite friends to play in your room — like asking for money, but for players.
3002
3159
  *
@@ -6167,8 +6324,9 @@ var Usion = (function () {
6167
6324
  /**
6168
6325
  * Usion SDK Cloud — server-persisted KV storage for mini-apps.
6169
6326
  *
6170
- * Unlike `Usion.storage` (device-local), cloud values live on the backend and
6171
- * survive reinstall / device switch. Enabled for every service, bounded by
6327
+ * `Usion.storage` has its own durable per-user database scope; `Usion.cloud`
6328
+ * exposes explicit per-user and shared app data. Cloud values survive
6329
+ * reinstall / device switch. Enabled for every service, bounded by
6172
6330
  * quotas (64 KB per value, 200 keys / 1 MB per bucket, 60 ops/min).
6173
6331
  * Rides the unified backend channel, so it works standalone AND embedded.
6174
6332
  *
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * Usion SDK Cloud — server-persisted KV storage for mini-apps.
3
3
  *
4
- * Unlike `Usion.storage` (device-local), cloud values live on the backend and
5
- * survive reinstall / device switch. Enabled for every service, bounded by
4
+ * `Usion.storage` has its own durable per-user database scope; `Usion.cloud`
5
+ * exposes explicit per-user and shared app data. Cloud values survive
6
+ * reinstall / device switch. Enabled for every service, bounded by
6
7
  * quotas (64 KB per value, 200 keys / 1 MB per bucket, 60 ops/min).
7
8
  * Rides the unified backend channel, so it works standalone AND embedded.
8
9
  *
@@ -68,7 +68,7 @@ export function isTrustedMessageSource(event) {
68
68
  * Core Usion object with init, _post, _request
69
69
  */
70
70
  export const core = {
71
- version: '2.25.0', // synced from package.json by scripts/sync-version.mjs
71
+ version: '2.27.0', // synced from package.json by scripts/sync-version.mjs
72
72
  config: {},
73
73
  _initialized: false,
74
74
  _initCallback: null,
@@ -530,6 +530,70 @@ export function applyGameMethods(game, Usion) {
530
530
  });
531
531
  };
532
532
 
533
+ /**
534
+ * Report a finished 2–8 player match to Game Center. Call ONCE from the host
535
+ * (config.playerIds[0]) at match end; pass an EXPLICIT winnerId (never
536
+ * inferred from scores).
537
+ *
538
+ * WHERE the result lands follows where the game was launched from:
539
+ * • started in a GROUP CHAT → one ranked standings card in that group
540
+ * (1-on-1 included — the group sees who beat who);
541
+ * • anywhere else (GameTok / invite / matchmaking) → cards in the DMs:
542
+ * "You beat Bob — 3 : 1" / "Bob beat you — 1 : 3" for 1-on-1, and a
543
+ * standings card across the host↔guest DMs for 3–8 players.
544
+ *
545
+ * `standings` is how a 3+ player game declares the finishing ORDER (best
546
+ * first). Pass it whenever there IS a ranking: it cannot be derived from
547
+ * `scores`, because a high score wins in some games and a low one wins in
548
+ * others. Accepts ids or {userId} objects. Omit for 1-on-1.
549
+ *
550
+ * result: { winnerId | draw, standings?, scores?, displayScore?, metric?,
551
+ * matchId?, roomId? }. Returns Promise<{ ok, notified? }>. See
552
+ * types/index.d.ts + the usion-app skill for the full contract.
553
+ */
554
+ game.reportResult = function(result, opts) {
555
+ const self = this;
556
+ result = result || {};
557
+ opts = opts || {};
558
+
559
+ if (!result.draw && (typeof result.winnerId !== 'string' || !result.winnerId)) {
560
+ return Promise.reject(new UsionError(
561
+ ERROR_CODES.INVALID_INPUT,
562
+ 'reportResult needs a winnerId (or draw: true)'));
563
+ }
564
+
565
+ const roomId = result.roomId || self.roomId || (Usion.config && Usion.config.roomId) || null;
566
+ if (!roomId) {
567
+ return Promise.reject(new UsionError(
568
+ ERROR_CODES.NO_ROOM, 'reportResult needs a room — join a game first'));
569
+ }
570
+
571
+ // Normalize standings to a plain id array. The server drops anything that
572
+ // isn't actually in the room, so a stray entry can't fabricate a player.
573
+ let standings = null;
574
+ if (Array.isArray(result.standings)) {
575
+ standings = result.standings
576
+ .map(function(e) {
577
+ if (typeof e === 'string') return e;
578
+ return (e && (e.userId || e.user_id)) || null;
579
+ })
580
+ .filter(function(id) { return typeof id === 'string' && id; });
581
+ if (!standings.length) standings = null;
582
+ }
583
+
584
+ return Usion._backendEmit('gc:match_result', {
585
+ service_id: opts.serviceId || (Usion.config && Usion.config.serviceId),
586
+ room_id: roomId,
587
+ winner_id: result.draw ? null : result.winnerId,
588
+ draw: !!result.draw,
589
+ standings: standings,
590
+ scores: (result.scores && typeof result.scores === 'object') ? result.scores : null,
591
+ display_score: result.displayScore != null ? String(result.displayScore) : null,
592
+ metric: result.metric != null ? String(result.metric) : null,
593
+ match_id: result.matchId != null ? String(result.matchId) : null,
594
+ });
595
+ };
596
+
533
597
  /**
534
598
  * Invite friends to play in your room — like asking for money, but for players.
535
599
  *
@@ -1,64 +1,157 @@
1
1
  /**
2
- * Usion SDK Storage Module — persistent storage (per-user, per-service)
2
+ * Usion SDK Storage Module — durable storage (per-user, per-service).
3
+ *
4
+ * The database `storage` scope is authoritative. Host-provided local storage
5
+ * remains a best-effort offline cache and a one-time migration source for
6
+ * values written by SDKs before 2.27.
3
7
  */
4
8
 
9
+ var DATA_PREFIX = '_d:';
10
+ var MIGRATION_KEY = '_migrated_v2';
11
+
12
+ function dbKey(key) {
13
+ return DATA_PREFIX + key;
14
+ }
15
+
16
+ function emit(Usion, event, extra) {
17
+ return Usion._backendEmit(event, Object.assign({
18
+ service_id: Usion.config && Usion.config.serviceId,
19
+ scope: 'storage',
20
+ }, extra));
21
+ }
22
+
23
+ function localGet(Usion, key) {
24
+ return Usion._request('STORAGE_GET', { key: key }).then(function (response) {
25
+ return response ? response.value : null;
26
+ });
27
+ }
28
+
29
+ function localSet(Usion, key, value) {
30
+ return Usion._request('STORAGE_SET', { key: key, value: value });
31
+ }
32
+
33
+ function localRemove(Usion, key) {
34
+ return Usion._request('STORAGE_REMOVE', { key: key });
35
+ }
36
+
37
+ function localKeys(Usion) {
38
+ return Usion._request('STORAGE_KEYS', {}).then(function (response) {
39
+ return (response && response.keys) || [];
40
+ });
41
+ }
42
+
43
+ function bestEffort(promise) {
44
+ return promise.catch(function () { return; });
45
+ }
46
+
5
47
  /**
6
48
  * @param {object} Usion - Reference to the main Usion object
7
49
  */
8
50
  export function createStorageModule(Usion) {
51
+ var migrationPromise = null;
52
+
53
+ /**
54
+ * Import the complete legacy cache once, then persist a database sentinel.
55
+ * The sentinel prevents a removed database key from being recreated later
56
+ * by a stale device cache.
57
+ */
58
+ function ensureMigrated() {
59
+ if (migrationPromise) return migrationPromise;
60
+ migrationPromise = emit(Usion, 'kv:get', { key: MIGRATION_KEY }).then(function (result) {
61
+ if (result && result.exists && result.value === true) return;
62
+ return Promise.all([
63
+ emit(Usion, 'kv:keys', {}),
64
+ localKeys(Usion),
65
+ ]).then(function (results) {
66
+ var durableKeys = new Set((results[0] && results[0].keys) || []);
67
+ return Promise.all(results[1].map(function (key) {
68
+ var target = dbKey(key);
69
+ if (durableKeys.has(target)) return;
70
+ return localGet(Usion, key).then(function (legacyValue) {
71
+ if (legacyValue == null) return;
72
+ return emit(Usion, 'kv:set', { key: target, value: legacyValue });
73
+ });
74
+ }));
75
+ }).then(function () {
76
+ return emit(Usion, 'kv:set', { key: MIGRATION_KEY, value: true });
77
+ });
78
+ }).catch(function (error) {
79
+ migrationPromise = null;
80
+ throw error;
81
+ });
82
+ return migrationPromise;
83
+ }
84
+
9
85
  return {
10
86
  /**
11
- * Get a stored value
12
- * @param {string} key - Storage key
13
- * @returns {Promise<any>} Stored value or null
87
+ * Read from the database, falling back to the device cache only when the
88
+ * database is unavailable.
14
89
  */
15
- get: function(key) {
16
- return Usion._request('STORAGE_GET', { key: key }).then(function(response) {
17
- return response.value;
90
+ get: function (key) {
91
+ return ensureMigrated().then(function () {
92
+ return emit(Usion, 'kv:get', { key: dbKey(key) });
93
+ }).then(function (result) {
94
+ if (result && result.exists) {
95
+ return bestEffort(localSet(Usion, key, result.value)).then(function () {
96
+ return result.value;
97
+ });
98
+ }
99
+ // Absence after the migration sentinel is authoritative.
100
+ return bestEffort(localRemove(Usion, key)).then(function () {
101
+ return null;
102
+ });
103
+ }).catch(function (databaseError) {
104
+ return localGet(Usion, key).then(function (cachedValue) {
105
+ if (cachedValue != null) return cachedValue;
106
+ throw databaseError;
107
+ }, function () {
108
+ throw databaseError;
109
+ });
18
110
  });
19
111
  },
20
112
 
21
- /**
22
- * Set a stored value
23
- * @param {string} key - Storage key
24
- * @param {any} value - Value to store (will be JSON serialized)
25
- * @returns {Promise<void>}
26
- */
27
- set: function(key, value) {
28
- return Usion._request('STORAGE_SET', { key: key, value: value }).then(function() {
29
- return;
113
+ /** Persist to the database before refreshing the local cache. */
114
+ set: function (key, value) {
115
+ return ensureMigrated().then(function () {
116
+ return emit(Usion, 'kv:set', { key: dbKey(key), value: value });
117
+ }).then(function () {
118
+ return bestEffort(localSet(Usion, key, value));
30
119
  });
31
120
  },
32
121
 
33
- /**
34
- * Remove a stored value
35
- * @param {string} key - Storage key
36
- * @returns {Promise<void>}
37
- */
38
- remove: function(key) {
39
- return Usion._request('STORAGE_REMOVE', { key: key }).then(function() {
40
- return;
122
+ /** Delete from the database before evicting the local cache. */
123
+ remove: function (key) {
124
+ return ensureMigrated().then(function () {
125
+ return emit(Usion, 'kv:remove', { key: dbKey(key) });
126
+ }).then(function () {
127
+ return bestEffort(localRemove(Usion, key));
41
128
  });
42
129
  },
43
130
 
44
- /**
45
- * Clear all stored values for this service
46
- * @returns {Promise<void>}
47
- */
48
- clear: function() {
49
- return Usion._request('STORAGE_CLEAR', {}).then(function() {
50
- return;
131
+ /** Clear only the storage data namespace, preserving the migration guard. */
132
+ clear: function () {
133
+ return ensureMigrated().then(function () {
134
+ return emit(Usion, 'kv:clear', { prefix: DATA_PREFIX });
135
+ }).then(function () {
136
+ return bestEffort(Usion._request('STORAGE_CLEAR', {}));
51
137
  });
52
138
  },
53
139
 
54
- /**
55
- * Get all keys
56
- * @returns {Promise<string[]>}
57
- */
58
- keys: function() {
59
- return Usion._request('STORAGE_KEYS', {}).then(function(response) {
60
- return response.keys || [];
140
+ /** List durable keys; internal metadata is never exposed. */
141
+ keys: function () {
142
+ return ensureMigrated().then(function () {
143
+ return emit(Usion, 'kv:keys', {});
144
+ }).then(function (result) {
145
+ return ((result && result.keys) || []).filter(function (key) {
146
+ return key.indexOf(DATA_PREFIX) === 0;
147
+ }).map(function (key) {
148
+ return key.slice(DATA_PREFIX.length);
149
+ });
150
+ }).catch(function (databaseError) {
151
+ return localKeys(Usion).catch(function () {
152
+ throw databaseError;
153
+ });
61
154
  });
62
- }
155
+ },
63
156
  };
64
157
  }
package/types/index.d.ts CHANGED
@@ -79,10 +79,15 @@ export interface UserModule {
79
79
  // ─── Storage ─────────────────────────────────────────────────────
80
80
 
81
81
  export interface StorageModule {
82
- get(key: string): Promise<any>;
82
+ /** Durable per-user/per-service read; device cache is an offline fallback. */
83
+ get(key: string): Promise<any | null>;
84
+ /** Resolves only after the database acknowledges the write. */
83
85
  set(key: string, value: any): Promise<void>;
86
+ /** Resolves only after the database acknowledges the delete. */
84
87
  remove(key: string): Promise<void>;
88
+ /** Clears only this service's durable storage scope for the current user. */
85
89
  clear(): Promise<void>;
90
+ /** Lists durable keys; SDK migration metadata is never returned. */
86
91
  keys(): Promise<string[]>;
87
92
  }
88
93
 
@@ -325,6 +330,39 @@ export interface GameInviteResult {
325
330
  invited: string[];
326
331
  }
327
332
 
333
+ /** Final result of a match, passed to game.reportResult(). */
334
+ export interface MatchResult {
335
+ /** userId of the winner. Required unless `draw` is true. */
336
+ winnerId?: string;
337
+ /** True when the match ended in a draw (no winner). */
338
+ draw?: boolean;
339
+ /** Final score per userId, e.g. `{ [alice]: 3, [bob]: 1 }`. Optional. */
340
+ scores?: Record<string, number>;
341
+ /** Game-authored score text for the card, e.g. "3 - 1". Optional. */
342
+ displayScore?: string;
343
+ /** Optional label for the score, e.g. "goals", "points", "time". */
344
+ metric?: string;
345
+ /**
346
+ * Finishing order for a 3+ player match, BEST FIRST — how the card ranks
347
+ * everyone. Pass it whenever there is a ranking: it cannot be derived from
348
+ * `scores`, since a high score wins in some games and a low one wins in
349
+ * others. Ids not in the room are ignored; anyone omitted is appended.
350
+ * Omit for 1-on-1. (SDK ≥ 2.27)
351
+ */
352
+ standings?: Array<string | { userId: string }>;
353
+ /** Optional idempotency key for this match (dedupes ack retries). */
354
+ matchId?: string;
355
+ /** Room to report for (defaults to the current room). */
356
+ roomId?: string;
357
+ }
358
+
359
+ /** Ack from game.reportResult(). */
360
+ export interface MatchResultAck {
361
+ ok: boolean;
362
+ /** How many participants were sent a Game Center card. */
363
+ notified?: number;
364
+ }
365
+
328
366
  /** Options for game.joinWorld(). */
329
367
  export interface JoinWorldOptions {
330
368
  /** Service to place into (defaults to the current service). */
@@ -439,6 +477,26 @@ export interface GameModule {
439
477
  requestRematch(): void;
440
478
  forfeit(): Promise<{ success: boolean; error?: string }>;
441
479
 
480
+ /**
481
+ * Report the final result of a finished 2–8 player match.
482
+ *
483
+ * WHERE the card lands follows where the game was launched from:
484
+ * - **Started in a group chat** → one ranked standings card posted into that
485
+ * group. Covers 1-on-1 too, so the group sees who beat who.
486
+ * - **Anywhere else** (GameTok / invite / matchmaking) → cards in the direct
487
+ * chats, written from each player's perspective ("You beat Bob — 3 : 1" /
488
+ * "Bob beat you — 1 : 3"). A 3–8 player match fans a standings card across
489
+ * the host↔guest DMs.
490
+ *
491
+ * Call ONCE, from the authoritative client only (your host,
492
+ * `config.playerIds[0]`), the moment the match ends. The backend re-checks
493
+ * that the players really shared this room, so a peer can't fabricate a
494
+ * result. Pass an EXPLICIT `winnerId` — Game Center never infers the winner
495
+ * from the scores, so lowest-wins and no-score games work identically, and
496
+ * pass `standings` for a 3+ player ranking. (SDK ≥ 2.26; `standings` ≥ 2.27)
497
+ */
498
+ reportResult(result: MatchResult, opts?: { serviceId?: string }): Promise<MatchResultAck>;
499
+
442
500
  /**
443
501
  * Invite friends to play in your room. Opens the host's friend/group picker
444
502
  * (recent chats + username search + your groups, multi-select); each pick gets