@hypersoniclabs/helix-sdk 0.1.2 → 0.1.9

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.
Files changed (115) hide show
  1. package/README.md +859 -8
  2. package/dist/action-surface.d.ts +182 -0
  3. package/dist/action-surface.js +1032 -0
  4. package/dist/action-surface.js.map +1 -0
  5. package/dist/camera.d.ts +65 -1
  6. package/dist/camera.js +568 -0
  7. package/dist/camera.js.map +1 -1
  8. package/dist/dev-shell/criteria.d.ts +46 -0
  9. package/dist/dev-shell/criteria.js +98 -0
  10. package/dist/dev-shell/criteria.js.map +1 -0
  11. package/dist/dev-shell/index.d.ts +189 -0
  12. package/dist/dev-shell/index.js +287 -0
  13. package/dist/dev-shell/index.js.map +1 -0
  14. package/dist/dev-shell/keys.d.ts +14 -0
  15. package/dist/dev-shell/keys.js +78 -0
  16. package/dist/dev-shell/keys.js.map +1 -0
  17. package/dist/dev-shell/simulator.d.ts +436 -0
  18. package/dist/dev-shell/simulator.js +1634 -0
  19. package/dist/dev-shell/simulator.js.map +1 -0
  20. package/dist/dev-shell/state.d.ts +148 -0
  21. package/dist/dev-shell/state.js +196 -0
  22. package/dist/dev-shell/state.js.map +1 -0
  23. package/dist/device-definition-resolver.d.ts +34 -0
  24. package/dist/device-definition-resolver.js +172 -0
  25. package/dist/device-definition-resolver.js.map +1 -0
  26. package/dist/device-trial.d.ts +3 -0
  27. package/dist/device-trial.js +132 -0
  28. package/dist/device-trial.js.map +1 -0
  29. package/dist/devices.d.ts +228 -0
  30. package/dist/devices.js +198 -0
  31. package/dist/devices.js.map +1 -0
  32. package/dist/dreamerAudio.d.ts +126 -0
  33. package/dist/dreamerAudio.js +135 -0
  34. package/dist/dreamerAudio.js.map +1 -0
  35. package/dist/generated/runtime-contract.d.ts +15529 -0
  36. package/dist/generated/runtime-contract.js +20470 -0
  37. package/dist/generated/runtime-contract.js.map +1 -0
  38. package/dist/index.d.ts +272 -15
  39. package/dist/index.js +1401 -91
  40. package/dist/index.js.map +1 -1
  41. package/dist/interaction-mode.d.ts +172 -0
  42. package/dist/interaction-mode.js +553 -0
  43. package/dist/interaction-mode.js.map +1 -0
  44. package/dist/internal/avatar-pose.d.ts +25 -0
  45. package/dist/internal/avatar-pose.js +46 -0
  46. package/dist/internal/avatar-pose.js.map +1 -0
  47. package/dist/internal/keyed-collection.d.ts +2 -0
  48. package/dist/internal/keyed-collection.js +12 -0
  49. package/dist/internal/keyed-collection.js.map +1 -0
  50. package/dist/internal/vehicle-detach-action.d.ts +2 -0
  51. package/dist/internal/vehicle-detach-action.js +6 -0
  52. package/dist/internal/vehicle-detach-action.js.map +1 -0
  53. package/dist/matchmaking.d.ts +433 -0
  54. package/dist/matchmaking.js +1487 -0
  55. package/dist/matchmaking.js.map +1 -0
  56. package/dist/materials.d.ts +122 -0
  57. package/dist/materials.js +217 -0
  58. package/dist/materials.js.map +1 -0
  59. package/dist/multiplayer-accessors.d.ts +100 -0
  60. package/dist/multiplayer-accessors.js +200 -0
  61. package/dist/multiplayer-accessors.js.map +1 -0
  62. package/dist/multiplayer-contract/avatar-pose.d.ts +112 -0
  63. package/dist/multiplayer-contract/avatar-pose.js +250 -0
  64. package/dist/multiplayer-contract/avatar-pose.js.map +1 -0
  65. package/dist/multiplayer-contract/credential.d.ts +38 -0
  66. package/dist/multiplayer-contract/final-rest.d.ts +66 -0
  67. package/dist/multiplayer-contract/final-rest.js +38 -0
  68. package/dist/multiplayer-contract/final-rest.js.map +1 -0
  69. package/dist/multiplayer-contract/index.d.ts +11 -5
  70. package/dist/multiplayer-contract/index.js +16 -5
  71. package/dist/multiplayer-contract/index.js.map +1 -1
  72. package/dist/multiplayer-contract/messages.d.ts +461 -14
  73. package/dist/multiplayer-contract/messages.js +141 -15
  74. package/dist/multiplayer-contract/messages.js.map +1 -1
  75. package/dist/multiplayer-contract/room.d.ts +55 -4
  76. package/dist/multiplayer-contract/state.d.ts +181 -1
  77. package/dist/multiplayer-contract/state.js.map +1 -1
  78. package/dist/multiplayer-final-rest.d.ts +32 -0
  79. package/dist/multiplayer-final-rest.js +217 -0
  80. package/dist/multiplayer-final-rest.js.map +1 -0
  81. package/dist/multiplayer.d.ts +507 -16
  82. package/dist/multiplayer.js +2242 -73
  83. package/dist/multiplayer.js.map +1 -1
  84. package/dist/package.json +3 -0
  85. package/dist/protocol.d.ts +668 -5
  86. package/dist/protocol.js +101 -1
  87. package/dist/protocol.js.map +1 -1
  88. package/dist/runtime-contract/index.d.ts +15 -0
  89. package/dist/runtime-contract/index.js +12 -0
  90. package/dist/runtime-contract/index.js.map +1 -0
  91. package/dist/server-clock.d.ts +25 -0
  92. package/dist/server-clock.js +88 -0
  93. package/dist/server-clock.js.map +1 -0
  94. package/dist/tsconfig.build.tsbuildinfo +1 -1
  95. package/dist/universal-vehicles.d.ts +111 -0
  96. package/dist/universal-vehicles.js +2 -0
  97. package/dist/universal-vehicles.js.map +1 -0
  98. package/dist/vault.d.ts +562 -0
  99. package/dist/vault.js +365 -0
  100. package/dist/vault.js.map +1 -0
  101. package/dist/vehicle-specialty-placement.d.ts +28 -0
  102. package/dist/vehicle-specialty-placement.js +154 -0
  103. package/dist/vehicle-specialty-placement.js.map +1 -0
  104. package/dist/vehicle-specialty-transport.d.ts +78 -0
  105. package/dist/vehicle-specialty-transport.js +183 -0
  106. package/dist/vehicle-specialty-transport.js.map +1 -0
  107. package/dist/voice.d.ts +229 -0
  108. package/dist/voice.js +1348 -0
  109. package/dist/voice.js.map +1 -0
  110. package/generated/runtime-contract/helix-runtime-contract.json +13332 -0
  111. package/generated/runtime-contract/known-answer.json +20471 -0
  112. package/generated/runtime-contract/known-answer.schema.json +630 -0
  113. package/generated/runtime-contract/runtime-contract.schema.json +607 -0
  114. package/generated/runtime-contract/unreal/HelixRuntimeContract.generated.h +908 -0
  115. package/package.json +32 -6
package/dist/index.js CHANGED
@@ -1,17 +1,79 @@
1
- import { isShellMessage, PROTOCOL_VERSION, } from './protocol';
2
- import { HelixMultiplayer } from './multiplayer';
3
- import { captureCanvas } from './camera';
4
- export { cropRectForAspect, captureCanvas } from './camera';
1
+ import { isShellMessage, PROTOCOL_VERSION, PURCHASE_STATUS_MEANING, normalizeRuntimeFidelityIntent, XR_INTERACTION_PROMPT_EVENT, XR_SESSION_EVENT, } from './protocol.js';
2
+ import { normalizeDeviceTrialSpawn } from './device-trial.js';
3
+ import { HelixMultiplayer } from './multiplayer.js';
4
+ import { HelixVoice } from './voice.js';
5
+ import { HelixMatchmaking, HelixParty } from './matchmaking.js';
6
+ import { ServerClock } from './server-clock.js';
7
+ import { captureCanvas, cameraCapabilityGate, cloneCameraCapability, cloneCameraState, defaultCameraCapability, defaultCameraState, intersectCameraCapability, normalizeCameraCapability, normalizeCameraState, validateCameraControl, } from './camera.js';
8
+ import { createMaterialsNamespace } from './materials.js';
9
+ export { WorldDeviceHost, deviceRuntimeModuleId as worldDeviceRuntimeModuleId, } from './devices.js';
10
+ export { createSealedDeviceDefinitionResolver, normalizeSealedDeviceDefinitionProjection, } from './device-definition-resolver.js';
11
+ export { normalizeDeviceTrialSpawn } from './device-trial.js';
12
+ export { CAMERA_LENS_PRESETS, RUNTIME_FIDELITY_VERSION, RUNTIME_FIDELITY_VISUAL_TIERS, RUNTIME_FIDELITY_RENDER_SCALES, RUNTIME_PROFILE_QUALITIES, normalizeRuntimeFidelityIntent, XR_INTERACTION_PROMPT_EVENT, XR_SESSION_EVENT, } from './protocol.js';
13
+ export { cropRectForAspect, captureCanvas, CAMERA_MIN_ZOOM, CAMERA_MAX_ZOOM, clampCameraZoom, nearestLensPreset, defaultCameraCapability, defaultCameraState, cloneCameraState, cloneCameraCapability, intersectCameraCapability, CAMERA_CAPABILITY_FLAGS, normalizeCameraCapability, normalizeCameraState, validateCameraControl, cameraCapabilityGate, isCameraSessionState, isCameraMediaMode, isCameraSpatialMode, isCameraControlTarget, isCameraFilterId, isCameraTimerSeconds, isCameraDroneLockMode, } from './camera.js';
14
+ export { createMaterialLibrary, createMaterialsNamespace, DEFAULT_MATERIAL_PACK_SLUG, } from './materials.js';
15
+ export { HelixRoomJoinError } from './multiplayer.js';
16
+ export { HelixMatchmakingError, HelixPartyError } from './matchmaking.js';
17
+ export { DEFAULT_PUSH_TO_TALK_KEY } from './voice.js';
18
+ export { createVarsView, createRoomAccessors, createModuleAccessors } from './multiplayer-accessors.js';
19
+ export { createVaultClient, createVaultLoadPlan, VAULT_ASSET_KINDS, VaultApiError, VaultArtifactUnavailableError, VaultCapabilityUnavailableError, VaultChecksumMismatchError, VaultUnsupportedRuntimeError, } from './vault.js';
20
+ export { createDreamerAudioClient, DREAMER_AUDIO_TIMEOUT_MS, DreamerAudioApiError, DreamerAudioCapabilityUnavailableError, DreamerAudioJobFailedError, DreamerAudioJobTimeoutError, DreamerAudioVaultUnavailableError, } from './dreamerAudio.js';
21
+ // Portable interaction takeover. The concrete character/input adapter lives in
22
+ // @helix/humanoid-character; this module intentionally carries no engine dependency.
23
+ export { ANY_VERB, ModeStack, bindStackSafety, normaliseTouch, validateInputMap, } from './interaction-mode.js';
24
+ // Universal action presentation. Authority resolves expressions, options, and
25
+ // permissions before producing a snapshot; this component renders that cache
26
+ // and consumes the same semantic takeover actions as every other mode.
27
+ export { UniversalActionSurface, createActionSurfaceInputMap, createActionSurfaceMode, validateActionSurfaceSnapshot, } from './action-surface.js';
5
28
  // The multiplayer wire contract. Re-exported here so `@hypersoniclabs/helix-sdk` root consumers (and
6
29
  // classic node-resolution type imports, e.g. the backend minting RoomCredentialClaims) get it; bundler
7
30
  // consumers that want only the contract import the lighter '@hypersoniclabs/helix-sdk/multiplayer-contract'.
