@usions/sdk 2.24.2 → 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.24.2",
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.24.2', // 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,
@@ -365,6 +365,15 @@ var Usion = (function () {
365
365
  self.bot._messageHandler(data.message);
366
366
  }
367
367
 
368
+ // Handle host tab navigation (hybrid tabbed services). Keep launchPath
369
+ // truthful so getLaunchParams().path always reflects the current tab.
370
+ if (data.type === 'HOST_NAVIGATE' && typeof data.path === 'string') {
371
+ if (self.config) self.config.launchPath = data.path;
372
+ if (self._hostNavigateCallback) {
373
+ self._hostNavigateCallback({ path: data.path, tab: data.tab || null });
374
+ }
375
+ }
376
+
368
377
  // Handle backend server-push events relayed by the host (embedded mode).
369
378
  if (data.type === 'BACKEND_EVENT' && data.event && self._backendHandlers) {
370
379
  const h = self._backendHandlers[data.event];
@@ -609,67 +618,160 @@ var Usion = (function () {
609
618
  }
610
619
 
611
620
  /**
612
- * 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.
613
626
  */
614
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
+
615
666
  /**
616
667
  * @param {object} Usion - Reference to the main Usion object
617
668
  */
618
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
+
619
704
  return {
620
705
  /**
621
- * Get a stored value
622
- * @param {string} key - Storage key
623
- * @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.
624
708
  */
625
- get: function(key) {
626
- return Usion._request('STORAGE_GET', { key: key }).then(function(response) {
627
- 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
+ });
628
729
  });
629
730
  },
630
731
 
631
- /**
632
- * Set a stored value
633
- * @param {string} key - Storage key
634
- * @param {any} value - Value to store (will be JSON serialized)
635
- * @returns {Promise<void>}
636
- */
637
- set: function(key, value) {
638
- return Usion._request('STORAGE_SET', { key: key, value: value }).then(function() {
639
- 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));
640
738
  });
641
739
  },
642
740
 
643
- /**
644
- * Remove a stored value
645
- * @param {string} key - Storage key
646
- * @returns {Promise<void>}
647
- */
648
- remove: function(key) {
649
- return Usion._request('STORAGE_REMOVE', { key: key }).then(function() {
650
- 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));
651
747
  });
652
748
  },
653
749
 
654
- /**
655
- * Clear all stored values for this service
656
- * @returns {Promise<void>}
657
- */
658
- clear: function() {
659
- return Usion._request('STORAGE_CLEAR', {}).then(function() {
660
- 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', {}));
661
756
  });
662
757
  },
663
758
 
664
- /**
665
- * Get all keys
666
- * @returns {Promise<string[]>}
667
- */
668
- keys: function() {
669
- return Usion._request('STORAGE_KEYS', {}).then(function(response) {
670
- 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
+ });
671
773
  });
672
- }
774
+ },
673
775
  };
674
776
  }
675
777
 
@@ -1140,6 +1242,73 @@ var Usion = (function () {
1140
1242
  };
1141
1243
  }
1142
1244
 
1245
+ /**
1246
+ * Usion SDK Host Tabs — hybrid tabbed services (SDK ≥ 2.25)
1247
+ *
1248
+ * A hybrid service registers `tabs`: the platform renders its native bot chat
1249
+ * as one tab and this app's own pages as the others, inside ONE persistent
1250
+ * iframe/WebView. These methods are the two-way bridge with that host screen:
1251
+ *
1252
+ * - Host → app: `onHostNavigate(cb)` receives tab switches as `{ path, tab }`.
1253
+ * Subscribing tells the host it can navigate in place; apps that never
1254
+ * subscribe get remounted with the new path as `getLaunchParams().path`.
1255
+ * - App → host: `openChat({ prefill })` jumps to the native chat tab with the
1256
+ * composer pre-filled (the user still presses send themselves), and
1257
+ * `reportPath(path)` keeps the host's tab highlight in sync when the user
1258
+ * navigates inside the app.
1259
+ */
1260
+
1261
+ function createHostTabsMethods(Usion) {
1262
+ return {
1263
+ /**
1264
+ * Subscribe to host tab navigation. Called when the user taps one of this
1265
+ * service's tabs in the host tab bar (or a deep link targets a tab).
1266
+ * Subscribing signals the host that this app navigates in place — without
1267
+ * a subscription the host reloads the app with the new launch path instead.
1268
+ * @param {function} callback - Called with { path, tab } (tab may be null)
1269
+ */
1270
+ onHostNavigate: function(callback) {
1271
+ Usion._hostNavigateCallback = callback;
1272
+ Usion._post({ type: 'HOST_NAVIGATE_SUBSCRIBED' });
1273
+ },
1274
+
1275
+ /**
1276
+ * Unsubscribe from host tab navigation (the host falls back to remounting
1277
+ * the app on the next tab switch).
1278
+ */
1279
+ offHostNavigate: function() {
1280
+ Usion._hostNavigateCallback = null;
1281
+ Usion._post({ type: 'HOST_NAVIGATE_UNSUBSCRIBED' });
1282
+ },
1283
+
1284
+ /**
1285
+ * Ask the host to switch to the native chat tab, optionally pre-filling
1286
+ * the message composer. The text is NEVER sent automatically — the user
1287
+ * reviews it and presses send. No-op outside a hybrid tabbed host screen.
1288
+ * @param {object} [opts]
1289
+ * @param {string} [opts.prefill] - Draft text for the chat composer
1290
+ */
1291
+ openChat: function(opts) {
1292
+ opts = opts || {};
1293
+ Usion._post({
1294
+ type: 'OPEN_CHAT_TAB',
1295
+ prefill: typeof opts.prefill === 'string' ? opts.prefill : undefined
1296
+ });
1297
+ },
1298
+
1299
+ /**
1300
+ * Report the app's current internal path so the host can keep its tab
1301
+ * highlight in sync with in-app navigation. Fire-and-forget; the host
1302
+ * never echoes a navigation back for a reported path.
1303
+ * @param {string} path - Current path inside the app (e.g. "/explore")
1304
+ */
1305
+ reportPath: function(path) {
1306
+ if (typeof path !== 'string' || !path) return;
1307
+ Usion._post({ type: 'TAB_CHANGED', path: path });
1308
+ }
1309
+ };
1310
+ }
1311
+
1143
1312
  /**
1144
1313
  * Usion SDK UI Utilities — DOM helpers for mini apps
1145
1314
  */
