@hypersoniclabs/helix-sdk 0.1.1 → 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.
- package/README.md +954 -2
- package/dist/action-surface.d.ts +182 -0
- package/dist/action-surface.js +1032 -0
- package/dist/action-surface.js.map +1 -0
- package/dist/camera.d.ts +78 -0
- package/dist/camera.js +640 -0
- package/dist/camera.js.map +1 -0
- package/dist/dev-shell/criteria.d.ts +46 -0
- package/dist/dev-shell/criteria.js +98 -0
- package/dist/dev-shell/criteria.js.map +1 -0
- package/dist/dev-shell/index.d.ts +189 -0
- package/dist/dev-shell/index.js +287 -0
- package/dist/dev-shell/index.js.map +1 -0
- package/dist/dev-shell/keys.d.ts +14 -0
- package/dist/dev-shell/keys.js +78 -0
- package/dist/dev-shell/keys.js.map +1 -0
- package/dist/dev-shell/simulator.d.ts +436 -0
- package/dist/dev-shell/simulator.js +1634 -0
- package/dist/dev-shell/simulator.js.map +1 -0
- package/dist/dev-shell/state.d.ts +148 -0
- package/dist/dev-shell/state.js +196 -0
- package/dist/dev-shell/state.js.map +1 -0
- package/dist/device-definition-resolver.d.ts +34 -0
- package/dist/device-definition-resolver.js +172 -0
- package/dist/device-definition-resolver.js.map +1 -0
- package/dist/device-trial.d.ts +3 -0
- package/dist/device-trial.js +132 -0
- package/dist/device-trial.js.map +1 -0
- package/dist/devices.d.ts +228 -0
- package/dist/devices.js +198 -0
- package/dist/devices.js.map +1 -0
- package/dist/dreamerAudio.d.ts +126 -0
- package/dist/dreamerAudio.js +135 -0
- package/dist/dreamerAudio.js.map +1 -0
- package/dist/generated/runtime-contract.d.ts +15529 -0
- package/dist/generated/runtime-contract.js +20470 -0
- package/dist/generated/runtime-contract.js.map +1 -0
- package/dist/index.d.ts +364 -3
- package/dist/index.js +1954 -13
- package/dist/index.js.map +1 -1
- package/dist/interaction-mode.d.ts +172 -0
- package/dist/interaction-mode.js +553 -0
- package/dist/interaction-mode.js.map +1 -0
- package/dist/internal/avatar-pose.d.ts +25 -0
- package/dist/internal/avatar-pose.js +46 -0
- package/dist/internal/avatar-pose.js.map +1 -0
- package/dist/internal/keyed-collection.d.ts +2 -0
- package/dist/internal/keyed-collection.js +12 -0
- package/dist/internal/keyed-collection.js.map +1 -0
- package/dist/internal/vehicle-detach-action.d.ts +2 -0
- package/dist/internal/vehicle-detach-action.js +6 -0
- package/dist/internal/vehicle-detach-action.js.map +1 -0
- package/dist/matchmaking.d.ts +433 -0
- package/dist/matchmaking.js +1487 -0
- package/dist/matchmaking.js.map +1 -0
- package/dist/materials.d.ts +122 -0
- package/dist/materials.js +217 -0
- package/dist/materials.js.map +1 -0
- package/dist/multiplayer-accessors.d.ts +100 -0
- package/dist/multiplayer-accessors.js +200 -0
- package/dist/multiplayer-accessors.js.map +1 -0
- package/dist/multiplayer-contract/avatar-pose.d.ts +112 -0
- package/dist/multiplayer-contract/avatar-pose.js +250 -0
- package/dist/multiplayer-contract/avatar-pose.js.map +1 -0
- package/dist/multiplayer-contract/credential.d.ts +80 -0
- package/dist/multiplayer-contract/credential.js +5 -0
- package/dist/multiplayer-contract/credential.js.map +1 -0
- package/dist/multiplayer-contract/final-rest.d.ts +66 -0
- package/dist/multiplayer-contract/final-rest.js +38 -0
- package/dist/multiplayer-contract/final-rest.js.map +1 -0
- package/dist/multiplayer-contract/index.d.ts +20 -0
- package/dist/multiplayer-contract/index.js +41 -0
- package/dist/multiplayer-contract/index.js.map +1 -0
- package/dist/multiplayer-contract/messages.d.ts +731 -0
- package/dist/multiplayer-contract/messages.js +237 -0
- package/dist/multiplayer-contract/messages.js.map +1 -0
- package/dist/multiplayer-contract/room.d.ts +177 -0
- package/dist/multiplayer-contract/room.js +17 -0
- package/dist/multiplayer-contract/room.js.map +1 -0
- package/dist/multiplayer-contract/state.d.ts +241 -0
- package/dist/multiplayer-contract/state.js +15 -0
- package/dist/multiplayer-contract/state.js.map +1 -0
- package/dist/multiplayer-final-rest.d.ts +32 -0
- package/dist/multiplayer-final-rest.js +217 -0
- package/dist/multiplayer-final-rest.js.map +1 -0
- package/dist/multiplayer.d.ts +624 -0
- package/dist/multiplayer.js +2503 -0
- package/dist/multiplayer.js.map +1 -0
- package/dist/package.json +3 -0
- package/dist/protocol.d.ts +859 -1
- package/dist/protocol.js +117 -5
- package/dist/protocol.js.map +1 -1
- package/dist/runtime-contract/index.d.ts +15 -0
- package/dist/runtime-contract/index.js +12 -0
- package/dist/runtime-contract/index.js.map +1 -0
- package/dist/server-clock.d.ts +25 -0
- package/dist/server-clock.js +88 -0
- package/dist/server-clock.js.map +1 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/universal-vehicles.d.ts +111 -0
- package/dist/universal-vehicles.js +2 -0
- package/dist/universal-vehicles.js.map +1 -0
- package/dist/vault.d.ts +562 -0
- package/dist/vault.js +365 -0
- package/dist/vault.js.map +1 -0
- package/dist/vehicle-specialty-placement.d.ts +28 -0
- package/dist/vehicle-specialty-placement.js +154 -0
- package/dist/vehicle-specialty-placement.js.map +1 -0
- package/dist/vehicle-specialty-transport.d.ts +78 -0
- package/dist/vehicle-specialty-transport.js +183 -0
- package/dist/vehicle-specialty-transport.js.map +1 -0
- package/dist/voice.d.ts +229 -0
- package/dist/voice.js +1348 -0
- package/dist/voice.js.map +1 -0
- package/generated/runtime-contract/helix-runtime-contract.json +13332 -0
- package/generated/runtime-contract/known-answer.json +20471 -0
- package/generated/runtime-contract/known-answer.schema.json +630 -0
- package/generated/runtime-contract/runtime-contract.schema.json +607 -0
- package/generated/runtime-contract/unreal/HelixRuntimeContract.generated.h +908 -0
- package/package.json +44 -5
package/dist/index.js
CHANGED
|
@@ -1,26 +1,415 @@
|
|
|
1
|
-
import { isShellMessage, PROTOCOL_VERSION, } from './protocol';
|
|
2
|
-
|
|
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';
|
|
28
|
+
// The multiplayer wire contract. Re-exported here so `@hypersoniclabs/helix-sdk` root consumers (and
|
|
29
|
+
// classic node-resolution type imports, e.g. the backend minting RoomCredentialClaims) get it; bundler
|
|
30
|
+
// consumers that want only the contract import the lighter '@hypersoniclabs/helix-sdk/multiplayer-contract'.
|
|
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
|
+
}
|
|
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
|
|
78
|
+
const READY_RETRY_MS = 200; // re-post helix:ready this often until the shell answers (handshake race — see waitForInit)
|
|
3
79
|
const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
|
|
80
|
+
const DEBUG_LOG_MAX = 200; // bounded ring of recent log entries (overlay backfill + pre-init forward flush)
|
|
81
|
+
// Reads/grants should resolve fast; a purchase may sit on the confirm popup, so
|
|
82
|
+
// it uses the longer LOGIN_TIMEOUT_MS instead.
|
|
83
|
+
const REQUEST_TIMEOUT_MS = 30 * 1000;
|
|
84
|
+
// A photo upload (encode + multipart POST to R2) is slower than a read; give it
|
|
85
|
+
// its own budget, shorter than the confirm-popup login window.
|
|
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
|
+
}
|
|
4
243
|
class HelixSdk {
|
|
5
244
|
shellOrigin = null;
|
|
6
245
|
session = null;
|
|
7
|
-
|
|
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;
|
|
8
253
|
initialized = false;
|
|
9
254
|
listeners = new Set();
|
|
255
|
+
debugEnabled = false;
|
|
256
|
+
debugRing = [];
|
|
257
|
+
debugListeners = new Set();
|
|
258
|
+
consoleHooked = false;
|
|
10
259
|
pendingLogins = new Map();
|
|
260
|
+
pendingRequests = new Map();
|
|
261
|
+
balanceListeners = new Set();
|
|
262
|
+
inventoryListeners = new Set();
|
|
263
|
+
entitlementListeners = new Set();
|
|
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
|
+
};
|
|
11
317
|
// Performs the shell handshake. Call once at world start, before any other
|
|
12
318
|
// Helix API. Resolves with embedded=false if no shell answers (local dev).
|
|
13
319
|
async init() {
|
|
14
320
|
if (this.initialized)
|
|
15
321
|
return this.snapshot();
|
|
16
322
|
window.addEventListener('message', this.onMessage);
|
|
323
|
+
window.addEventListener('keydown', this.onKeyDown);
|
|
17
324
|
if (window.parent !== window) {
|
|
18
|
-
this.post({ type: 'helix:ready', protocolVersion: PROTOCOL_VERSION }, '*');
|
|
19
325
|
await this.waitForInit();
|
|
20
326
|
}
|
|
21
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();
|
|
22
333
|
return this.snapshot();
|
|
23
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();
|
|
338
|
+
// Multiplayer (pillar D): Helix.multiplayer.joinRoom(). Reads the world_session token + world id off
|
|
339
|
+
// this singleton; the heavy Colyseus client is dynamically imported only on join.
|
|
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({
|
|
359
|
+
isInitialized: () => this.initialized,
|
|
360
|
+
getToken: () => this.session?.token ?? 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 }),
|
|
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);
|
|
381
|
+
// Debug surface. A world's own console lives in its cross-origin iframe — invisible to DevTools / an
|
|
382
|
+
// automation harness attached to the shell, and to teammates without that frame selected. debug.log feeds
|
|
383
|
+
// a bounded ring an in-world overlay can render (onLog/recent), and — when the shell enabled debug
|
|
384
|
+
// (?debug) — is mirrored to the shell frame's console via helix:log. enableDebug() also hooks console.*
|
|
385
|
+
// so ALL world output is captured, not just explicit debug.log calls. enabled() is a fn (the flag flips
|
|
386
|
+
// at init, after the field initializer runs).
|
|
387
|
+
debug = {
|
|
388
|
+
enabled: () => this.debugEnabled,
|
|
389
|
+
log: (...args) => this.captureLog('info', args),
|
|
390
|
+
onLog: (cb) => {
|
|
391
|
+
this.debugListeners.add(cb);
|
|
392
|
+
return () => this.debugListeners.delete(cb);
|
|
393
|
+
},
|
|
394
|
+
recent: () => this.debugRing.slice(),
|
|
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
|
+
};
|
|
24
413
|
auth = {
|
|
25
414
|
getUser: async () => {
|
|
26
415
|
this.assertInitialized();
|
|
@@ -65,16 +454,1130 @@ class HelixSdk {
|
|
|
65
454
|
return () => this.listeners.delete(listener);
|
|
66
455
|
},
|
|
67
456
|
};
|
|
457
|
+
notify = {
|
|
458
|
+
show: (notification) => {
|
|
459
|
+
this.assertInitialized();
|
|
460
|
+
return this.postToShell({ type: 'helix:notify', notification });
|
|
461
|
+
},
|
|
462
|
+
success: (title, message) => this.notify.show({ kind: 'success', title, message }),
|
|
463
|
+
failure: (title, message) => this.notify.show({ kind: 'failure', title, message }),
|
|
464
|
+
notification: (title, message) => this.notify.show({ kind: 'notification', title, message }),
|
|
465
|
+
message: (title, message) => this.notify.show({ kind: 'message', title, message }),
|
|
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.
|
|
471
|
+
prompts = {
|
|
472
|
+
set: (prompt) => {
|
|
473
|
+
this.assertInitialized();
|
|
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;
|
|
483
|
+
},
|
|
484
|
+
clear: (promptId) => {
|
|
485
|
+
this.assertInitialized();
|
|
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;
|
|
492
|
+
},
|
|
493
|
+
};
|
|
494
|
+
device = {
|
|
495
|
+
openTablet: () => this.openDevice('tablet'),
|
|
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
|
+
},
|
|
510
|
+
};
|
|
68
511
|
// World-scoped session token for direct platform API calls (used by later
|
|
69
512
|
// SDK modules; exposed for advanced cases). Null when unauthenticated.
|
|
70
513
|
getSessionToken() {
|
|
71
514
|
return this.session?.token ?? null;
|
|
72
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
|
+
}
|
|
547
|
+
// ─────────────────────────── wallet ───────────────────────────
|
|
548
|
+
wallet = {
|
|
549
|
+
// The player's current LIX + Coins balances.
|
|
550
|
+
getBalance: async () => {
|
|
551
|
+
this.assertInitialized();
|
|
552
|
+
if (!this.shellOrigin) {
|
|
553
|
+
this.notePreview('wallet.getBalance');
|
|
554
|
+
return { lix: 0, coins: 0 };
|
|
555
|
+
}
|
|
556
|
+
return this.request('wallet.getBalance');
|
|
557
|
+
},
|
|
558
|
+
// Fires after the wallet changes (e.g. a purchase settles). Returns an
|
|
559
|
+
// unsubscribe fn.
|
|
560
|
+
onBalanceChanged: (cb) => {
|
|
561
|
+
this.balanceListeners.add(cb);
|
|
562
|
+
return () => this.balanceListeners.delete(cb);
|
|
563
|
+
},
|
|
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
|
+
};
|
|
604
|
+
// ────────────────────────── marketplace ──────────────────────────
|
|
605
|
+
marketplace = {
|
|
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
|
+
},
|
|
639
|
+
// Browse marketplace listings.
|
|
640
|
+
getListings: async (query) => {
|
|
641
|
+
this.assertInitialized();
|
|
642
|
+
if (!this.shellOrigin) {
|
|
643
|
+
this.notePreview('marketplace.getListings');
|
|
644
|
+
return [];
|
|
645
|
+
}
|
|
646
|
+
return this.request('marketplace.getListings', query ?? {});
|
|
647
|
+
},
|
|
648
|
+
// Product/listing + the player's live balance + eligibility, in one call —
|
|
649
|
+
// for building a custom confirm UI (the built-in popup uses this internally).
|
|
650
|
+
getPurchaseContext: async (ref, options) => {
|
|
651
|
+
this.assertInitialized();
|
|
652
|
+
if (!this.shellOrigin) {
|
|
653
|
+
this.notePreview('marketplace.getPurchaseContext');
|
|
654
|
+
return null;
|
|
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);
|
|
702
|
+
},
|
|
703
|
+
};
|
|
704
|
+
analytics = {
|
|
705
|
+
track: (eventName, input = {}) => this.trackAnalytics(eventName, input),
|
|
706
|
+
};
|
|
707
|
+
// ─────────────────────────── inventory ───────────────────────────
|
|
708
|
+
inventory = {
|
|
709
|
+
// Whether the current player owns at least one of an item. Works across
|
|
710
|
+
// worlds and creators (universal items) — the basis for VIP / season passes.
|
|
711
|
+
hasItem: async (itemId) => {
|
|
712
|
+
this.assertInitialized();
|
|
713
|
+
if (!this.shellOrigin) {
|
|
714
|
+
this.notePreview('inventory.hasItem');
|
|
715
|
+
return false;
|
|
716
|
+
}
|
|
717
|
+
return this.request('inventory.hasItem', { itemId });
|
|
718
|
+
},
|
|
719
|
+
getQuantity: async (itemId) => {
|
|
720
|
+
this.assertInitialized();
|
|
721
|
+
if (!this.shellOrigin) {
|
|
722
|
+
this.notePreview('inventory.getQuantity');
|
|
723
|
+
return 0;
|
|
724
|
+
}
|
|
725
|
+
return this.request('inventory.getQuantity', { itemId });
|
|
726
|
+
},
|
|
727
|
+
// All items the current player owns.
|
|
728
|
+
getMyItems: async () => {
|
|
729
|
+
this.assertInitialized();
|
|
730
|
+
if (!this.shellOrigin) {
|
|
731
|
+
this.notePreview('inventory.getMyItems');
|
|
732
|
+
return [];
|
|
733
|
+
}
|
|
734
|
+
return this.request('inventory.getMyItems');
|
|
735
|
+
},
|
|
736
|
+
// Equip an owned cosmetic item (visual).
|
|
737
|
+
equipItem: async (itemId) => {
|
|
738
|
+
this.assertInitialized();
|
|
739
|
+
if (!this.shellOrigin) {
|
|
740
|
+
this.notePreview('inventory.equipItem');
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
await this.request('inventory.equipItem', { itemId });
|
|
744
|
+
},
|
|
745
|
+
onInventoryChanged: (cb) => {
|
|
746
|
+
this.inventoryListeners.add(cb);
|
|
747
|
+
return () => this.inventoryListeners.delete(cb);
|
|
748
|
+
},
|
|
749
|
+
};
|
|
750
|
+
// Durable, per-world key–value storage (the Roblox DataStore analog). The
|
|
751
|
+
// right place for anything that must survive a session: player progress,
|
|
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
|
|
758
|
+
// apply). See https://docs3.helixgame.com/docs/platform-api/data-store
|
|
759
|
+
dataStore = {
|
|
760
|
+
// Read a durable value by key. Returns null if unset (or in preview mode,
|
|
761
|
+
// when the world is opened directly with no shell).
|
|
762
|
+
get: async (key) => {
|
|
763
|
+
this.assertInitialized();
|
|
764
|
+
if (!this.shellOrigin) {
|
|
765
|
+
this.notePreview('dataStore.get');
|
|
766
|
+
return null;
|
|
767
|
+
}
|
|
768
|
+
return this.request('dataStore.get', { key });
|
|
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
|
+
},
|
|
781
|
+
// Create or overwrite a durable value. No-op in preview mode (read-only).
|
|
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) => {
|
|
790
|
+
this.assertInitialized();
|
|
791
|
+
if (!this.shellOrigin) {
|
|
792
|
+
this.notePreview('dataStore.set');
|
|
793
|
+
return;
|
|
794
|
+
}
|
|
795
|
+
await this.request('dataStore.set', {
|
|
796
|
+
key,
|
|
797
|
+
value,
|
|
798
|
+
expectedVersion: options?.expectedVersion,
|
|
799
|
+
});
|
|
800
|
+
},
|
|
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) => {
|
|
805
|
+
this.assertInitialized();
|
|
806
|
+
if (!this.shellOrigin) {
|
|
807
|
+
this.notePreview('dataStore.delete');
|
|
808
|
+
return;
|
|
809
|
+
}
|
|
810
|
+
await this.request('dataStore.delete', {
|
|
811
|
+
key,
|
|
812
|
+
expectedVersion: options?.expectedVersion,
|
|
813
|
+
});
|
|
814
|
+
},
|
|
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) => {
|
|
820
|
+
this.assertInitialized();
|
|
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', {});
|
|
898
|
+
},
|
|
899
|
+
};
|
|
900
|
+
// ─────────────────────────── camera ───────────────────────────
|
|
901
|
+
//
|
|
902
|
+
// The universal world camera's cloud side. Photo-mode UI + camera control live
|
|
903
|
+
// in the engine (which owns three.js + the render loop); the engine hands the
|
|
904
|
+
// captured pixels here to persist them to the player's account, where they show
|
|
905
|
+
// up in the phone's Gallery on any device (account-scoped, cross-device).
|
|
906
|
+
//
|
|
907
|
+
// `capture` is a pure DOM helper a world/engine can use to turn its rendered
|
|
908
|
+
// canvas into an encoded, aspect-cropped Blob; `savePhoto` is the shell-mediated
|
|
909
|
+
// upload. See https://docs3.helixgame.com/docs/platform-api/camera
|
|
910
|
+
camera = {
|
|
911
|
+
// True when running inside a HELIX shell (so a save can actually reach the
|
|
912
|
+
// account). False in local/preview — capture still works, cloud save no-ops.
|
|
913
|
+
available: () => {
|
|
914
|
+
this.assertInitialized();
|
|
915
|
+
return this.shellOrigin !== null;
|
|
916
|
+
},
|
|
917
|
+
// Encode a (already-rendered) canvas to a Blob, centre-cropped to `aspect`.
|
|
918
|
+
// Pure capture — no upload. The caller must render into the canvas in the
|
|
919
|
+
// same tick (WebGL clears its buffer between frames). Re-exported as
|
|
920
|
+
// `captureCanvas` for non-camera use.
|
|
921
|
+
capture: (canvas, opts) => captureCanvas(canvas, opts),
|
|
922
|
+
// Persist a captured photo to the player's account; it appears in the phone
|
|
923
|
+
// Gallery on every device, tagged with the world it was taken in (the shell
|
|
924
|
+
// stamps the world name authoritatively). Resolves null in preview mode
|
|
925
|
+
// (no shell) — never a fake success. Requires the `camera.capture` scope in
|
|
926
|
+
// the world manifest; a missing scope rejects.
|
|
927
|
+
savePhoto: async (image, meta) => {
|
|
928
|
+
this.assertInitialized();
|
|
929
|
+
if (!this.shellOrigin) {
|
|
930
|
+
this.notePreview('camera.savePhoto');
|
|
931
|
+
return null;
|
|
932
|
+
}
|
|
933
|
+
const { bytes, contentType } = await toBytes(image, meta?.contentType);
|
|
934
|
+
return this.request('camera.savePhoto', { bytes, contentType, caption: meta?.caption, aspect: meta?.aspect ?? 'free' }, UPLOAD_TIMEOUT_MS);
|
|
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
|
+
},
|
|
1029
|
+
};
|
|
1030
|
+
// ─────────────────────────── avatar ───────────────────────────
|
|
1031
|
+
avatar = {
|
|
1032
|
+
openCreator: async () => {
|
|
1033
|
+
this.assertInitialized();
|
|
1034
|
+
if (!this.shellOrigin) {
|
|
1035
|
+
this.notePreview('avatar.openCreator');
|
|
1036
|
+
return false;
|
|
1037
|
+
}
|
|
1038
|
+
return this.request('avatar.openCreator');
|
|
1039
|
+
},
|
|
1040
|
+
getLoadout: async () => {
|
|
1041
|
+
this.assertInitialized();
|
|
1042
|
+
if (!this.shellOrigin)
|
|
1043
|
+
return this.fetchAvatarLoadout();
|
|
1044
|
+
try {
|
|
1045
|
+
return await this.request('avatar.getLoadout');
|
|
1046
|
+
}
|
|
1047
|
+
catch {
|
|
1048
|
+
return this.fetchAvatarLoadout();
|
|
1049
|
+
}
|
|
1050
|
+
},
|
|
1051
|
+
updateLoadout: async (patch) => {
|
|
1052
|
+
this.assertInitialized();
|
|
1053
|
+
if (!this.shellOrigin)
|
|
1054
|
+
return this.fetchAvatarLoadout(patch);
|
|
1055
|
+
try {
|
|
1056
|
+
const loadout = await this.request('avatar.updateLoadout', patch);
|
|
1057
|
+
this.emitAvatarChanged();
|
|
1058
|
+
return loadout;
|
|
1059
|
+
}
|
|
1060
|
+
catch {
|
|
1061
|
+
const loadout = await this.fetchAvatarLoadout(patch);
|
|
1062
|
+
if (loadout)
|
|
1063
|
+
this.emitAvatarChanged();
|
|
1064
|
+
return loadout;
|
|
1065
|
+
}
|
|
1066
|
+
},
|
|
1067
|
+
// The local player's equipped "universal avatar" — the single avatar a world
|
|
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.
|
|
1109
|
+
getEquipped: async () => {
|
|
1110
|
+
this.assertInitialized();
|
|
1111
|
+
const user = this.session?.user;
|
|
1112
|
+
const token = this.session?.token ?? null;
|
|
1113
|
+
if (!user || token === null)
|
|
1114
|
+
return null;
|
|
1115
|
+
const apiBase = this.multiplayer.resolveApiBase(token);
|
|
1116
|
+
if (apiBase === null)
|
|
1117
|
+
return null;
|
|
1118
|
+
try {
|
|
1119
|
+
const res = await fetch(`${apiBase}/api/v1/universal-items/emotes/equipped/users/${encodeURIComponent(user.id)}`);
|
|
1120
|
+
if (!res.ok)
|
|
1121
|
+
return null;
|
|
1122
|
+
const dto = (await res.json());
|
|
1123
|
+
if (!dto || !Array.isArray(dto.emotes))
|
|
1124
|
+
return null;
|
|
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 };
|
|
1149
|
+
}
|
|
1150
|
+
catch {
|
|
1151
|
+
return null;
|
|
1152
|
+
}
|
|
1153
|
+
},
|
|
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 };
|
|
1204
|
+
},
|
|
1205
|
+
};
|
|
1206
|
+
// ─────────────────────────── presence ───────────────────────────
|
|
1207
|
+
presence = {
|
|
1208
|
+
// Push a live rich-presence activity for the local player — enriches the
|
|
1209
|
+
// baseline "In [World]" shown to their friends (sidebar + profile), e.g.
|
|
1210
|
+
// "Racing — lap 3/5". Dynamic: pass whatever the moment calls for, no
|
|
1211
|
+
// registration. `image` defaults to the world thumbnail when omitted.
|
|
1212
|
+
//
|
|
1213
|
+
// SERVER-AUTHORITATIVE (by design): this posts to the authenticated presence
|
|
1214
|
+
// endpoint as the player's own session; the server sets activity ONLY for
|
|
1215
|
+
// that player and ONLY for the world they are currently in — a world can
|
|
1216
|
+
// never set another player's status. When the room runtime lands it will set
|
|
1217
|
+
// activity server-to-server after authenticating the player into its
|
|
1218
|
+
// instance; the API and validation are already shaped for that.
|
|
1219
|
+
//
|
|
1220
|
+
// Governed by the player's privacy settings (visibility + hide-activity):
|
|
1221
|
+
// if they've hidden activity or restricted who sees them, the server never
|
|
1222
|
+
// emits it. Text is length-capped, rate-limited, and moderated server-side.
|
|
1223
|
+
//
|
|
1224
|
+
// Returns true on success; false for guests / outside a shell / not in a
|
|
1225
|
+
// world / rejected — never throws into the world loop.
|
|
1226
|
+
setActivity: async (activity) => {
|
|
1227
|
+
this.assertInitialized();
|
|
1228
|
+
const token = this.session?.token ?? null;
|
|
1229
|
+
if (token === null)
|
|
1230
|
+
return false;
|
|
1231
|
+
const apiBase = this.multiplayer.resolveApiBase(token);
|
|
1232
|
+
if (apiBase === null)
|
|
1233
|
+
return false;
|
|
1234
|
+
const worldId = this.worldContext?.id ?? undefined;
|
|
1235
|
+
try {
|
|
1236
|
+
const res = await fetch(`${apiBase}/api/v1/users/me/presence/activity`, {
|
|
1237
|
+
method: 'POST',
|
|
1238
|
+
headers: {
|
|
1239
|
+
'Content-Type': 'application/json',
|
|
1240
|
+
Authorization: `Bearer ${token}`,
|
|
1241
|
+
},
|
|
1242
|
+
body: JSON.stringify({
|
|
1243
|
+
state: activity.state,
|
|
1244
|
+
details: activity.details,
|
|
1245
|
+
image: activity.image,
|
|
1246
|
+
party: activity.party,
|
|
1247
|
+
joinable: activity.joinable,
|
|
1248
|
+
worldId,
|
|
1249
|
+
}),
|
|
1250
|
+
});
|
|
1251
|
+
return res.ok;
|
|
1252
|
+
}
|
|
1253
|
+
catch {
|
|
1254
|
+
return false;
|
|
1255
|
+
}
|
|
1256
|
+
},
|
|
1257
|
+
// Clear any activity the world set, falling back to the baseline "In
|
|
1258
|
+
// [World]". Also happens automatically when the player leaves the world.
|
|
1259
|
+
clearActivity: async () => {
|
|
1260
|
+
this.assertInitialized();
|
|
1261
|
+
const token = this.session?.token ?? null;
|
|
1262
|
+
if (token === null)
|
|
1263
|
+
return false;
|
|
1264
|
+
const apiBase = this.multiplayer.resolveApiBase(token);
|
|
1265
|
+
if (apiBase === null)
|
|
1266
|
+
return false;
|
|
1267
|
+
try {
|
|
1268
|
+
const res = await fetch(`${apiBase}/api/v1/users/me/presence/activity`, {
|
|
1269
|
+
method: 'DELETE',
|
|
1270
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
1271
|
+
});
|
|
1272
|
+
return res.ok;
|
|
1273
|
+
}
|
|
1274
|
+
catch {
|
|
1275
|
+
return false;
|
|
1276
|
+
}
|
|
1277
|
+
},
|
|
1278
|
+
};
|
|
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) {
|
|
1282
|
+
this.assertInitialized();
|
|
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);
|
|
1292
|
+
return Promise.resolve({ status: 'Unauthorized', completed: false });
|
|
1293
|
+
}
|
|
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;
|
|
1385
|
+
}
|
|
1386
|
+
async trackAnalytics(eventName, input) {
|
|
1387
|
+
this.assertInitialized();
|
|
1388
|
+
const token = this.session?.token ?? null;
|
|
1389
|
+
const apiBase = this.multiplayer.resolveApiBase(token);
|
|
1390
|
+
if (!apiBase)
|
|
1391
|
+
return;
|
|
1392
|
+
const body = {
|
|
1393
|
+
event_name: eventName,
|
|
1394
|
+
event_id: input.eventId ?? `sdk:${this.newId()}`,
|
|
1395
|
+
occurred_at: new Date().toISOString(),
|
|
1396
|
+
user_id: this.session?.user.id,
|
|
1397
|
+
anonymous_id: this.session?.user.id ? undefined : `sdk:${this.newId()}`,
|
|
1398
|
+
session_id: token ? `world:${this.session?.user.id ?? 'guest'}` : undefined,
|
|
1399
|
+
platform: 'web',
|
|
1400
|
+
source: 'client',
|
|
1401
|
+
world_id: this.worldContext?.id,
|
|
1402
|
+
instance_id: input.instanceId ?? undefined,
|
|
1403
|
+
item_id: input.itemId ?? undefined,
|
|
1404
|
+
invite_id: input.inviteId ?? undefined,
|
|
1405
|
+
referrer: input.referrer ?? undefined,
|
|
1406
|
+
properties: this.safeAnalyticsProperties(input.properties),
|
|
1407
|
+
};
|
|
1408
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
1409
|
+
if (token)
|
|
1410
|
+
headers.Authorization = `Bearer ${token}`;
|
|
1411
|
+
const res = await fetch(`${apiBase}/api/v1/analytics/events`, {
|
|
1412
|
+
method: 'POST',
|
|
1413
|
+
headers,
|
|
1414
|
+
body: JSON.stringify(body),
|
|
1415
|
+
keepalive: true,
|
|
1416
|
+
});
|
|
1417
|
+
if (!res.ok)
|
|
1418
|
+
throw new Error(`Helix.analytics: collector responded ${res.status}`);
|
|
1419
|
+
}
|
|
1420
|
+
safeAnalyticsProperties(properties) {
|
|
1421
|
+
if (!properties)
|
|
1422
|
+
return undefined;
|
|
1423
|
+
const out = {};
|
|
1424
|
+
for (const [key, value] of Object.entries(properties)) {
|
|
1425
|
+
if (value === undefined || /password|token|secret|authorization|cookie|payment|card|cvv|private_message|raw_chat|raw_voice|email/i.test(key)) {
|
|
1426
|
+
continue;
|
|
1427
|
+
}
|
|
1428
|
+
out[key] = typeof value === 'string' && value.length > 256 ? `${value.slice(0, 253)}...` : value;
|
|
1429
|
+
}
|
|
1430
|
+
return Object.keys(out).length ? out : undefined;
|
|
1431
|
+
}
|
|
1432
|
+
openDevice(form) {
|
|
1433
|
+
this.assertInitialized();
|
|
1434
|
+
return this.postToShell({ type: 'helix:open-device', form });
|
|
1435
|
+
}
|
|
1436
|
+
onKeyDown = (event) => {
|
|
1437
|
+
if (!this.initialized)
|
|
1438
|
+
return;
|
|
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)
|
|
1447
|
+
return;
|
|
1448
|
+
if (this.isInteractiveUiEvent(event))
|
|
1449
|
+
return;
|
|
1450
|
+
if (this.device.openTablet())
|
|
1451
|
+
event.preventDefault();
|
|
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
|
+
}
|
|
1472
|
+
// Generic shell-mediated request/response over postMessage.
|
|
1473
|
+
request(method, payload, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
1474
|
+
this.assertInitialized();
|
|
1475
|
+
if (!this.shellOrigin) {
|
|
1476
|
+
return Promise.reject(new Error('Helix: not embedded in a HELIX shell'));
|
|
1477
|
+
}
|
|
1478
|
+
const requestId = this.newId();
|
|
1479
|
+
return new Promise((resolve, reject) => {
|
|
1480
|
+
const timer = setTimeout(() => {
|
|
1481
|
+
this.pendingRequests.delete(requestId);
|
|
1482
|
+
reject(new Error(`Helix: ${method} timed out`));
|
|
1483
|
+
}, timeoutMs);
|
|
1484
|
+
this.pendingRequests.set(requestId, {
|
|
1485
|
+
resolve: (v) => {
|
|
1486
|
+
clearTimeout(timer);
|
|
1487
|
+
resolve(v);
|
|
1488
|
+
},
|
|
1489
|
+
reject: (e) => {
|
|
1490
|
+
clearTimeout(timer);
|
|
1491
|
+
reject(e);
|
|
1492
|
+
},
|
|
1493
|
+
});
|
|
1494
|
+
this.post({ type: 'helix:request', requestId, method, payload }, this.shellOrigin);
|
|
1495
|
+
});
|
|
1496
|
+
}
|
|
1497
|
+
newId() {
|
|
1498
|
+
const c = globalThis.crypto;
|
|
1499
|
+
if (c?.randomUUID)
|
|
1500
|
+
return c.randomUUID();
|
|
1501
|
+
return Math.random().toString(36).slice(2) + Date.now().toString(36);
|
|
1502
|
+
}
|
|
1503
|
+
async fetchAvatarLoadout(patch) {
|
|
1504
|
+
const token = this.session?.token ?? null;
|
|
1505
|
+
if (token === null)
|
|
1506
|
+
return null;
|
|
1507
|
+
const apiBase = this.multiplayer.resolveApiBase(token);
|
|
1508
|
+
if (apiBase === null)
|
|
1509
|
+
return null;
|
|
1510
|
+
try {
|
|
1511
|
+
const res = await fetch(`${apiBase}/api/v1/universal-items/avatar/loadout/me`, {
|
|
1512
|
+
method: patch ? 'PATCH' : 'GET',
|
|
1513
|
+
headers: {
|
|
1514
|
+
Authorization: `Bearer ${token}`,
|
|
1515
|
+
...(patch ? { 'Content-Type': 'application/json' } : {}),
|
|
1516
|
+
},
|
|
1517
|
+
body: patch ? JSON.stringify(patch) : undefined,
|
|
1518
|
+
});
|
|
1519
|
+
if (!res.ok)
|
|
1520
|
+
return null;
|
|
1521
|
+
return (await res.json());
|
|
1522
|
+
}
|
|
1523
|
+
catch {
|
|
1524
|
+
return null;
|
|
1525
|
+
}
|
|
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
|
+
}
|
|
1566
|
+
emitAvatarChanged() {
|
|
1567
|
+
for (const listener of this.avatarListeners)
|
|
1568
|
+
listener();
|
|
1569
|
+
}
|
|
73
1570
|
snapshot() {
|
|
1571
|
+
const customizer = this.currentCustomizerContext();
|
|
74
1572
|
return {
|
|
75
1573
|
embedded: this.shellOrigin !== null,
|
|
76
|
-
world: this.
|
|
1574
|
+
world: this.worldContext,
|
|
77
1575
|
user: this.session?.user ?? null,
|
|
1576
|
+
runtimeFidelity: this.runtimeFidelityIntent
|
|
1577
|
+
? { ...this.runtimeFidelityIntent }
|
|
1578
|
+
: null,
|
|
1579
|
+
customizerSubject: customizer.subject,
|
|
1580
|
+
customizerSource: customizer.source,
|
|
78
1581
|
};
|
|
79
1582
|
}
|
|
80
1583
|
assertInitialized() {
|
|
@@ -82,19 +1585,25 @@ class HelixSdk {
|
|
|
82
1585
|
throw new Error('Helix: call Helix.init() before using the SDK');
|
|
83
1586
|
}
|
|
84
1587
|
}
|
|
1588
|
+
// Handshake: announce readiness and wait for the shell's helix:init reply. We RE-POST helix:ready until the
|
|
1589
|
+
// shell answers (or we time out) because the shell may attach its message listener AFTER our first post — it
|
|
1590
|
+
// registers in a post-hydration effect, and a lightweight world (no heavy assets, cached) can fire helix:ready
|
|
1591
|
+
// before then, so a single post would be lost and we'd fall back to embedded=false. Retrying closes that race;
|
|
1592
|
+
// the moment the shell answers (shellOrigin set) we stop, so a shell that's already listening sees just one post.
|
|
85
1593
|
waitForInit() {
|
|
86
1594
|
return new Promise((resolve) => {
|
|
87
|
-
const
|
|
1595
|
+
const deadline = Date.now() + INIT_TIMEOUT_MS;
|
|
1596
|
+
const ready = () => this.post({ type: 'helix:ready', protocolVersion: PROTOCOL_VERSION }, '*');
|
|
1597
|
+
ready();
|
|
88
1598
|
const check = () => {
|
|
89
|
-
if (this.shellOrigin) {
|
|
90
|
-
clearTimeout(timer);
|
|
1599
|
+
if (this.shellOrigin || Date.now() >= deadline) {
|
|
91
1600
|
resolve();
|
|
1601
|
+
return;
|
|
92
1602
|
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
}
|
|
1603
|
+
ready();
|
|
1604
|
+
setTimeout(check, READY_RETRY_MS);
|
|
96
1605
|
};
|
|
97
|
-
check
|
|
1606
|
+
setTimeout(check, READY_RETRY_MS);
|
|
98
1607
|
});
|
|
99
1608
|
}
|
|
100
1609
|
onMessage = (event) => {
|
|
@@ -109,8 +1618,14 @@ class HelixSdk {
|
|
|
109
1618
|
if (this.shellOrigin)
|
|
110
1619
|
return;
|
|
111
1620
|
this.shellOrigin = event.origin;
|
|
112
|
-
this.
|
|
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);
|
|
113
1626
|
this.setSession(msg.session);
|
|
1627
|
+
if (msg.debug)
|
|
1628
|
+
this.enableDebug();
|
|
114
1629
|
break;
|
|
115
1630
|
case 'helix:session':
|
|
116
1631
|
this.setSession(msg.session);
|
|
@@ -126,20 +1641,446 @@ class HelixSdk {
|
|
|
126
1641
|
pending.reject(new Error(`Helix: login ${msg.reason ?? 'failed'}`));
|
|
127
1642
|
break;
|
|
128
1643
|
}
|
|
1644
|
+
case 'helix:response': {
|
|
1645
|
+
const pending = this.pendingRequests.get(msg.requestId);
|
|
1646
|
+
if (!pending)
|
|
1647
|
+
return;
|
|
1648
|
+
this.pendingRequests.delete(msg.requestId);
|
|
1649
|
+
if (msg.ok)
|
|
1650
|
+
pending.resolve(msg.result);
|
|
1651
|
+
else
|
|
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();
|
|
1723
|
+
break;
|
|
1724
|
+
}
|
|
1725
|
+
case 'helix:event': {
|
|
1726
|
+
if (msg.event === 'balance-changed') {
|
|
1727
|
+
const b = msg.data ?? { lix: 0, coins: 0 };
|
|
1728
|
+
for (const l of this.balanceListeners)
|
|
1729
|
+
l(b);
|
|
1730
|
+
}
|
|
1731
|
+
else if (msg.event === 'inventory-changed') {
|
|
1732
|
+
for (const l of this.inventoryListeners)
|
|
1733
|
+
l();
|
|
1734
|
+
}
|
|
1735
|
+
else if (msg.event === 'entitlements-changed') {
|
|
1736
|
+
for (const l of this.entitlementListeners)
|
|
1737
|
+
l();
|
|
1738
|
+
}
|
|
1739
|
+
else if (msg.event === 'avatar-changed' || msg.event === 'equipment-changed') {
|
|
1740
|
+
this.emitAvatarChanged();
|
|
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
|
+
}
|
|
1749
|
+
break;
|
|
1750
|
+
}
|
|
129
1751
|
}
|
|
130
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
|
+
}
|
|
131
1843
|
setSession(session) {
|
|
132
1844
|
const before = this.session?.user.id ?? null;
|
|
1845
|
+
const tokenBefore = this.session?.token ?? null;
|
|
133
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);
|
|
134
1852
|
const after = session?.user.id ?? null;
|
|
135
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();
|
|
136
1857
|
for (const listener of this.listeners)
|
|
137
1858
|
listener(session?.user ?? null);
|
|
138
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
|
+
});
|
|
1875
|
+
}
|
|
1876
|
+
enableDebug() {
|
|
1877
|
+
if (this.debugEnabled)
|
|
1878
|
+
return;
|
|
1879
|
+
this.debugEnabled = true;
|
|
1880
|
+
this.hookConsole();
|
|
1881
|
+
// Flush anything buffered before the shell turned debug on (e.g. early lifecycle logs).
|
|
1882
|
+
if (this.shellOrigin)
|
|
1883
|
+
for (const entry of this.debugRing)
|
|
1884
|
+
this.post({ type: 'helix:log', entry }, this.shellOrigin);
|
|
1885
|
+
}
|
|
1886
|
+
// Capture ALL console output once debug is on (three.js warnings, SDK errors, uncaught logs) — not just
|
|
1887
|
+
// explicit debug.log calls. Pass-through preserves normal console behaviour in the iframe.
|
|
1888
|
+
hookConsole() {
|
|
1889
|
+
if (this.consoleHooked || typeof console === 'undefined')
|
|
1890
|
+
return;
|
|
1891
|
+
this.consoleHooked = true;
|
|
1892
|
+
const levels = ['log', 'info', 'warn', 'error', 'debug'];
|
|
1893
|
+
const c = console;
|
|
1894
|
+
for (const level of levels) {
|
|
1895
|
+
const orig = c[level]?.bind(console);
|
|
1896
|
+
if (!orig)
|
|
1897
|
+
continue;
|
|
1898
|
+
c[level] = (...args) => {
|
|
1899
|
+
this.captureLog(level, args);
|
|
1900
|
+
orig(...args);
|
|
1901
|
+
};
|
|
1902
|
+
}
|
|
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
|
+
}
|
|
1918
|
+
captureLog(level, args) {
|
|
1919
|
+
const entry = { level, args: args.map(stringifyArg), t: Date.now() };
|
|
1920
|
+
this.debugRing.push(entry);
|
|
1921
|
+
if (this.debugRing.length > DEBUG_LOG_MAX)
|
|
1922
|
+
this.debugRing.shift();
|
|
1923
|
+
for (const cb of this.debugListeners) {
|
|
1924
|
+
try {
|
|
1925
|
+
cb(entry);
|
|
1926
|
+
}
|
|
1927
|
+
catch {
|
|
1928
|
+
/* a listener must never break logging */
|
|
1929
|
+
}
|
|
1930
|
+
}
|
|
1931
|
+
if (this.debugEnabled && this.shellOrigin)
|
|
1932
|
+
this.post({ type: 'helix:log', entry }, this.shellOrigin);
|
|
139
1933
|
}
|
|
140
1934
|
post(message, targetOrigin) {
|
|
141
1935
|
window.parent.postMessage(message, targetOrigin);
|
|
142
1936
|
}
|
|
1937
|
+
postToShell(message) {
|
|
1938
|
+
if (!this.shellOrigin)
|
|
1939
|
+
return false;
|
|
1940
|
+
this.post(message, this.shellOrigin);
|
|
1941
|
+
return true;
|
|
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
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
// Normalize a captured image to a transferable ArrayBuffer + a content type for
|
|
2047
|
+
// the shell to upload. Accepts a Blob (browser capture), an ArrayBuffer, or a
|
|
2048
|
+
// Uint8Array. A Blob carries its own MIME; otherwise default to JPEG.
|
|
2049
|
+
async function toBytes(image, contentTypeOverride) {
|
|
2050
|
+
if (typeof Blob !== 'undefined' && image instanceof Blob) {
|
|
2051
|
+
return {
|
|
2052
|
+
bytes: await image.arrayBuffer(),
|
|
2053
|
+
contentType: contentTypeOverride || image.type || 'image/jpeg',
|
|
2054
|
+
};
|
|
2055
|
+
}
|
|
2056
|
+
if (image instanceof Uint8Array) {
|
|
2057
|
+
const copy = image.slice();
|
|
2058
|
+
return { bytes: copy.buffer, contentType: contentTypeOverride || 'image/jpeg' };
|
|
2059
|
+
}
|
|
2060
|
+
// Remaining case is ArrayBuffer (the Blob branch above returns); the compound
|
|
2061
|
+
// typeof-guard stops TS from negative-narrowing Blob, so assert it here.
|
|
2062
|
+
return { bytes: image, contentType: contentTypeOverride || 'image/jpeg' };
|
|
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
|
+
}
|
|
2071
|
+
// Serialize a console arg to a string the shell can print: strings as-is, Errors to their stack, other
|
|
2072
|
+
// objects to compact JSON (falling back to String() on cyclic/unserializable values).
|
|
2073
|
+
function stringifyArg(a) {
|
|
2074
|
+
if (typeof a === 'string')
|
|
2075
|
+
return a;
|
|
2076
|
+
if (a instanceof Error)
|
|
2077
|
+
return a.stack ?? `${a.name}: ${a.message}`;
|
|
2078
|
+
try {
|
|
2079
|
+
return typeof a === 'object' && a !== null ? JSON.stringify(a) : String(a);
|
|
2080
|
+
}
|
|
2081
|
+
catch {
|
|
2082
|
+
return String(a);
|
|
2083
|
+
}
|
|
143
2084
|
}
|
|
144
2085
|
// Worlds import this singleton: `import { Helix } from '@hypersoniclabs/helix-sdk'`.
|
|
145
2086
|
export const Helix = new HelixSdk();
|