8
- export * from './multiplayer-contract';
9
- // Statuses where the player ends up owning the thing.
10
- const COMPLETED_STATUSES = new Set([
11
- 'Granted',
12
- 'Claimed',
13
- 'AlreadyOwned',
14
- ]);
31
+ export * from './multiplayer-contract/index.js';
32
+ export * from './vehicle-specialty-transport.js';
33
+ export * from './vehicle-specialty-placement.js';
34
+ // Both sets are derived from the mirrored meaning map, so they stay total over PurchaseStatus by
35
+ // construction. completed = ownership (deliberately WIDER than the backend's "money settled" —
36
+ // AlreadyOwned means the player has it, which is what a world gates on); unresolved = money 'unknown'
37
+ // (the attempt may still charge, so its idempotency key must be reused, never re-minted).
38
+ const statusesWhere = (pick) => new Set(Object.keys(PURCHASE_STATUS_MEANING).filter((s) => pick(PURCHASE_STATUS_MEANING[s])));
39
+ const COMPLETED_STATUSES = statusesWhere((m) => m.ownsAfter);
40
+ const UNRESOLVED_PURCHASE_STATUSES = statusesWhere((m) => m.money === 'unknown');
41
+ // SYNC OBLIGATION: the shell's LOCAL concurrency refusal, produced at exactly one site
42
+ // (helixgame.com/components/iwp/helix-world-frame.tsx, the pendingResolve guard). It resolves without
43
+ // ever posting to the backend, so it is no answer about the attempt named by the key — recognising it
44
+ // (rather than re-implementing the shell's rule here) is what keeps the two repos from diverging.
45
+ const SHELL_CONCURRENT_PURCHASE_REASON = 'A purchase is already in progress';
46
+ const PURCHASE_ATTEMPTS_STORAGE_KEY = 'helix:iwp-purchase-attempts:v1';
47
+ // Raw database ids and legacy item: refs are deliberately not world-facing.
48
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
49
+ const CANONICAL_PURCHASE_REF = /^(pkey|dkey|distribution|listing):[^:]+$/;
50
+ // One spelling rule shared by buy, context, and recovery. Bare authored keys
51
+ // become pkey: refs; every other route must name a narrow canonical capability.
52
+ const productRef = (keyOrRef) => {
53
+ if (UUID_RE.test(keyOrRef)) {
54
+ throw new Error('Helix: raw item ids are not valid purchase references');
55
+ }
56
+ const ref = keyOrRef.includes(':') ? keyOrRef : `pkey:${keyOrRef}`;
57
+ if (!CANONICAL_PURCHASE_REF.test(ref)) {
58
+ throw new Error('Helix: purchase refs must use pkey:, dkey:, distribution:, or listing:');
59
+ }
60
+ return ref;
61
+ };
62
+ /**
63
+ * A shell-mediated request that failed. `code` classifies it when the shell could —
64
+ * `'version-conflict'` (an optimistic-concurrency clash), `'rate-limited'`, or a Data Store
65
+ * key-policy rule such as `'session-sub-key'` — so a world branches on the code instead of
66
+ * matching error prose. Undefined when the shell is older than the code it would have sent,
67
+ * or the failure has no classification.
68
+ */
69
+ export class HelixRequestError extends Error {
70
+ code;
71
+ constructor(message, code) {
72
+ super(message);
73
+ this.name = 'HelixRequestError';
74
+ this.code = code;
75
+ }
76
+ }
15
77
  const INIT_TIMEOUT_MS = 8000; // re-post helix:ready up to this long before falling back to standalone — a cold shell (Next route compile) can take >3s to mount its frame + reply
16
78
  const READY_RETRY_MS = 200; // re-post helix:ready this often until the shell answers (handshake race — see waitForInit)
17
79
  const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
@@ -22,10 +84,172 @@ const REQUEST_TIMEOUT_MS = 30 * 1000;
22
84
  // A photo upload (encode + multipart POST to R2) is slower than a read; give it
23
85
  // its own budget, shorter than the confirm-popup login window.
24
86
  const UPLOAD_TIMEOUT_MS = 60 * 1000;