@@ -2921,6 +3090,70 @@ var Usion = (function () {
2921
3090
  });
2922
3091
  };
2923
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
+
2924
3157
  /**
2925
3158
  * Invite friends to play in your room — like asking for money, but for players.
2926
3159
  *
@@ -6091,8 +6324,9 @@ var Usion = (function () {
6091
6324
  /**
6092
6325
  * Usion SDK Cloud — server-persisted KV storage for mini-apps.
6093
6326
  *
6094
- * Unlike `Usion.storage` (device-local), cloud values live on the backend and
6095
- * 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
6096
6330
  * quotas (64 KB per value, 200 keys / 1 MB per bucket, 60 ops/min).
6097
6331
  * Rides the unified backend channel, so it works standalone AND embedded.
6098
6332
  *
@@ -6707,6 +6941,9 @@ var Usion = (function () {
6707
6941
  // Attach back button methods directly on Usion
6708
6942
  Object.assign(Usion, createBackButtonMethods(Usion));
6709
6943
 
6944
+ // Attach hybrid tabbed-service methods directly on Usion
6945
+ Object.assign(Usion, createHostTabsMethods(Usion));
6946
+
6710
6947
  // Attach UI utilities directly on Usion
6711
6948
  Object.assign(Usion, uiMethods);
6712
6949
 
@@ -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.24.2', // 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,
@@ -242,6 +242,15 @@ export const core = {
242
242
  self.bot._messageHandler(data.message);
243
243
  }
244
244
 
245
+ // Handle host tab navigation (hybrid tabbed services). Keep launchPath
246
+ // truthful so getLaunchParams().path always reflects the current tab.
247
+ if (data.type === 'HOST_NAVIGATE' && typeof data.path === 'string') {
248
+ if (self.config) self.config.launchPath = data.path;
249
+ if (self._hostNavigateCallback) {
250
+ self._hostNavigateCallback({ path: data.path, tab: data.tab || null });
251
+ }
252
+ }
253
+
245
254
  // Handle backend server-push events relayed by the host (embedded mode).
246
255
  if (data.type === 'BACKEND_EVENT' && data.event && self._backendHandlers) {
247
256
  const h = self._backendHandlers[data.event];
@@ -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
  *
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Usion SDK Host Tabs — hybrid tabbed services (SDK ≥ 2.25)
3
+ *
4
+ * A hybrid service registers `tabs`: the platform renders its native bot chat
5
+ * as one tab and this app's own pages as the others, inside ONE persistent
6
+ * iframe/WebView. These methods are the two-way bridge with that host screen:
7
+ *
8
+ * - Host → app: `onHostNavigate(cb)` receives tab switches as `{ path, tab }`.
9
+ * Subscribing tells the host it can navigate in place; apps that never
10
+ * subscribe get remounted with the new path as `getLaunchParams().path`.
11
+ * - App → host: `openChat({ prefill })` jumps to the native chat tab with the
12
+ * composer pre-filled (the user still presses send themselves), and
13
+ * `reportPath(path)` keeps the host's tab highlight in sync when the user
14
+ * navigates inside the app.
15
+ */
16
+
17
+ export function createHostTabsMethods(Usion) {
18
+ return {
19
+ /**
20
+ * Subscribe to host tab navigation. Called when the user taps one of this
21
+ * service's tabs in the host tab bar (or a deep link targets a tab).
22
+ * Subscribing signals the host that this app navigates in place — without
23
+ * a subscription the host reloads the app with the new launch path instead.
24
+ * @param {function} callback - Called with { path, tab } (tab may be null)
25
+ */
26
+ onHostNavigate: function(callback) {
27
+ Usion._hostNavigateCallback = callback;
28
+ Usion._post({ type: 'HOST_NAVIGATE_SUBSCRIBED' });
29
+ },
30
+
31
+ /**
32
+ * Unsubscribe from host tab navigation (the host falls back to remounting
33
+ * the app on the next tab switch).
34
+ */
35
+ offHostNavigate: function() {
36
+ Usion._hostNavigateCallback = null;
37
+ Usion._post({ type: 'HOST_NAVIGATE_UNSUBSCRIBED' });
38
+ },
39
+
40
+ /**
41
+ * Ask the host to switch to the native chat tab, optionally pre-filling
42
+ * the message composer. The text is NEVER sent automatically — the user
43
+ * reviews it and presses send. No-op outside a hybrid tabbed host screen.
44
+ * @param {object} [opts]
45
+ * @param {string} [opts.prefill] - Draft text for the chat composer
46
+ */
47
+ openChat: function(opts) {
48
+ opts = opts || {};
49
+ Usion._post({
50
+ type: 'OPEN_CHAT_TAB',
51
+ prefill: typeof opts.prefill === 'string' ? opts.prefill : undefined
52
+ });
53
+ },
54
+
55
+ /**
56
+ * Report the app's current internal path so the host can keep its tab
57
+ * highlight in sync with in-app navigation. Fire-and-forget; the host
58
+ * never echoes a navigation back for a reported path.
59
+ * @param {string} path - Current path inside the app (e.g. "/explore")
60
+ */
61
+ reportPath: function(path) {
62
+ if (typeof path !== 'string' || !path) return;
63
+ Usion._post({ type: 'TAB_CHANGED', path: path });
64
+ }
65
+ };
66
+ }
@@ -21,6 +21,7 @@ import { createChatModule } from './chat.js';
21
21
  import { createBotModule } from './bot.js';
22
22
  import { createResultsMethods } from './results.js';
23
23
  import { createBackButtonMethods } from './back-button.js';
24
+ import { createHostTabsMethods } from './host-tabs.js';
24
25
  import { uiMethods } from './ui.js';
25
26
  import { miscMethods } from './misc.js';
26
27
  import { createFileStorageModule } from './file-storage.js';
@@ -69,6 +70,9 @@ Object.assign(Usion, createResultsMethods(Usion));
69
70
  // Attach back button methods directly on Usion
70
71
  Object.assign(Usion, createBackButtonMethods(Usion));
71
72
 
73
+ // Attach hybrid tabbed-service methods directly on Usion
74
+ Object.assign(Usion, createHostTabsMethods(Usion));
75
+
72
76
  // Attach UI utilities directly on Usion
73
77
  Object.assign(Usion, uiMethods);
74
78
 
@@ -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
@@ -1071,6 +1129,29 @@ export interface UsionSDK {
1071
1129
  claimBackButton(callback: () => void): void;
1072
1130
  releaseBackButton(): void;
1073
1131
 
1132
+ // Hybrid tabbed services (SDK ≥ 2.25)
1133
+ /**
1134
+ * Subscribe to host tab navigation on a hybrid tabbed service. Called with
1135
+ * `{ path, tab }` when the user taps one of this service's tabs in the host
1136
+ * tab bar (or a deep link targets a tab). Subscribing signals the host that
1137
+ * the app navigates in place; apps that never subscribe are remounted with
1138
+ * the new path as `getLaunchParams().path` instead. (SDK ≥ 2.25)
1139
+ */
1140
+ onHostNavigate(callback: (nav: { path: string; tab: string | null }) => void): void;
1141
+ /** Unsubscribe from host tab navigation. (SDK ≥ 2.25) */
1142
+ offHostNavigate(): void;
1143
+ /**
1144
+ * Ask the host to switch to the native chat tab, optionally pre-filling the
1145
+ * message composer. The text is never sent automatically — the user reviews
1146
+ * it and presses send. No-op outside a hybrid tabbed host screen. (SDK ≥ 2.25)
1147
+ */
1148
+ openChat(opts?: { prefill?: string }): void;
1149
+ /**
1150
+ * Report the app's current internal path so the host keeps its tab highlight
1151
+ * in sync with in-app navigation. Fire-and-forget. (SDK ≥ 2.25)
1152
+ */
1153
+ reportPath(path: string): void;
1154
+
1074
1155
  // Download
1075
1156
  download(url: string, filename?: string): Promise<{ success?: boolean; error?: string }>;
1076
1157