87
+ // Biggest leaderboard page the backend serves; checked here so an oversized ask
88
+ // fails immediately instead of on a 400.
89
+ const MAX_LEADERBOARD_LIMIT = 100;
90
+ // Preview mode (no shell) degrades to neutral values by design — display data must never break the
91
+ // world loop. One warning per method per page makes that degradation audible without spamming a
92
+ // render loop; module-level, so it is per page rather than per SDK instance.
93
+ const warnedPreview = new Set();
94
+ // These three drop a WRITE on the floor, which is what turns "I verified persistence in preview"
95
+ // into a false positive — they say so louder than the neutral reads.
96
+ const SILENT_WRITE_METHODS = new Set([
97
+ 'dataStore.set',
98
+ 'dataStore.delete',
99
+ 'inventory.equipItem',
100
+ ]);
101
+ // The emote wheel's slot vocabulary, so a row the platform reports outside it is dropped rather than
102
+ // typed as an EquippedEmote it is not. Mirrors the contract's EmoteEntry['slot'] (and the room's
103
+ // EMOTE_SLOTS) — widen all three together.
104
+ const EMOTE_WHEEL_SLOTS = ['r0', 'r1', 'r2', 'r3', 'r4', 'r5', 'r6', 'r7', 'sit', 'lie'];
105
+ const customizerRecord = (value) => (value !== null && typeof value === 'object' && !Array.isArray(value));
106
+ const customizerString = (value) => (typeof value === 'string' && value.length > 0 && value.length <= 2048);
107
+ const customizerNullableString = (value) => (value === null || typeof value === 'string');
108
+ const customizerAssetUrl = (value) => {
109
+ if (value === null)
110
+ return true;
111
+ if (typeof value !== 'string')
112
+ return false;
113
+ try {
114
+ const url = new URL(value);
115
+ return url.protocol === 'https:' && url.hostname.length > 0 && !url.username && !url.password;
116
+ }
117
+ catch {
118
+ return false;
119
+ }
120
+ };
121
+ function freezeCustomizerValue(value) {
122
+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
123
+ for (const child of Object.values(value))
124
+ freezeCustomizerValue(child);
125
+ Object.freeze(value);
126
+ }
127
+ return value;
128
+ }
129
+ function normalizePackageCustomizerSource(session) {
130
+ const trial = session?.trial;
131
+ const spawnedItem = trial?.spawnedItem;
132
+ if (trial?.kind !== 'vehicle' ||
133
+ !customizerString(trial.id) ||
134
+ !customizerString(trial.itemId) ||
135
+ spawnedItem?.trial !== true ||
136
+ spawnedItem.kind !== 'vehicle' ||
137
+ spawnedItem.placementId !== trial.id ||
138
+ spawnedItem.instanceId !== trial.id ||
139
+ spawnedItem.itemId !== trial.itemId) {
140
+ return null;
141
+ }
142
+ return Object.freeze({ kind: 'trial', hostId: trial.id, itemId: trial.itemId });
143
+ }
144
+ function normalizePackageCustomizerSubject(session, source) {
145
+ const trial = session?.trial;
146
+ const spawnedItem = trial?.spawnedItem;
147
+ const value = spawnedItem?.customizerSubject;
148
+ if (source === null ||
149
+ trial?.kind !== 'vehicle' ||
150
+ !Number.isFinite(trial.expiresAt) ||
151
+ trial.expiresAt <= Date.now() / 1000 ||
152
+ spawnedItem?.trial !== true ||
153
+ spawnedItem.kind !== 'vehicle' ||
154
+ spawnedItem.canCustomize !== false ||
155
+ !customizerRecord(value) ||
156
+ value.kind !== 'package' ||
157
+ value.hostKind !== 'vehicle' ||
158
+ value.hostId !== source.hostId ||
159
+ !customizerString(value.packageId) ||
160
+ !customizerString(value.version) ||
161
+ !Array.isArray(value.renditions) ||
162
+ value.renditions.length === 0 ||
163
+ value.renditions.length > 64 ||
164
+ !customizerRecord(value.board) ||
165
+ !customizerString(value.board.id) ||
166
+ !customizerRecord(value.assignments) ||
167
+ Object.keys(value.assignments).length > 512 ||
168
+ !Object.values(value.assignments).every(customizerNullableString) ||
169
+ (value.hiddenSlotIds !== undefined && (!Array.isArray(value.hiddenSlotIds) ||
170
+ value.hiddenSlotIds.length > 512 ||
171
+ !value.hiddenSlotIds.every(customizerString))) ||
172
+ !customizerRecord(value.equipBoard)) {
173
+ return null;
174
+ }
175
+ if (!value.renditions.every((rendition) => (customizerRecord(rendition) &&
176
+ customizerString(rendition.id) &&
177
+ typeof rendition.url === 'string' &&
178
+ customizerAssetUrl(rendition.url)))) {
179
+ return null;
180
+ }
181
+ const board = value.equipBoard;
182
+ if (board.itemId !== source.itemId ||
183
+ board.hostKind !== 'vehicle' ||
184
+ !customizerString(board.title) ||
185
+ !customizerAssetUrl(board.modelUrl) ||
186
+ !customizerAssetUrl(board.thumbnailUrl) ||
187
+ !customizerAssetUrl(board.instanceThumbnailUrl) ||
188
+ !Array.isArray(board.slots) ||
189
+ board.slots.length > 512 ||
190
+ !Array.isArray(board.owned) ||
191
+ board.owned.length > 2048 ||
192
+ !Array.isArray(board.shop) ||
193
+ board.shop.length !== 0 ||
194
+ !customizerRecord(board.appearance) ||
195
+ !Array.isArray(board.appearance.hiddenSlotIds) ||
196
+ !board.appearance.hiddenSlotIds.every(customizerString)) {
197
+ return null;
198
+ }
199
+ const renderable = (row) => (customizerAssetUrl(row.modelUrl) &&
200
+ customizerAssetUrl(row.thumbnailUrl) &&
201
+ Array.isArray(row.ops) &&
202
+ customizerString(row.title) &&
203
+ customizerString(row.inventoryItemId) &&
204
+ customizerString(row.itemId));
205
+ if (!board.owned.every((row) => (customizerRecord(row) && renderable(row) && customizerString(row.slotType)))) {
206
+ return null;
207
+ }
208
+ if (!board.slots.every((slot) => (customizerRecord(slot) &&
209
+ customizerString(slot.instanceId) &&
210
+ customizerString(slot.slotType) &&
211
+ customizerString(slot.title) &&
212
+ typeof slot.category === 'string' &&
213
+ (slot.fill === 'all' || slot.fill === 'each') &&
214
+ (slot.exclusiveWith === undefined || (Array.isArray(slot.exclusiveWith) && slot.exclusiveWith.every(customizerString))) &&
215
+ (slot.installed === null || (customizerRecord(slot.installed) && renderable(slot.installed)))))) {
216
+ return null;
217
+ }
218
+ const slots = new Set(board.slots.map((slot) => slot.instanceId));
219
+ const choices = new Set(board.owned.map((row) => row.inventoryItemId));
220
+ if (!Object.entries(value.assignments).every(([slot, choice]) => (slots.has(slot) && (choice === null || choices.has(choice)))) ||
221
+ !(value.hiddenSlotIds ?? []).every((slot) => slots.has(slot))) {
222
+ return null;
223
+ }
224
+ try {
225
+ const normalized = JSON.parse(JSON.stringify({
226
+ kind: 'package',
227
+ hostKind: 'vehicle',
228
+ hostId: value.hostId,
229
+ packageId: value.packageId,
230
+ version: value.version,
231
+ renditions: value.renditions,
232
+ board: value.board,
233
+ assignments: value.assignments,
234
+ ...(value.hiddenSlotIds === undefined ? {} : { hiddenSlotIds: value.hiddenSlotIds }),
235
+ equipBoard: value.equipBoard,
236
+ }));
237
+ return freezeCustomizerValue(normalized);
238
+ }
239
+ catch {
240
+ return null;
241
+ }
242
+ }
25
243
  class HelixSdk {
26
244
  shellOrigin = null;
27
245
  session = null;
28
- world = null;
246
+ worldContext = null;
247
+ runtimeFidelityIntent = null;
248
+ customizerSubject = null;
249
+ customizerSource = null;
250
+ deviceTrialSpawn = null;
251
+ // Shell-provided multiplayer join target (helix:init instanceId — the play URL's ?instance=).
252
+ requestedInstanceId = null;
29
253
  initialized = false;
30
254
  listeners = new Set();
31
255
  debugEnabled = false;
@@ -36,7 +260,60 @@ class HelixSdk {
36
260
  pendingRequests = new Map();
37
261
  balanceListeners = new Set();
38
262
  inventoryListeners = new Set();
263
+ entitlementListeners = new Set();
39
264
  avatarListeners = new Set();
265
+ emoteListeners = new Set();
266
+ deviceState = { open: false };
267
+ deviceListeners = new Set();
268
+ deviceGlobalShortcutEnabled = true;
269
+ // The native avatar camera. The shell owns the state (helix:camera-state); the runtime
270
+ // owns what is POSSIBLE. Those are kept as two separate facts and combined, rather than
271
+ // one field the last writer wins: a shell push replacing the runtime's report outright
272
+ // would let one message promote an all-false runtime to all-true and re-open the local
273
+ // gate in front of a rig that does not exist. The runtime's report is a ceiling the
274
+ // shell can only lower — see intersectCameraCapability.
275
+ //
276
+ // `cameraShellCapability` stays null until the first push, so a runtime that has
277
+ // reported is gated on its own answer alone rather than on an all-false shell default
278
+ // it has never actually been sent.
279
+ cameraState = defaultCameraState();
280
+ cameraRuntimeCapability = defaultCameraCapability();
281
+ cameraShellCapability = null;
282
+ cameraListeners = new Set();
283
+ autoPurchaseAttempts = new Map();
284
+ // The shell said the player left this world (helix:leave) — see hasLeft().
285
+ left = false;
286
+ leaveListeners = new Set();
287
+ /** Code-free default material packs resolved from their platform CDN base. */
288
+ materials = createMaterialsNamespace();
289
+ /** Authoritative owned item instances currently standing in this World. */
290
+ world = {
291
+ getSpawns: async () => {
292
+ this.assertInitialized();
293
+ const worldId = this.worldContext?.id;
294
+ if (!worldId) {
295
+ throw new HelixRequestError('Helix.world.getSpawns: no active World context', 'UNAVAILABLE');
296
+ }
297
+ const token = this.session?.token ?? null;
298
+ const apiBase = this.multiplayer.resolveApiBase(token);
299
+ if (!apiBase) {
300
+ throw new HelixRequestError('Helix.world.getSpawns: cannot resolve the platform API', 'UNAVAILABLE');
301
+ }
302
+ const response = await fetch(`${apiBase}/api/v1/worlds/${encodeURIComponent(worldId)}/spawned-items`, {
303
+ headers: token ? { authorization: `Bearer ${token}` } : undefined,
304
+ cache: 'no-store',
305
+ });
306
+ if (!response.ok) {
307
+ throw new HelixRequestError(`Helix.world.getSpawns: platform returned HTTP ${response.status}`, 'UNAVAILABLE');
308
+ }
309
+ const body = (await response.json());
310
+ const spawns = body?.items ?? body?.data;
311
+ if (!Array.isArray(spawns)) {
312
+ throw new HelixRequestError('Helix.world.getSpawns: platform returned an invalid collection', 'CORRECTION_REQUIRED');
313
+ }
314
+ return spawns;
315
+ },
316
+ };
40
317
  // Performs the shell handshake. Call once at world start, before any other
41
318
  // Helix API. Resolves with embedded=false if no shell answers (local dev).
42
319
  async init() {
@@ -48,15 +325,59 @@ class HelixSdk {
48
325
  await this.waitForInit();
49
326
  }
50
327
  this.initialized = true;
328
+ // A world that subscribed to matchmaking / party events before init resolved is served from here.
329
+ // Both are no-ops without a subscriber.
330
+ this.matchmaking.ready();
331
+ this.party.ready();
332
+ this.attachXrSessionBridge();
51
333
  return this.snapshot();
52
334
  }
335
+ // The platform's clock as this page has learned it (server-clock.ts): fed by the joined room's clock and by
336
+ // the platform's answers, read by every matchmaking / party expiry judgement. Holds no timer and sends nothing.
337
+ serverClock = new ServerClock();
53
338
  // Multiplayer (pillar D): Helix.multiplayer.joinRoom(). Reads the world_session token + world id off
54
339
  // this singleton; the heavy Colyseus client is dynamically imported only on join.
55
340
  multiplayer = new HelixMultiplayer({
341
+ clock: this.serverClock,
342
+ isInitialized: () => this.initialized,
343
+ getToken: () => this.session?.token ?? null,
344
+ getWorldId: () => this.worldContext?.id ?? null,
345
+ getInstanceId: () => this.requestedInstanceId,
346
+ // Live room status → the shell (tablet Server Details panel). No-op when not embedded.
347
+ publishRoomState: (state) => void this.postToShell({ type: 'helix:multiplayer-state', state }),
348
+ // Strict instance-join failure → the shell (play page "server unavailable" modal). No-op when not embedded.
349
+ publishInstanceJoinError: (instanceId, message) => void this.postToShell({ type: 'helix:multiplayer-join-error', instanceId, message }),
350
+ // Room hops (switchRoom): voice is paired to a room instance, so it is handed off around the hop.
351
+ // (The explicit return type breaks the multiplayer ⇄ voice field-initializer inference cycle.)
352
+ detachVoice: () => this.voice.detachForRoomSwitch(),
353
+ // After the shell's leave, joinRoom() / switchRoom() reject `left` (see hasLeft()).
354
+ hasLeft: () => this.left,
355
+ });
356
+ // Voice chat (LiveKit): Helix.voice.join() after multiplayer.joinRoom(). The heavy livekit-client
357
+ // is dynamically imported only when a world actually joins voice (the same golden rule as Colyseus).
358
+ voice = new HelixVoice({
56
359
  isInitialized: () => this.initialized,
57
360
  getToken: () => this.session?.token ?? null,
58
- getWorldId: () => this.world?.id ?? null,
361
+ getWorldId: () => this.worldContext?.id ?? null,
362
+ getRoomId: () => this.multiplayer.currentRoomId(),
363
+ resolveApiBase: (token) => this.multiplayer.resolveApiBase(token),
364
+ // Live voice status → the shell (tablet voice controls + roster chips). No-op when not embedded.
365
+ publishVoiceState: (state) => void this.postToShell({ type: 'helix:voice-state', state }),
366
+ // Live mic meter (~10 Hz while captured) → the tablet's input-sensitivity meter.
367
+ publishVoiceLevel: (level) => void this.postToShell({ type: 'helix:voice-level', level }),
59
368
  });
369
+ // Matchmaking queues and parties (SPEC-U3 v1): direct platform calls with the world session, driven by
370
+ // polling. Both are inert until a world calls them — no timer, no listener, no request.
371
+ socialHost = {
372
+ isInitialized: () => this.initialized,
373
+ getToken: () => this.session?.token ?? null,
374
+ getWorldId: () => this.worldContext?.id ?? null,
375
+ getUserId: () => this.session?.user.id ?? null,
376
+ resolveApiBase: (token) => this.multiplayer.resolveApiBase(token),
377
+ clock: this.serverClock,
378
+ };
379
+ party = new HelixParty(this.socialHost);
380
+ matchmaking = new HelixMatchmaking(this.socialHost, this.party);
60
381
  // Debug surface. A world's own console lives in its cross-origin iframe — invisible to DevTools / an
61
382
  // automation harness attached to the shell, and to teammates without that frame selected. debug.log feeds
62
383
  // a bounded ring an in-world overlay can render (onLog/recent), and — when the shell enabled debug
@@ -72,6 +393,23 @@ class HelixSdk {
72
393
  },
73
394
  recent: () => this.debugRing.slice(),
74
395
  };
396
+ /** Live, read-only access to the current trial customizer projection. */
397
+ customizer = {
398
+ getContext: () => {
399
+ this.assertInitialized();
400
+ return this.currentCustomizerContext();
401
+ },
402
+ };
403
+ /** Live, read-only access to the authenticated session's ephemeral Device trial. */
404
+ trial = {
405
+ getDeviceSpawn: () => {
406
+ this.assertInitialized();
407
+ if (this.deviceTrialSpawn && Date.now() >= this.deviceTrialSpawn.expiresAt * 1_000) {
408
+ this.deviceTrialSpawn = null;
409
+ }
410
+ return this.deviceTrialSpawn;
411
+ },
412
+ };
75
413
  auth = {
76
414
  getUser: async () => {
77
415
  this.assertInitialized();
@@ -126,32 +464,95 @@ class HelixSdk {
126
464
  notification: (title, message) => this.notify.show({ kind: 'notification', title, message }),
127
465
  message: (title, message) => this.notify.show({ kind: 'message', title, message }),
128
466
  };
467
+ // Each call also mirrors the prompt into the world document as XR_INTERACTION_PROMPT_EVENT, so the
468
+ // engine's XR module can draw it in-scene during an immersive session (the shell's DOM prompt is not
469
+ // visible inside a headset). The mirror is document-local and runs embedded or standalone; the
470
+ // shell post and the return value are exactly what they were before it existed.
129
471
  prompts = {
130
472
  set: (prompt) => {
131
473
  this.assertInitialized();
132
- return this.postToShell({ type: 'helix:set-interaction-prompt', prompt });
474
+ const posted = this.postToShell({ type: 'helix:set-interaction-prompt', prompt });
475
+ if (prompt && typeof prompt.id === 'string' && typeof prompt.title === 'string') {
476
+ publishInteractionPromptSignal({
477
+ id: prompt.id,
478
+ label: prompt.title,
479
+ ...(prompt.state !== undefined ? { state: prompt.state } : {}),
480
+ });
481
+ }
482
+ return posted;
133
483
  },
134
484
  clear: (promptId) => {
135
485
  this.assertInitialized();
136
- return this.postToShell({ type: 'helix:clear-interaction-prompt', promptId });
486
+ const posted = this.postToShell({ type: 'helix:clear-interaction-prompt', promptId });
487
+ // A targeted clear only withdraws the mirrored prompt when it names the one on display.
488
+ if (promptId === undefined || storedInteractionPromptId() === promptId) {
489
+ publishInteractionPromptSignal(null);
490
+ }
491
+ return posted;
137
492
  },
138
493
  };
139
494
  device = {
140
495
  openTablet: () => this.openDevice('tablet'),
141
496
  openPhone: () => this.openDevice('phone'),
497
+ /**
498
+ * Enable or disable the SDK-owned Tab shortcut. Enabled by default.
499
+ * An earlier key handler may override one event with `preventDefault()`; a World-level
500
+ * window handler registered after `Helix.init()` should disable this shortcut instead.
501
+ */
502
+ setGlobalShortcutEnabled: (enabled) => {
503
+ this.deviceGlobalShortcutEnabled = enabled;
504
+ },
505
+ getState: () => ({ ...this.deviceState }),
506
+ onStateChanged: (cb) => {
507
+ this.deviceListeners.add(cb);
508
+ return () => this.deviceListeners.delete(cb);
509
+ },
142
510
  };
143
511
  // World-scoped session token for direct platform API calls (used by later
144
512
  // SDK modules; exposed for advanced cases). Null when unauthenticated.
145
513
  getSessionToken() {
146
514
  return this.session?.token ?? null;
147
515
  }
516
+ /**
517
+ * True once the player has left this world: the shell's Exit button, the browser's Back off the play page,
518
+ * and, for some worlds, the play page being unloaded (all reach the SDK as helix:leave). From then on the SDK leaves the
519
+ * room and voice, matchmaking and parties stop, and `Helix.multiplayer.joinRoom()` / `switchRoom()` reject
520
+ * with code `left` — whether or not the world held a room when the leave came. A world that runs its own
521
+ * room lifecycle (bot matches, its own rejoin retries) checks this before it rejoins.
522
+ *
523
+ * It stays true for the rest of this world document. The shell never re-enters a world in the same
524
+ * document: entering again is a new iframe document, so a new SDK instance and a new helix:init, which
525
+ * starts at false. The one way the same document comes back is a back/forward-cache restore of the play
526
+ * page (the page is shown again without a new handshake); then this is false again and rooms can be joined.
527
+ *
528
+ * Only the shell that initialised this world can end it: a helix:leave that arrives before helix:init (or
529
+ * from another origin) does not count.
530
+ */
531
+ hasLeft() {
532
+ return this.left;
533
+ }
534
+ /**
535
+ * Called once, synchronously, when the player leaves this world (see hasLeft(), which is already true by
536
+ * then). A subscriber registered after the leave is not called; read hasLeft() instead. Returns an
537
+ * unsubscribe function. A throwing subscriber is logged and does not stop the others. The subscribers are
538
+ * taken as a snapshot when the leave arrives: unsubscribing another one from inside a callback does not
539
+ * stop it being called for this leave.
540
+ */
541
+ onLeave(cb) {
542
+ this.leaveListeners.add(cb);
543
+ return () => {
544
+ this.leaveListeners.delete(cb);
545
+ };
546
+ }
148
547
  // ─────────────────────────── wallet ───────────────────────────
149
548
  wallet = {
150
549
  // The player's current LIX + Coins balances.
151
550
  getBalance: async () => {
152
551
  this.assertInitialized();
153
- if (!this.shellOrigin)
552
+ if (!this.shellOrigin) {
553
+ this.notePreview('wallet.getBalance');
154
554
  return { lix: 0, coins: 0 };
555
+ }
155
556
  return this.request('wallet.getBalance');
156
557
  },
157
558
  // Fires after the wallet changes (e.g. a purchase settles). Returns an
@@ -161,27 +562,143 @@ class HelixSdk {
161
562
  return () => this.balanceListeners.delete(cb);
162
563
  },
163
564
  };
565
+ // ─────────────────────────── listen ───────────────────────────
566
+ //
567
+ // Account-bound listen host admission. These are HOST-runtime actions available ONLY to the
568
+ // `listen` authority profile (a player-owned host); `client`/`preview` cannot call them. The
569
+ // player host holds no account JWT and no session capability — both stay in the shell, which
570
+ // performs the backend call. The host passes the joiner's single-use join token + a per-peer
571
+ // connection id and admits the connection ONLY on a correlated `admitted:true` that carries the
572
+ // joiner's real HELIX user id (`joinerUserId` — fail closed when an admitted receipt omits it).
573
+ listen = {
574
+ // Admit one joiner's single-use listen_join token against the host's session.
575
+ consume: async (sessionId, listenJoinToken, connectionId) => {
576
+ this.assertInitialized();
577
+ return this.request('listen.consume', {
578
+ sessionId,
579
+ listenJoinToken,
580
+ connectionId,
581
+ });
582
+ },
583
+ // Report one admitted peer's departure (host-side peer disconnect) and free its seat. The
584
+ // shell authenticates the OWNING host and calls the canonical backend disconnect route.
585
+ release: async (sessionId, seatId, connectionId) => {
586
+ this.assertInitialized();
587
+ return this.request('listen.release', {
588
+ sessionId,
589
+ seatId,
590
+ connectionId,
591
+ });
592
+ },
593
+ // Session-level liveness for the host's listen session.
594
+ heartbeat: async (sessionId) => {
595
+ this.assertInitialized();
596
+ return this.request('listen.heartbeat', { sessionId });
597
+ },
598
+ // Close the host's listen session (host departure closes the world; no migration).
599
+ close: async (sessionId) => {
600
+ this.assertInitialized();
601
+ return this.request('listen.close', { sessionId });
602
+ },
603
+ };
164
604
  // ────────────────────────── marketplace ──────────────────────────
165
605
  marketplace = {
166
- // Request a server-settled purchase of a marketplace (catalog) item. The
167
- // shell raises the confirm popup and settles; the world reacts to the result.
168
- purchaseItem: (itemId) => this.purchase(`item:${itemId}`),
169
- // Request a server-settled purchase of a product registered on the world.
170
- purchaseProduct: (productId) => this.purchase(productId),
606
+ // Request a world-local product by its stable creator key. Internal product
607
+ // UUIDs are not world-facing purchase references.
608
+ purchaseProduct: (productKey, options) => this.purchase(productRef(productKey), options),
609
+ // Request the stable world distribution key registered for THIS world.
610
+ // The shell binds dkey to the active world and owns Claim/Buy confirmation.
611
+ purchaseDistributionKey: (key, options) => this.purchase(`dkey:${key}`, options),
612
+ // Feature one exact active public primary distribution from any creator.
613
+ purchaseDistribution: (distributionId, options) => this.purchase(`distribution:${distributionId}`, options),
614
+ // Feature one exact active secondary Collectible listing. Listings name one
615
+ // immutable serial, so quantity is always 1.
616
+ purchaseListing: (listingId, options) => this.purchase(`listing:${listingId}`, { ...options, quantity: options?.quantity ?? 1 }),
617
+ // Re-read a purchase this world already started, by the key it supplied. The recovery path when
618
+ // the tab reloaded or the response was lost mid-settle; the shell has always routed it.
619
+ // PASS `ref` — the same product string the purchase used. Without it the answer is bound only to
620
+ // (key, player, world), so a key that settled for one product answers for any other. It takes the
621
+ // `purchaseProduct` spelling (a bare authored key becomes `pkey:`), or one
622
+ // of the canonical dkey:/distribution:/listing: spellings.
623
+ getPurchase: async (idempotencyKey, ref) => {
624
+ this.assertInitialized();
625
+ if (!this.shellOrigin) {
626
+ this.notePreview('marketplace.getPurchase');
627
+ return null;
628
+ }
629
+ const normalizedRef = ref ? productRef(ref) : undefined;
630
+ const raw = await this.request('iwp.getPurchase', { idempotencyKey, ...(normalizedRef ? { ref: normalizedRef } : {}) });
631
+ if (!raw)
632
+ return null;
633
+ const result = this.settlePurchaseResult(raw);
634
+ if (!UNRESOLVED_PURCHASE_STATUSES.has(result.status)) {
635
+ this.clearAutoPurchaseAttempt(idempotencyKey);
636
+ }
637
+ return result;
638
+ },
171
639
  // Browse marketplace listings.
172
640
  getListings: async (query) => {
173
641
  this.assertInitialized();
174
- if (!this.shellOrigin)
642
+ if (!this.shellOrigin) {
643
+ this.notePreview('marketplace.getListings');
175
644
  return [];
645
+ }
176
646
  return this.request('marketplace.getListings', query ?? {});
177
647
  },
178
648
  // Product/listing + the player's live balance + eligibility, in one call —
179
649
  // for building a custom confirm UI (the built-in popup uses this internally).
180
- getPurchaseContext: async (ref) => {
650
+ getPurchaseContext: async (ref, options) => {
181
651
  this.assertInitialized();
182
- if (!this.shellOrigin)
652
+ if (!this.shellOrigin) {
653
+ this.notePreview('marketplace.getPurchaseContext');
183
654
  return null;
184
- return this.request('iwp.getContext', { ref });
655
+ }
656
+ return this.request('iwp.getContext', {
657
+ ref: productRef(ref),
658
+ quantity: this.purchaseQuantity(options),
659
+ });
660
+ },
661
+ };
662
+ // ────────────────────────── purchases (entitlements) ──────────────────────────
663
+ //
664
+ // What fulfilment granted THIS player in THIS world: passes, named balances, owned counts —
665
+ // server-held, backend-written. The read and the spend ride the shell's world-session token, so
666
+ // no payload here names a world or player; a world can never forge an entitlement, and spending
667
+ // goes through the server's atomic floor-at-zero consume, never a client-side counter.
668
+ purchases = {
669
+ // The player's entitlements. Preview mode (no shell) resolves empty — display data must never
670
+ // break the world loop; a real backend failure still rejects rather than fabricating an empty.
671
+ getEntitlements: async () => {
672
+ this.assertInitialized();
673
+ if (!this.shellOrigin) {
674
+ this.notePreview('purchases.getEntitlements');
675
+ return { v: 1, passes: {}, balances: {}, owned: {} };
676
+ }
677
+ return this.request('iwp.getEntitlements', {});
678
+ },
679
+ // Spend `amount` of a named balance. Server-atomic and idempotent per attempt: the SDK mints
680
+ // one opId per call, so a shell/network retry of THIS call can never double-spend, while a new
681
+ // call is a genuinely new spend. `applied: false` + 'insufficient' = balance left untouched.
682
+ consume: async (code, amount) => {
683
+ this.assertInitialized();
684
+ if (!this.shellOrigin) {
685
+ this.notePreview('purchases.consume');
686
+ return { applied: false, balance: 0, reason: 'insufficient' };
687
+ }
688
+ return this.request('iwp.consumeEntitlement', {
689
+ code,
690
+ amount,
691
+ opId: `op-${this.newId()}`,
692
+ });
693
+ },
694
+ // Same recovery read as marketplace.getPurchase — here so purchase-flow code can live entirely
695
+ // under one namespace.
696
+ getPurchase: (idempotencyKey, ref) => this.marketplace.getPurchase(idempotencyKey, ref),
697
+ // Fires after the shell settles a purchase that changed this player's entitlements. No
698
+ // payload — re-read with getEntitlements(). Returns an unsubscribe fn.
699
+ onEntitlementsChanged: (cb) => {
700
+ this.entitlementListeners.add(cb);
701
+ return () => this.entitlementListeners.delete(cb);
185
702
  },
186
703
  };
187
704
  analytics = {
@@ -193,28 +710,36 @@ class HelixSdk {
193
710
  // worlds and creators (universal items) — the basis for VIP / season passes.
194
711
  hasItem: async (itemId) => {
195
712
  this.assertInitialized();
196
- if (!this.shellOrigin)
713
+ if (!this.shellOrigin) {
714
+ this.notePreview('inventory.hasItem');
197
715
  return false;
716
+ }
198
717
  return this.request('inventory.hasItem', { itemId });
199
718
  },
200
719
  getQuantity: async (itemId) => {
201
720
  this.assertInitialized();
202
- if (!this.shellOrigin)
721
+ if (!this.shellOrigin) {
722
+ this.notePreview('inventory.getQuantity');
203
723
  return 0;
724
+ }
204
725
  return this.request('inventory.getQuantity', { itemId });
205
726
  },
206
727
  // All items the current player owns.
207
728
  getMyItems: async () => {
208
729
  this.assertInitialized();
209
- if (!this.shellOrigin)
730
+ if (!this.shellOrigin) {
731
+ this.notePreview('inventory.getMyItems');
210
732
  return [];
733
+ }
211
734
  return this.request('inventory.getMyItems');
212
735
  },
213
736
  // Equip an owned cosmetic item (visual).
214
737
  equipItem: async (itemId) => {
215
738
  this.assertInitialized();
216
- if (!this.shellOrigin)
739
+ if (!this.shellOrigin) {
740
+ this.notePreview('inventory.equipItem');
217
741
  return;
742
+ }
218
743
  await this.request('inventory.equipItem', { itemId });
219
744
  },
220
745
  onInventoryChanged: (cb) => {
@@ -224,42 +749,152 @@ class HelixSdk {
224
749
  };
225
750
  // Durable, per-world key–value storage (the Roblox DataStore analog). The
226
751
  // right place for anything that must survive a session: player progress,
227
- // settings, world state. Scoped to THIS world; namespace per-player data
228
- // yourself (e.g. `player:${userId}`). Value-bearing writes should be made
229
- // server-authoritatively. Free for every world (quotas + write rate limits
752
+ // settings, world state. Scoped to THIS world.
753
+ //
754
+ // A player's own session may write exactly ONE key: `player:${user.id}`. Put the
755
+ // whole save in that one JSON document — sub-keys, world-global keys and room state
756
+ // are written by the game server, and a session write outside that key is refused
757
+ // with a 403 naming the rule. Free for every world (quotas + write rate limits
230
758
  // apply). See https://docs3.helixgame.com/docs/platform-api/data-store
231
759
  dataStore = {
232
760
  // Read a durable value by key. Returns null if unset (or in preview mode,
233
761
  // when the world is opened directly with no shell).
234
762
  get: async (key) => {
235
763
  this.assertInitialized();
236
- if (!this.shellOrigin)
764
+ if (!this.shellOrigin) {
765
+ this.notePreview('dataStore.get');
237
766
  return null;
767
+ }
238
768
  return this.request('dataStore.get', { key });
239
769
  },
770
+ // Read a value WITH its version, for optimistic concurrency: pass the version
771
+ // back to set() and the write is refused if anything changed meanwhile. Null if
772
+ // unset (or in preview mode).
773
+ getEntry: async (key) => {
774
+ this.assertInitialized();
775
+ if (!this.shellOrigin) {
776
+ this.notePreview('dataStore.getEntry');
777
+ return null;
778
+ }
779
+ return this.request('dataStore.getEntry', { key });
780
+ },
240
781
  // Create or overwrite a durable value. No-op in preview mode (read-only).
241
- // Subject to the world's free-tier quotas and write rate limit; a rejected
242
- // write surfaces as a thrown error (e.g. RateLimited / quota exceeded).
243
- set: async (key, value) => {
782
+ // Subject to the world's quotas and write rate limit: a value may be at most
783
+ // 256 KB, and each player's session gets 30 writes/min — its slice of the world's
784
+ // shared 600/min budget (shared with every other player and the room). A rejected
785
+ // write throws a HelixRequestError — code 'rate-limited' when throttled. Pass
786
+ // `expectedVersion` (from getEntry) to make the write conditional — a losing race
787
+ // rejects with code 'version-conflict' instead of silently clobbering. Pass 0 to
788
+ // assert create-only.
789
+ set: async (key, value, options) => {
244
790
  this.assertInitialized();
245
- if (!this.shellOrigin)
791
+ if (!this.shellOrigin) {
792
+ this.notePreview('dataStore.set');
246
793
  return;
247
- await this.request('dataStore.set', { key, value });
794
+ }
795
+ await this.request('dataStore.set', {
796
+ key,
797
+ value,
798
+ expectedVersion: options?.expectedVersion,
799
+ });
248
800
  },
249
- // Remove a durable value by key. No-op in preview mode.
250
- delete: async (key) => {
801
+ // Remove a durable value by key. No-op in preview mode. Accepts the same
802
+ // `expectedVersion` guard as set(), and counts against the same write rate
803
+ // limit as set() (the player's 30/min slice of the world's 600/min).
804
+ delete: async (key, options) => {
251
805
  this.assertInitialized();
252
- if (!this.shellOrigin)
806
+ if (!this.shellOrigin) {
807
+ this.notePreview('dataStore.delete');
253
808
  return;
254
- await this.request('dataStore.delete', { key });
809
+ }
810
+ await this.request('dataStore.delete', {
811
+ key,
812
+ expectedVersion: options?.expectedVersion,
813
+ });
255
814
  },
256
- // List stored keys, optionally filtered by prefix (e.g. `player:`). Returns
257
- // keys only (fetch values with get), mirroring Roblox ListKeysAsync.
258
- list: async (prefix) => {
815
+ // List stored keys, optionally filtered by prefix (e.g. `player:`). Keys only —
816
+ // values are never returned in bulk, so read each one with get/getEntry.
817
+ // ONE call = ONE backend request returning up to 100 keys: when the result carries
818
+ // a `nextCursor`, pass it back as `opts.cursor` to read the next page.
819
+ list: async (prefix, opts) => {
259
820
  this.assertInitialized();
260
- if (!this.shellOrigin)
261
- return [];
262
- return this.request('dataStore.list', { prefix });
821
+ if (!this.shellOrigin) {
822
+ this.notePreview('dataStore.list');
823
+ return { keys: [] };
824
+ }
825
+ const payload = {
826
+ prefix,
827
+ cursor: opts?.cursor,
828
+ limit: opts?.limit,
829
+ };
830
+ return this.request('dataStore.list', payload);
831
+ },
832
+ };
833
+ // Per-world ranked score boards. A session always submits for ITSELF — the backend
834
+ // takes the subject from the world-session token, so a client cannot score for another
835
+ // player; scores players must not write are submitted by the game server instead.
836
+ // Needs a shell: in preview mode both calls reject rather than fake a board.
837
+ leaderboard = {
838
+ // Submit this player's score to `board`, resolving the score that now stands for them and whether this submission
839
+ // replaced it. `order` declares which direction wins ('desc' = higher is better); a board's shape (order/size) is fixed
840
+ // at creation — a session submit can never reshape an existing board, only the manifest-declared (room/creator) lane can.
841
+ submit: async (board, score, options) => {
842
+ this.assertInitialized();
843
+ assertBoardName(board, 'submit');
844
+ if (typeof score !== 'number' || !Number.isFinite(score)) {
845
+ throw new Error('Helix.leaderboard.submit: score must be a finite number');
846
+ }
847
+ return this.request('leaderboard.submit', {
848
+ board,
849
+ score,
850
+ order: options?.order,
851
+ });
852
+ },
853
+ // Read the ranked head of `board` (the backend's default page size when `limit`
854
+ // is omitted). `truncated` is true when the board holds more than the page.
855
+ top: async (board, options) => {
856
+ this.assertInitialized();
857
+ assertBoardName(board, 'top');
858
+ const limit = options?.limit;
859
+ if (limit !== undefined &&
860
+ (!Number.isInteger(limit) || limit < 1 || limit > MAX_LEADERBOARD_LIMIT)) {
861
+ throw new Error(`Helix.leaderboard.top: limit must be an integer between 1 and ${MAX_LEADERBOARD_LIMIT}`);
862
+ }
863
+ return this.request('leaderboard.top', {
864
+ board,
865
+ limit,
866
+ order: options?.order,
867
+ });
868
+ },
869
+ };
870
+ // This world's achievements and whether the viewer has earned them — read-only.
871
+ // Awarding is server-side only (write-time criteria, or the room's awardAchievement
872
+ // rule), so there is no award/claim method here by design.
873
+ //
874
+ // World-scoped: the shell supplies the world id, so a world can never enumerate the
875
+ // viewer's earns elsewhere. A hidden achievement they have NOT earned arrives with its
876
+ // name + description redacted by the shell.
877
+ achievements = {
878
+ // Every achievement registered to this world, with the viewer's earned flags and
879
+ // tally. Preview mode (no shell) resolves neutral empties: this is display data, so
880
+ // it must never break the world loop.
881
+ list: async () => {
882
+ this.assertInitialized();
883
+ if (!this.shellOrigin) {
884
+ this.notePreview('achievements.list');
885
+ return { achievements: [], total: 0, earned: 0 };
886
+ }
887
+ return this.request('achievements.list', {});
888
+ },
889
+ // Only the ones the viewer has earned in this world. Empty for a signed-out player
890
+ // (they have earned nothing) and in preview mode.
891
+ mine: async () => {
892
+ this.assertInitialized();
893
+ if (!this.shellOrigin) {
894
+ this.notePreview('achievements.mine');
895
+ return { achievements: [] };
896
+ }
897
+ return this.request('achievements.mine', {});
263
898
  },
264
899
  };
265
900
  // ─────────────────────────── camera ───────────────────────────
@@ -291,18 +926,115 @@ class HelixSdk {
291
926
  // the world manifest; a missing scope rejects.
292
927
  savePhoto: async (image, meta) => {
293
928
  this.assertInitialized();
294
- if (!this.shellOrigin)
929
+ if (!this.shellOrigin) {
930
+ this.notePreview('camera.savePhoto');
295
931
  return null;
932
+ }
296
933
  const { bytes, contentType } = await toBytes(image, meta?.contentType);
297
934
  return this.request('camera.savePhoto', { bytes, contentType, caption: meta?.caption, aspect: meta?.aspect ?? 'free' }, UPLOAD_TIMEOUT_MS);
298
935
  },
936
+ // ── native avatar camera: control ──
937
+ //
938
+ // Everything above is the album pipeline. Everything below is the CAMERA the
939
+ // player carries. HELIX OS owns its UI and pushes the whole state down; this
940
+ // runtime owns the rig and reports what it can actually do back up.
941
+ //
942
+ // No manifest capability gates any of this — see docs/camera-contract.md
943
+ // ("Does the native camera need a world manifest capability?").
944
+ // Pointing a phone at things is a native avatar ability like walking, and a
945
+ // world cannot revoke it by omitting a scope. `control` is the one exception,
946
+ // because a WORLD SCRIPT driving the player's camera is a different act.
947
+ // The camera as the shell last described it. Never null: an unpushed camera
948
+ // reads as `session: 'inactive'` with an all-false capability, which is a
949
+ // truthful "put away, claims nothing" rather than a guess.
950
+ //
951
+ // A DEEP copy, not a spread. A spread shares `capability`/`shutter`/`aim`, so
952
+ // one line of caller code could rewrite what the SDK believes the runtime can
953
+ // do, make the recording flag lie to every other reader, or corrupt the
954
+ // de-duplication baseline and mute a later genuine push.
955
+ getState: () => cloneCameraState(this.cameraState),
956
+ // Fires on every real change (edge-deduplicated). Returns an unsubscribe fn.
957
+ onStateChanged: (cb) => {
958
+ this.cameraListeners.add(cb);
959
+ return () => this.cameraListeners.delete(cb);
960
+ },
961
+ // What this runtime can do RIGHT NOW — the live counterpart to the runtime
962
+ // contract's static `runtimeBindings.*.availability`. HELIX OS disables the
963
+ // controls this reports false; it must never grey one out on a guess, nor
964
+ // offer one whose call it already knows will be refused.
965
+ capabilities: () => cloneCameraCapability(this.cameraState.capability),
966
+ // The runtime declaring its abilities to the shell. Call it at boot and again
967
+ // whenever an ability is LOST (a revoked mic kills worldAudio, a torn-down rig
968
+ // kills video) — a capability that only ever grows is a capability that lies.
969
+ // Applied locally first, then posted; false means no shell heard it.
970
+ //
971
+ // The NORMALIZED value is what goes on the wire, not the caller's object: a
972
+ // world-supplied bag can carry keys the contract does not name, and forwarding
973
+ // it would put them in front of the shell and leave the two sides holding
974
+ // different objects for the same fact.
975
+ reportCapability: (capability) => {
976
+ this.assertInitialized();
977
+ const reported = normalizeCameraCapability(capability);
978
+ if (!reported) {
979
+ throw new HelixRequestError('Helix: camera.reportCapability needs every capability flag as a boolean', 'INVALID_ARGUMENT');
980
+ }
981
+ this.cameraRuntimeCapability = reported;
982
+ this.setCameraState({ ...this.cameraState, capability: this.effectiveCameraCapability() });
983
+ if (!this.shellOrigin) {
984
+ this.notePreview('camera.reportCapability');
985
+ return false;
986
+ }
987
+ return this.postToShell({ type: 'helix:camera-capability', capability: reported });
988
+ },
989
+ // A WORLD SCRIPT asking HELIX OS to move the player's camera. Requires the
990
+ // `camera.control` manifest capability. Rejects — never resolves a stale
991
+ // state — when the patch is malformed, when it asks for something this
992
+ // runtime reported it cannot do, or when there is no shell to ask.
993
+ control: async (control) => {
994
+ this.assertInitialized();
995
+ const invalid = validateCameraControl(control);
996
+ if (invalid)
997
+ throw new HelixRequestError(`Helix: ${invalid}`, 'INVALID_ARGUMENT');
998
+ // Against the whole STATE, not the capability alone: the gate has to know the
999
+ // mode the camera ends up in, or a bare `{shutter: true}` in video mode is
1000
+ // checked against `photo` and starts a recording nobody can serve.
1001
+ const missing = cameraCapabilityGate(control, this.cameraState);
1002
+ if (missing)
1003
+ throw this.cameraCapabilityRefusal(missing);
1004
+ if (!this.shellOrigin) {
1005
+ this.notePreview('camera.control');
1006
+ throw new HelixRequestError('Helix: not embedded in a HELIX shell — the camera cannot be driven', 'UNAVAILABLE');
1007
+ }
1008
+ const next = await this.request('camera.control', control);
1009
+ // The shell answers with the state it actually reached, which may be less
1010
+ // than was asked for. Adopt it rather than the request, so a partial apply
1011
+ // cannot leave this runtime believing it got what it wanted.
1012
+ const applied = normalizeCameraState(next);
1013
+ if (!applied) {
1014
+ throw new HelixRequestError('Helix: the shell answered camera.control with a state outside the contract', 'CORRECTION_REQUIRED');
1015
+ }
1016
+ this.adoptShellCameraState(applied);
1017
+ return cloneCameraState(this.cameraState);
1018
+ },
1019
+ // Phase 2. Declared so HELIX OS, the web engine and Unreal agree on the drone
1020
+ // vocabulary now, and REFUSED so nobody ships against a resolve that means
1021
+ // nothing: the runtime contract marks camera.flyDrone `unavailable` on every
1022
+ // binding until flight authority is settled (a drone is a second body in a
1023
+ // shared world, so who may move it is not a client's decision to make).
1024
+ flyDrone: (command) => {
1025
+ this.assertInitialized();
1026
+ void command;
1027
+ return Promise.reject(new HelixRequestError('Helix: camera.flyDrone is contracted vocabulary only — see knownGaps camera-drone-flight-authority-uncontracted', 'UNAVAILABLE'));
1028
+ },
299
1029
  };
300
1030
  // ─────────────────────────── avatar ───────────────────────────
301
1031
  avatar = {
302
1032
  openCreator: async () => {
303
1033
  this.assertInitialized();
304
- if (!this.shellOrigin)
1034
+ if (!this.shellOrigin) {
1035
+ this.notePreview('avatar.openCreator');
305
1036
  return false;
1037
+ }
306
1038
  return this.request('avatar.openCreator');
307
1039
  },
308
1040
  getLoadout: async () => {
@@ -333,13 +1065,47 @@ class HelixSdk {
333
1065
  }
334
1066
  },
335
1067
  // The local player's equipped "universal avatar" — the single avatar a world
336
- // renders for them (equipped → auto-equip first owned → default). Resolved by
337
- // a DIRECT call to the platform's public equipped-avatar endpoint — no shell
338
- // round-trip (the generic helix:request bridge is not implemented by the
339
- // shells). The session supplies the player's own user id; the API base is
340
- // Helix.multiplayer.configure({ apiBaseUrl }) else the session token's `iss`.
341
- // Returns null for guests / outside a shell / on ANY resolution failure — the
342
- // world falls back to its default body, never breaks.
1068
+ // renders for them (trial → equipped → auto-equip first owned → default).
1069
+ // The shell is authoritative for the local player because it can supply a
1070
+ // session-scoped marketplace trial. Older/local shells fall back to the
1071
+ // platform's public equipped-avatar endpoint using the session user id.
1072
+ getEquipped: async () => {
1073
+ this.assertInitialized();
1074
+ if (this.shellOrigin) {
1075
+ try {
1076
+ return await this.request('avatar.getEquipped');
1077
+ }
1078
+ catch {
1079
+ // Preserve direct resolution for older or local shells without this bridge method.
1080
+ }
1081
+ }
1082
+ const user = this.session?.user;
1083
+ return user ? this.fetchEquippedAvatar(user.id) : null;
1084
+ },
1085
+ /** Resolve another joined player's public configured avatar for replica rendering. */
1086
+ getEquippedForUser: async (userId) => {
1087
+ this.assertInitialized();
1088
+ return typeof userId === 'string' && userId.length > 0
1089
+ ? this.fetchEquippedAvatar(userId)
1090
+ : null;
1091
+ },
1092
+ onAvatarChanged: (cb) => {
1093
+ this.avatarListeners.add(cb);
1094
+ return () => this.avatarListeners.delete(cb);
1095
+ },
1096
+ };
1097
+ // ─────────────────────────── emotes ───────────────────────────
1098
+ emotes = {
1099
+ // The local player's equipped emote wheel — the same rows the ROOM resolves
1100
+ // onto every seat as PlayerState.emotes (contract v28), readable here so a
1101
+ // world can render the wheel without (or before) a room join. Resolved by a
1102
+ // DIRECT call to the platform's public equipped-emotes endpoint, exactly like
1103
+ // avatar.getEquipped — no shell round-trip (the generic helix:request bridge
1104
+ // is not implemented by the shells). The session supplies the player's own
1105
+ // user id; the API base is Helix.multiplayer.configure({ apiBaseUrl }) else
1106
+ // the session token's `iss`. Returns null for guests / outside a shell / on
1107
+ // ANY resolution failure — the world just shows no wheel, never breaks. An
1108
+ // EMPTY emotes array is a real answer: the player carries none.
343
1109
  getEquipped: async () => {
344
1110
  this.assertInitialized();
345
1111
  const user = this.session?.user;
@@ -350,27 +1116,91 @@ class HelixSdk {
350
1116
  if (apiBase === null)
351
1117
  return null;
352
1118
  try {
353
- const res = await fetch(`${apiBase}/api/v1/universal-items/avatar/equipped/users/${encodeURIComponent(user.id)}`);
1119
+ const res = await fetch(`${apiBase}/api/v1/universal-items/emotes/equipped/users/${encodeURIComponent(user.id)}`);
354
1120
  if (!res.ok)
355
1121
  return null;
356
1122
  const dto = (await res.json());
357
- if (!dto || (dto.source !== 'equipped' && dto.source !== 'auto' && dto.source !== 'default'))
1123
+ if (!dto || !Array.isArray(dto.emotes))
358
1124
  return null;
359
- return {
360
- source: dto.source,
361
- inventoryItemId: typeof dto.inventoryItemId === 'string' ? dto.inventoryItemId : null,
362
- itemId: typeof dto.itemId === 'string' ? dto.itemId : null,
363
- glbUrl: typeof dto.glbUrl === 'string' ? dto.glbUrl : null,
364
- skeleton: typeof dto.skeleton === 'string' ? dto.skeleton : null,
365
- };
1125
+ const emotes = [];
1126
+ for (const raw of dto.emotes) {
1127
+ if (typeof raw !== 'object' || raw === null)
1128
+ continue;
1129
+ const e = raw;
1130
+ // A row the wheel can't place, can't play or can't fetch is dropped — one bad catalog row costs
1131
+ // one emote, not the set (the room's sanitizeEmotes makes the same call on the replicated side).
1132
+ if (typeof e.slot !== 'string' || !EMOTE_WHEEL_SLOTS.includes(e.slot))
1133
+ continue;
1134
+ if (e.playback !== 'oneshot' && e.playback !== 'loop')
1135
+ continue;
1136
+ if (typeof e.clip !== 'string' || e.clip.length === 0)
1137
+ continue;
1138
+ emotes.push({
1139
+ slot: e.slot,
1140
+ itemId: typeof e.itemId === 'string' ? e.itemId : '',
1141
+ clip: e.clip,
1142
+ playback: e.playback,
1143
+ // audio/label are garnish: absent, empty or mistyped just means a silent / unnamed emote.
1144
+ ...(typeof e.audio === 'string' && e.audio.length > 0 ? { audio: e.audio } : {}),
1145
+ ...(typeof e.label === 'string' && e.label.length > 0 ? { label: e.label } : {}),
1146
+ });
1147
+ }
1148
+ return { emotes };
366
1149
  }
367
1150
  catch {
368
1151
  return null;
369
1152
  }
370
1153
  },
371
- onAvatarChanged: (cb) => {
372
- this.avatarListeners.add(cb);
373
- return () => this.avatarListeners.delete(cb);
1154
+ /**
1155
+ * Fires after the shell has settled and closed an emote-customizer session. A joined room uses the
1156
+ * same cue to re-resolve its authoritative seat; a join:false world re-fetches getEquipped instead.
1157
+ */
1158
+ onChanged: (cb) => {
1159
+ this.emoteListeners.add(cb);
1160
+ return () => this.emoteListeners.delete(cb);
1161
+ },
1162
+ /**
1163
+ * Raise the platform's emote-wheel customizer over this world.
1164
+ *
1165
+ * Routed through the `helix:request` bridge, unlike `getEquipped()` above, which deliberately
1166
+ * calls the public platform API directly. The difference is that this one CHANGES something and
1167
+ * needs the player's own credential: the shell owns the session, so the shell owns the editor.
1168
+ * A world can ask for the door to be opened and learns only whether it was.
1169
+ *
1170
+ * Resolves `false` when the player is signed out (the shell routes them to auth instead) or when
1171
+ * the host has no customizer mounted — never throws for either, because "the editor did not open"
1172
+ * is a normal outcome a world should handle, not an exception.
1173
+ */
1174
+ openCustomizer: async () => {
1175
+ this.assertInitialized();
1176
+ if (!this.shellOrigin) {
1177
+ this.notePreview('emotes.openCustomizer');
1178
+ return false;
1179
+ }
1180
+ return this.request('emotes.openCustomizer');
1181
+ },
1182
+ };
1183
+ // ─────────────────────────── locomotion ───────────────────────────
1184
+ locomotion = {
1185
+ /**
1186
+ * The locomotion pack the local player MOVES on — read off the seat, not an endpoint.
1187
+ *
1188
+ * Deliberately unlike `avatar.getEquipped` / `emotes.getEquipped`, which resolve through the shell
1189
+ * bridge or a public platform endpoint: a locomotion pack is resolved SERVER-SIDE by the ROOM at join
1190
+ * (and re-resolved on the `avatarRefresh` hint) and written onto PlayerState.locomotionPack — contract
1191
+ * v34 — so the replicated seat is the only place a client can honestly learn which pack landed on it.
1192
+ * Asking the platform directly would answer "what is equipped", which is not the same question as
1193
+ * "what is this seat playing".
1194
+ *
1195
+ * Returns null when there is no seat to read (no room joined, or this session's player has not
1196
+ * replicated yet) — the same "could not resolve at all" null its siblings return. An EMPTY `pack` is a
1197
+ * real answer: the seat moves on the platform locomotion set, which is equally what a room predating
1198
+ * v34, an unresolvable pack and an unservable URL replicate. Never throws.
1199
+ */
1200
+ getEquipped: async () => {
1201
+ this.assertInitialized();
1202
+ const pack = this.multiplayer.localLocomotionPack();
1203
+ return pack === null ? null : { pack };
374
1204
  },
375
1205
  };
376
1206
  // ─────────────────────────── presence ───────────────────────────
@@ -401,7 +1231,7 @@ class HelixSdk {
401
1231
  const apiBase = this.multiplayer.resolveApiBase(token);
402
1232
  if (apiBase === null)
403
1233
  return false;
404
- const worldId = this.world?.id ?? undefined;
1234
+ const worldId = this.worldContext?.id ?? undefined;
405
1235
  try {
406
1236
  const res = await fetch(`${apiBase}/api/v1/users/me/presence/activity`, {
407
1237
  method: 'POST',
@@ -446,19 +1276,112 @@ class HelixSdk {
446
1276
  }
447
1277
  },
448
1278
  };
449
- // Shared purchase path. The SDK mints a stable idempotency key per attempt
450
- // (reused by the shell across confirm-popup retries) and asks the shell to
451
- // settle. Not embedded (local dev) → Unauthorized, never a fake success.
452
- purchase(ref) {
1279
+ // Shared purchase path. An automatic key survives an unresolved result or reload and is reused for the same
1280
+ // world+ref until a terminal answer arrives. Not embedded (local dev) → Unauthorized, never a fake success.
1281
+ purchase(ref, options) {
453
1282
  this.assertInitialized();
454
1283
  if (!this.shellOrigin) {
1284
+ const method = ref.startsWith('dkey:')
1285
+ ? 'marketplace.purchaseDistributionKey'
1286
+ : ref.startsWith('distribution:')
1287
+ ? 'marketplace.purchaseDistribution'
1288
+ : ref.startsWith('listing:')
1289
+ ? 'marketplace.purchaseListing'
1290
+ : 'marketplace.purchaseProduct';
1291
+ this.notePreview(method);
455
1292
  return Promise.resolve({ status: 'Unauthorized', completed: false });
456
1293
  }
457
- const idempotencyKey = this.newId();
458
- return this.request('marketplace.purchase', { ref, idempotencyKey }, LOGIN_TIMEOUT_MS).then((raw) => ({
459
- ...raw,
460
- completed: COMPLETED_STATUSES.has(raw.status),
461
- }));
1294
+ const quantity = this.purchaseQuantity(options);
1295
+ if (ref.startsWith('listing:') && quantity !== 1) {
1296
+ return Promise.reject(new Error('Helix: a collectible listing contains exactly one serial; quantity must be 1'));
1297
+ }
1298
+ // Caller keys remain verbatim. Automatic keys are session-persisted before the request is posted, closing
1299
+ // the lost-response gap where a retry used to mint a second key and could charge twice. The shell additionally
1300
+ // prefixes the world id, and the server scopes the row to buyer+world. Max 128 chars is enforced by the shell.
1301
+ const callerKey = typeof options === 'number' ? undefined : options?.idempotencyKey;
1302
+ const attemptRef = `${ref}\nquantity:${quantity}`;
1303
+ const idempotencyKey = callerKey ?? this.autoPurchaseKey(attemptRef);
1304
+ return this.request('marketplace.purchase', { ref, quantity, idempotencyKey }, LOGIN_TIMEOUT_MS).then((raw) => {
1305
+ const result = this.settlePurchaseResult(raw);
1306
+ // A shell concurrency refusal is fabricated locally for a SECOND, competing call — clearing
1307
+ // here would wipe the FIRST attempt's recovery key while its charge may still be settling.
1308
+ if (!callerKey &&
1309
+ !UNRESOLVED_PURCHASE_STATUSES.has(result.status) &&
1310
+ !(result.status === 'Failed' && result.reason === SHELL_CONCURRENT_PURCHASE_REASON)) {
1311
+ this.clearAutoPurchaseAttempt(idempotencyKey, attemptRef);
1312
+ }
1313
+ return result;
1314
+ });
1315
+ }
1316
+ purchaseQuantity(options) {
1317
+ const quantity = typeof options === 'number' ? options : options?.quantity ?? 1;
1318
+ if (!Number.isInteger(quantity) || quantity < 1) {
1319
+ throw new Error('Helix: purchase quantity must be a whole number >= 1');
1320
+ }
1321
+ return quantity;
1322
+ }
1323
+ purchaseAttemptSlot(ref) {
1324
+ return this.worldContext?.id ? `${this.worldContext.id}\n${ref}` : null;
1325
+ }
1326
+ readPersistedPurchaseAttempts() {
1327
+ try {
1328
+ const raw = window.sessionStorage.getItem(PURCHASE_ATTEMPTS_STORAGE_KEY);
1329
+ if (!raw)
1330
+ return {};
1331
+ const parsed = JSON.parse(raw);
1332
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
1333
+ return {};
1334
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => typeof entry[1] === 'string'));
1335
+ }
1336
+ catch {
1337
+ return {};
1338
+ }
1339
+ }
1340
+ writePersistedPurchaseAttempts(attempts) {
1341
+ try {
1342
+ if (Object.keys(attempts).length === 0)
1343
+ window.sessionStorage.removeItem(PURCHASE_ATTEMPTS_STORAGE_KEY);
1344
+ else
1345
+ window.sessionStorage.setItem(PURCHASE_ATTEMPTS_STORAGE_KEY, JSON.stringify(attempts));
1346
+ }
1347
+ catch {
1348
+ // Sandboxed/private contexts may deny storage. The in-memory map still protects retries in this SDK instance.
1349
+ }
1350
+ }
1351
+ autoPurchaseKey(ref) {
1352
+ const slot = this.purchaseAttemptSlot(ref);
1353
+ if (!slot)
1354
+ return this.newId();
1355
+ const persisted = this.readPersistedPurchaseAttempts();
1356
+ const idempotencyKey = this.autoPurchaseAttempts.get(slot) ?? persisted[slot] ?? this.newId();
1357
+ this.autoPurchaseAttempts.set(slot, idempotencyKey);
1358
+ persisted[slot] = idempotencyKey;
1359
+ this.writePersistedPurchaseAttempts(persisted);
1360
+ return idempotencyKey;
1361
+ }
1362
+ clearAutoPurchaseAttempt(idempotencyKey, ref) {
1363
+ const persisted = this.readPersistedPurchaseAttempts();
1364
+ const exactSlot = ref ? this.purchaseAttemptSlot(ref) : null;
1365
+ for (const [slot, key] of this.autoPurchaseAttempts) {
1366
+ if (key === idempotencyKey && (!exactSlot || slot === exactSlot))
1367
+ this.autoPurchaseAttempts.delete(slot);
1368
+ }
1369
+ for (const [slot, key] of Object.entries(persisted)) {
1370
+ if (key === idempotencyKey && (!exactSlot || slot === exactSlot))
1371
+ delete persisted[slot];
1372
+ }
1373
+ this.writePersistedPurchaseAttempts(persisted);
1374
+ }
1375
+ // Normalize a shell purchase result: add the `completed` convenience and forward any backend receipt to a
1376
+ // live room (v22). Gated on the receipt's presence, never on `completed` — AlreadyOwned completes but
1377
+ // settles nothing, so it carries none. Every result path runs through here, including the getPurchase
1378
+ // recovery read, or a killed tab would lose the receipt the room needs.
1379
+ settlePurchaseResult(raw) {
1380
+ const result = { ...raw, completed: COMPLETED_STATUSES.has(raw.status) };
1381
+ if (typeof raw.receipt === 'string' && raw.receipt.length > 0) {
1382
+ this.multiplayer.sendPurchaseReceipt(raw.receipt);
1383
+ }
1384
+ return result;
462
1385
  }
463
1386
  async trackAnalytics(eventName, input) {
464
1387
  this.assertInitialized();
@@ -475,7 +1398,7 @@ class HelixSdk {
475
1398
  session_id: token ? `world:${this.session?.user.id ?? 'guest'}` : undefined,
476
1399
  platform: 'web',
477
1400
  source: 'client',
478
- world_id: this.world?.id,
1401
+ world_id: this.worldContext?.id,
479
1402
  instance_id: input.instanceId ?? undefined,
480
1403
  item_id: input.itemId ?? undefined,
481
1404
  invite_id: input.inviteId ?? undefined,
@@ -513,19 +1436,39 @@ class HelixSdk {
513
1436
  onKeyDown = (event) => {
514
1437
  if (!this.initialized)
515
1438
  return;
516
- if (event.key !== 'Escape' || event.repeat || event.defaultPrevented)
1439
+ if (!this.deviceGlobalShortcutEnabled ||
1440
+ event.key !== 'Tab' ||
1441
+ event.repeat ||
1442
+ event.defaultPrevented ||
1443
+ event.altKey ||
1444
+ event.ctrlKey ||
1445
+ event.metaKey ||
1446
+ event.shiftKey)
517
1447
  return;
518
- const target = event.target;
519
- const tag = target?.tagName?.toLowerCase();
520
- const isTyping = target?.isContentEditable ||
521
- tag === 'input' ||
522
- tag === 'textarea' ||
523
- tag === 'select';
524
- if (isTyping)
1448
+ if (this.isInteractiveUiEvent(event))
525
1449
  return;
526
1450
  if (this.device.openTablet())
527
1451
  event.preventDefault();
528
1452
  };
1453
+ isInteractiveUiEvent(event) {
1454
+ const path = typeof event.composedPath === 'function'
1455
+ ? event.composedPath()
1456
+ : [event.target];
1457
+ return path.some((target) => {
1458
+ if (!(target instanceof Element))
1459
+ return false;
1460
+ if (target.tagName.toLowerCase() === 'canvas')
1461
+ return false;
1462
+ if (target.matches('input, textarea, select, button, a[href], area[href], summary, ' +
1463
+ 'audio[controls], video[controls], [contenteditable]:not([contenteditable="false"]), ' +
1464
+ '[role="button"], [role="link"], [role="textbox"], [role="combobox"], ' +
1465
+ '[role="listbox"], [role="menu"], [role="menuitem"], [role="option"], ' +
1466
+ '[role="switch"], [role="tab"], [role="treeitem"]'))
1467
+ return true;
1468
+ return target instanceof HTMLElement
1469
+ && (target.isContentEditable || target.tabIndex >= 0);
1470
+ });
1471
+ }
529
1472
  // Generic shell-mediated request/response over postMessage.
530
1473
  request(method, payload, timeoutMs = REQUEST_TIMEOUT_MS) {
531
1474
  this.assertInitialized();
@@ -581,15 +1524,60 @@ class HelixSdk {
581
1524
  return null;
582
1525
  }
583
1526
  }
1527
+ async fetchEquippedAvatar(userId) {
1528
+ const token = this.session?.token ?? null;
1529
+ if (token === null)
1530
+ return null;
1531
+ const apiBase = this.multiplayer.resolveApiBase(token);
1532
+ if (apiBase === null)
1533
+ return null;
1534
+ try {
1535
+ const res = await fetch(`${apiBase}/api/v1/universal-items/avatar/equipped/users/${encodeURIComponent(userId)}`);
1536
+ if (!res.ok)
1537
+ return null;
1538
+ const dto = (await res.json());
1539
+ if (!dto ||
1540
+ (dto.source !== 'equipped' &&
1541
+ dto.source !== 'auto' &&
1542
+ dto.source !== 'default')) {
1543
+ return null;
1544
+ }
1545
+ const composition = dto.composition &&
1546
+ typeof dto.composition === 'object' &&
1547
+ dto.composition.hostKind === 'character' &&
1548
+ Array.isArray(dto.composition.visibleAddOns)
1549
+ ? dto.composition
1550
+ : null;
1551
+ return {
1552
+ source: dto.source,
1553
+ inventoryItemId: typeof dto.inventoryItemId === 'string'
1554
+ ? dto.inventoryItemId
1555
+ : null,
1556
+ itemId: typeof dto.itemId === 'string' ? dto.itemId : null,
1557
+ glbUrl: typeof dto.glbUrl === 'string' ? dto.glbUrl : null,
1558
+ skeleton: typeof dto.skeleton === 'string' ? dto.skeleton : null,
1559
+ ...(composition ? { composition } : {}),
1560
+ };
1561
+ }
1562
+ catch {
1563
+ return null;
1564
+ }
1565
+ }
584
1566
  emitAvatarChanged() {
585
1567
  for (const listener of this.avatarListeners)
586
1568
  listener();
587
1569
  }
588
1570
  snapshot() {
1571
+ const customizer = this.currentCustomizerContext();
589
1572
  return {
590
1573
  embedded: this.shellOrigin !== null,
591
- world: this.world,
1574
+ world: this.worldContext,
592
1575
  user: this.session?.user ?? null,
1576
+ runtimeFidelity: this.runtimeFidelityIntent
1577
+ ? { ...this.runtimeFidelityIntent }
1578
+ : null,
1579
+ customizerSubject: customizer.subject,
1580
+ customizerSource: customizer.source,
593
1581
  };
594
1582
  }
595
1583
  assertInitialized() {
@@ -630,7 +1618,11 @@ class HelixSdk {
630
1618
  if (this.shellOrigin)
631
1619
  return;
632
1620
  this.shellOrigin = event.origin;
633
- this.world = msg.world;
1621
+ this.worldContext = msg.world;
1622
+ this.runtimeFidelityIntent = normalizeRuntimeFidelityIntent(msg.runtimeFidelity);
1623
+ this.requestedInstanceId = typeof msg.instanceId === 'string' && msg.instanceId.length > 0 ? msg.instanceId : null;
1624
+ if (typeof msg.apiBaseUrl === 'string' && msg.apiBaseUrl.length > 0)
1625
+ this.multiplayer.adoptShellApiBase(msg.apiBaseUrl);
634
1626
  this.setSession(msg.session);
635
1627
  if (msg.debug)
636
1628
  this.enableDebug();
@@ -657,7 +1649,77 @@ class HelixSdk {
657
1649
  if (msg.ok)
658
1650
  pending.resolve(msg.result);
659
1651
  else
660
- pending.reject(new Error(msg.error ?? 'Helix: request failed'));
1652
+ pending.reject(new HelixRequestError(msg.error ?? 'Helix: request failed', msg.errorCode));
1653
+ break;
1654
+ }
1655
+ case 'helix:voice-settings':
1656
+ // The shell owns voice preferences (tablet mic mode / device / local mutes); apply is async
1657
+ // (mic capture may prompt) and failures surface via the published voice-state, never throw.
1658
+ void this.voice.applySettings(msg.settings).catch(() => undefined);
1659
+ break;
1660
+ case 'helix:voice-ptt':
1661
+ // Keyboard events stay inside their focused document. The world's own listener covers
1662
+ // pointer-locked gameplay; this authenticated shell edge covers shell chrome/overlays.
1663
+ if (!this.shellOrigin || typeof msg.down !== 'boolean')
1664
+ return;
1665
+ this.voice.setPttDown(msg.down);
1666
+ break;
1667
+ case 'helix:device-state':
1668
+ // Accept only after helix:init pins the shell origin. The shell replays its current snapshot
1669
+ // after the handshake, so a world cannot miss a device that was already open while it booted.
1670
+ if (!this.shellOrigin)
1671
+ return;
1672
+ this.setDeviceState({
1673
+ open: msg.open,
1674
+ ...(msg.form !== undefined ? { form: msg.form } : {}),
1675
+ });
1676
+ break;
1677
+ case 'helix:camera-state': {
1678
+ // Same trust rule as helix:device-state: a camera message cannot establish
1679
+ // an origin, only helix:init can. The shell re-sends its snapshot after the
1680
+ // handshake, so a runtime that booted mid-shot is never left guessing.
1681
+ if (!this.shellOrigin)
1682
+ return;
1683
+ const state = normalizeCameraState(msg.state);
1684
+ if (!state) {
1685
+ // DROPPED WHOLE, not partially applied. A push naming something outside
1686
+ // the shared vocabulary means the shell and this SDK have diverged, and a
1687
+ // camera half-moved into a state nobody authored is worse than one that
1688
+ // did not move. Audible on the debug channel so a harness can see it.
1689
+ this.captureLog('warn', [
1690
+ '[Helix] dropped a helix:camera-state outside the camera contract',
1691
+ msg.state,
1692
+ ]);
1693
+ return;
1694
+ }
1695
+ this.adoptShellCameraState(state);
1696
+ break;
1697
+ }
1698
+ case 'helix:distribution-capability-request': {
1699
+ const requestId = typeof msg.requestId === 'string' ? msg.requestId.slice(0, 64) : '';
1700
+ const origin = this.shellOrigin;
1701
+ if (!requestId || !origin || typeof msg.ref !== 'string')
1702
+ return;
1703
+ void this.multiplayer.requestDistributionCapability(msg.ref).then((grant) => this.post({ type: 'helix:distribution-capability-result', requestId, ...grant }, origin), (error) => this.post({ type: 'helix:distribution-capability-result', requestId, error: error instanceof Error ? error.message : 'unavailable' }, origin));
1704
+ break;
1705
+ }
1706
+ case 'helix:leave': {
1707
+ // The world is left (hasLeft()) only on the word of the shell that initialised it: before helix:init
1708
+ // pins an origin, a leave cannot be told apart from any other window's message. Set BEFORE the
1709
+ // teardown below, so nothing it triggers — a room handle's onLeave, a cancelled join — can rejoin.
1710
+ const leaving = this.shellOrigin !== null && !this.left;
1711
+ if (leaving)
1712
+ this.markLeft();
1713
+ // Deliberate exit (shell Exit button / browser Back): free the seat NOW — consented close,
1714
+ // instant despawn, no reconnect grace — and leave voice. Fire-and-forget: if the frame dies
1715
+ // before this lands, the room falls back to the plain-drop grace, i.e. today's behavior.
1716
+ void this.multiplayer.leave().catch(() => undefined);
1717
+ void this.voice.leave().catch(() => undefined);
1718
+ // The queue heartbeat and the party poll stop with the world.
1719
+ this.matchmaking.teardown();
1720
+ this.party.teardown();
1721
+ if (leaving)
1722
+ this.emitLeave();
661
1723
  break;
662
1724
  }
663
1725
  case 'helix:event': {
@@ -670,21 +1732,146 @@ class HelixSdk {
670
1732
  for (const l of this.inventoryListeners)
671
1733
  l();
672
1734
  }
1735
+ else if (msg.event === 'entitlements-changed') {
1736
+ for (const l of this.entitlementListeners)
1737
+ l();
1738
+ }
673
1739
  else if (msg.event === 'avatar-changed' || msg.event === 'equipment-changed') {
674
1740
  this.emitAvatarChanged();
675
1741
  }
1742
+ else if (msg.event === 'emotes-changed') {
1743
+ // Joined worlds re-resolve the authoritative room seat. join:false worlds have no seat, so their
1744
+ // facade listens to the same settled cue and re-fetches Helix.emotes.getEquipped() instead.
1745
+ this.multiplayer.sendEmoteRefresh();
1746
+ for (const l of this.emoteListeners)
1747
+ l();
1748
+ }
676
1749
  break;
677
1750
  }
678
1751
  }
679
1752
  };
1753
+ // The player left (helix:leave). A world that is never left registers nothing here; one that is gets a
1754
+ // single `pageshow` listener, which exists only while it is left (the same rule as the matchmaking poll's).
1755
+ markLeft() {
1756
+ this.left = true;
1757
+ if (typeof window !== 'undefined')
1758
+ window.addEventListener('pageshow', this.onPageRestored);
1759
+ }
1760
+ // The shell never re-enters a world in the same document (a new iframe, a new SDK, a new helix:init),
1761
+ // EXCEPT one way: the play page restored from the back/forward cache, which shows this very document again
1762
+ // with no new handshake. The player is back in the world, so it is no longer left. Any other `pageshow` (the
1763
+ // first one of a load that a leave overtook) is not a return.
1764
+ onPageRestored = (event) => {
1765
+ if (event.persisted !== true)
1766
+ return;
1767
+ window.removeEventListener('pageshow', this.onPageRestored);
1768
+ this.left = false;
1769
+ };
1770
+ emitLeave() {
1771
+ for (const listener of [...this.leaveListeners]) {
1772
+ try {
1773
+ listener();
1774
+ }
1775
+ catch (e) {
1776
+ console.error('[Helix] an onLeave subscriber threw', e);
1777
+ }
1778
+ }
1779
+ }
1780
+ setDeviceState(next) {
1781
+ if (next.open === this.deviceState.open && next.form === this.deviceState.form)
1782
+ return;
1783
+ this.deviceState = next;
1784
+ for (const listener of this.deviceListeners)
1785
+ listener({ ...next });
1786
+ }
1787
+ // Edge de-duplication for the camera, on the same rule as setDeviceState — the
1788
+ // shell re-sends its whole snapshot after the handshake and on any UI redraw, so
1789
+ // an identical push must cost a world nothing. Compared by serialization rather
1790
+ // than field by field because the state is nested and grows: a new member added
1791
+ // to HelixCameraState is covered here the day it is added, where an explicit
1792
+ // field comparison would silently stop noticing it.
1793
+ //
1794
+ // Deterministic because every camera state reaching here was BUILT by
1795
+ // normalizeCameraState in one fixed key order — a raw push is never compared.
1796
+ setCameraState(next) {
1797
+ if (JSON.stringify(next) === JSON.stringify(this.cameraState))
1798
+ return;
1799
+ this.cameraState = next;
1800
+ for (const listener of this.cameraListeners) {
1801
+ try {
1802
+ // One DEEP copy PER listener. Sharing one object across listeners lets the
1803
+ // first one mutate the camera every later one sees, and sharing the stored
1804
+ // object lets any of them rewrite the SDK's own state.
1805
+ listener(cloneCameraState(next));
1806
+ }
1807
+ catch {
1808
+ /* one world's listener must never stop the others from seeing the camera */
1809
+ }
1810
+ }
1811
+ }
1812
+ // What the runtime claimed, narrowed by what the shell permits. Before the first
1813
+ // shell push there is nothing to narrow with — an all-false default would be a
1814
+ // refusal the shell never actually sent — so the runtime's own report stands.
1815
+ effectiveCameraCapability() {
1816
+ return this.cameraShellCapability
1817
+ ? intersectCameraCapability(this.cameraRuntimeCapability, this.cameraShellCapability)
1818
+ : cloneCameraCapability(this.cameraRuntimeCapability);
1819
+ }
1820
+ // Name the side that actually refused, and quote ITS reason.
1821
+ //
1822
+ // The effective capability is an AND, so a false flag says only that SOMEBODY
1823
+ // said no. Reporting every refusal as the runtime's put HELIX OS in front of the
1824
+ // player with two falsehoods at once: a flag the runtime had reported AVAILABLE
1825
+ // described as the runtime's refusal, explained by whatever unrelated note the
1826
+ // runtime happened to be carrying — while the shell's actual policy line went
1827
+ // unshown. An honest failure reason is the point of this error existing.
1828
+ cameraCapabilityRefusal(flag) {
1829
+ const shell = this.cameraShellCapability;
1830
+ const shellRefused = this.cameraRuntimeCapability[flag] && shell !== null && !shell[flag];
1831
+ const source = shellRefused ? shell : this.cameraRuntimeCapability;
1832
+ const who = shellRefused ? 'HELIX OS' : 'this runtime';
1833
+ const reason = source.unavailableReason;
1834
+ return new HelixRequestError(`Helix: ${who} reported camera.${flag} unavailable${reason ? ` (${reason})` : ''}`, 'RUNTIME_CAPABILITY_UNAVAILABLE');
1835
+ }
1836
+ // The single door a shell-authored camera state comes through — the push and
1837
+ // camera.control's answer both land here, so neither can skip the intersection
1838
+ // and hand the local gate a capability the runtime never claimed.
1839
+ adoptShellCameraState(state) {
1840
+ this.cameraShellCapability = state.capability;
1841
+ this.setCameraState({ ...state, capability: this.effectiveCameraCapability() });
1842
+ }
680
1843
  setSession(session) {
681
1844
  const before = this.session?.user.id ?? null;
1845
+ const tokenBefore = this.session?.token ?? null;
682
1846
  this.session = session;
1847
+ this.deviceTrialSpawn = normalizeDeviceTrialSpawn(session);
1848
+ const source = normalizePackageCustomizerSource(session);
1849
+ if (source)
1850
+ this.customizerSource = source;
1851
+ this.customizerSubject = normalizePackageCustomizerSubject(session, this.customizerSource);
683
1852
  const after = session?.user.id ?? null;
684
1853
  if (before !== after) {
1854
+ // A different player (or none): the old session's queue ticket and party are not this one's.
1855
+ this.matchmaking.reset();
1856
+ this.party.reset();
685
1857
  for (const listener of this.listeners)
686
1858
  listener(session?.user ?? null);
687
1859
  }
1860
+ else if (session !== null && session.token !== tokenBefore) {
1861
+ // Same player, refreshed token: a party poll that was refused for the old one may try again.
1862
+ this.party.sessionRefreshed();
1863
+ }
1864
+ }
1865
+ currentCustomizerContext() {
1866
+ const expiresAt = this.session?.trial?.expiresAt;
1867
+ if (this.customizerSubject &&
1868
+ (!Number.isFinite(expiresAt) || expiresAt <= Date.now() / 1000)) {
1869
+ this.customizerSubject = null;
1870
+ }
1871
+ return Object.freeze({
1872
+ source: this.customizerSource,
1873
+ subject: this.customizerSubject,
1874
+ });
688
1875
  }
689
1876
  enableDebug() {
690
1877
  if (this.debugEnabled)
@@ -714,6 +1901,20 @@ class HelixSdk {
714
1901
  };
715
1902
  }
716
1903
  }
1904
+ // Makes a no-shell no-op audible once per method per page: the console for a human, the debug ring
1905
+ // for an in-world overlay / harness. hookConsole() already funnels console.warn INTO the ring, so
1906
+ // capture explicitly ONLY when that hook is absent — otherwise one call would land in the ring twice.
1907
+ notePreview(method) {
1908
+ if (warnedPreview.has(method))
1909
+ return;
1910
+ warnedPreview.add(method);
1911
+ const message = SILENT_WRITE_METHODS.has(method)
1912
+ ? `[Helix] ${method}() silently did NOTHING — no HELIX shell, so nothing was saved. Run \`helix dev\` to exercise this locally.`
1913
+ : `[Helix] ${method}() did nothing — not embedded in a HELIX shell. Run \`helix dev\` to exercise this locally.`;
1914
+ if (!this.consoleHooked)
1915
+ this.captureLog('warn', [message]);
1916
+ console.warn(message);
1917
+ }
717
1918
  captureLog(level, args) {
718
1919
  const entry = { level, args: args.map(stringifyArg), t: Date.now() };
719
1920
  this.debugRing.push(entry);
@@ -739,6 +1940,108 @@ class HelixSdk {
739
1940
  this.post(message, this.shellOrigin);
740
1941
  return true;
741
1942
  }
1943
+ // The engine XR module's session state → the shell, as helix:xr-session. Attached once, when init()
1944
+ // resolves (embedded or not: a shell that pins its origin late is still reached, and postToShell is a
1945
+ // no-op without one). Inert when the engine never dispatches. There is deliberately no detach: HelixSdk
1946
+ // has no teardown path (the window message/keydown listeners are never removed either) — the SDK lives
1947
+ // exactly as long as the world document, and so does this listener.
1948
+ xrSessionBridgeAttached = false;
1949
+ attachXrSessionBridge() {
1950
+ if (this.xrSessionBridgeAttached)
1951
+ return;
1952
+ const doc = worldDocument();
1953
+ if (!doc)
1954
+ return;
1955
+ this.xrSessionBridgeAttached = true;
1956
+ // A session the engine reported before init resolved is recorded on the document: report it once.
1957
+ let sticky = null;
1958
+ try {
1959
+ sticky = normalizeXrSession(doc[XR_SESSION_STORE_KEY]);
1960
+ }
1961
+ catch {
1962
+ /* a foreign document with a throwing accessor — nothing to replay */
1963
+ }
1964
+ if (sticky)
1965
+ this.postToShell({ type: 'helix:xr-session', ...sticky });
1966
+ doc.addEventListener(XR_SESSION_EVENT, this.onXrSession);
1967
+ }
1968
+ onXrSession = (event) => {
1969
+ const detail = event.detail;
1970
+ if (!detail || typeof detail !== 'object')
1971
+ return;
1972
+ if (detail.source !== XR_SESSION_SOURCE)
1973
+ return;
1974
+ const session = normalizeXrSession(detail);
1975
+ if (session)
1976
+ this.postToShell({ type: 'helix:xr-session', ...session });
1977
+ };
1978
+ }
1979
+ // Exhaustive over the wire union: a state added to protocol.ts without being accepted here is a compile error.
1980
+ const XR_SESSION_STATES = {
1981
+ entering: true,
1982
+ active: true,
1983
+ exiting: true,
1984
+ idle: true,
1985
+ unsupported: true,
1986
+ };
1987
+ /** The only emitter whose XR_SESSION_EVENT the SDK forwards. */
1988
+ const XR_SESSION_SOURCE = 'humanoid-character';
1989
+ /** Sticky store the engine XR module writes: `document.__helixXrSession = { state, reason }`. */
1990
+ const XR_SESSION_STORE_KEY = '__helixXrSession';
1991
+ /** Sticky store the SDK writes: `document.__helixInteractionPrompt = detail`. */
1992
+ const XR_INTERACTION_PROMPT_STORE_KEY = '__helixInteractionPrompt';
1993
+ const XR_INTERACTION_PROMPT_SOURCE = 'helix-sdk';
1994
+ function worldDocument() {
1995
+ return typeof document === 'undefined' ? null : document;
1996
+ }
1997
+ // Copy an untrusted session report into the wire shape: a known state, and `reason` only when it is a string.
1998
+ // Anything else (including the engine's `source`) is dropped rather than forwarded.
1999
+ function normalizeXrSession(value) {
2000
+ if (!value || typeof value !== 'object')
2001
+ return null;
2002
+ const { state, reason } = value;
2003
+ if (typeof state !== 'string' || !Object.prototype.hasOwnProperty.call(XR_SESSION_STATES, state))
2004
+ return null;
2005
+ return {
2006
+ state: state,
2007
+ ...(typeof reason === 'string' ? { reason } : {}),
2008
+ };
2009
+ }
2010
+ function storedInteractionPromptId() {
2011
+ const doc = worldDocument();
2012
+ if (!doc)
2013
+ return null;
2014
+ try {
2015
+ const stored = doc[XR_INTERACTION_PROMPT_STORE_KEY];
2016
+ return typeof stored?.prompt?.id === 'string' ? stored.prompt.id : null;
2017
+ }
2018
+ catch {
2019
+ return null;
2020
+ }
2021
+ }
2022
+ // Record the detail on the document (sticky, for an engine module that attaches late) and dispatch it.
2023
+ // A signal is never worth a crash: a missing document, a missing CustomEvent or a foreign document is a no-op.
2024
+ function publishInteractionPromptSignal(prompt) {
2025
+ const doc = worldDocument();
2026
+ if (!doc)
2027
+ return;
2028
+ const detail = { prompt, source: XR_INTERACTION_PROMPT_SOURCE };
2029
+ try {
2030
+ doc[XR_INTERACTION_PROMPT_STORE_KEY] = detail;
2031
+ }
2032
+ catch {
2033
+ /* a frozen foreign document */
2034
+ }
2035
+ const Ctor = doc.defaultView?.CustomEvent ??
2036
+ globalThis.CustomEvent;
2037
+ if (!Ctor)
2038
+ return;
2039
+ try {
2040
+ doc.dispatchEvent(new Ctor(XR_INTERACTION_PROMPT_EVENT, { detail }));
2041
+ }
2042
+ catch {
2043
+ /* a detached or foreign document */
2044
+ }
742
2045
  }
743
2046
  // Normalize a captured image to a transferable ArrayBuffer + a content type for
744
2047
  // the shell to upload. Accepts a Blob (browser capture), an ArrayBuffer, or a
@@ -758,6 +2061,13 @@ async function toBytes(image, contentTypeOverride) {
758
2061
  // typeof-guard stops TS from negative-narrowing Blob, so assert it here.
759
2062
  return { bytes: image, contentType: contentTypeOverride || 'image/jpeg' };
760
2063
  }
2064
+ // A board name travels in the request URL's path, so an empty one would hit a route that
2065
+ // isn't there; reject it world-side with a message naming the call that made it.
2066
+ function assertBoardName(board, method) {
2067
+ if (typeof board !== 'string' || board.trim() === '') {
2068
+ throw new Error(`Helix.leaderboard.${method}: board must be a non-empty string`);
2069
+ }
2070
+ }
761
2071
  // Serialize a console arg to a string the shell can print: strings as-is, Errors to their stack, other
762
2072
  // objects to compact JSON (falling back to String() on cyclic/unserializable values).
763
2073
  function stringifyArg(a) {