@hypersoniclabs/helix-sdk 0.1.1 → 0.1.2
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 +101 -0
- package/dist/camera.d.ts +14 -0
- package/dist/camera.js +72 -0
- package/dist/camera.js.map +1 -0
- package/dist/index.d.ts +106 -2
- package/dist/index.js +640 -9
- package/dist/index.js.map +1 -1
- package/dist/multiplayer-contract/credential.d.ts +42 -0
- package/dist/multiplayer-contract/credential.js +5 -0
- package/dist/multiplayer-contract/credential.js.map +1 -0
- package/dist/multiplayer-contract/index.d.ts +14 -0
- package/dist/multiplayer-contract/index.js +30 -0
- package/dist/multiplayer-contract/index.js.map +1 -0
- package/dist/multiplayer-contract/messages.d.ts +284 -0
- package/dist/multiplayer-contract/messages.js +111 -0
- package/dist/multiplayer-contract/messages.js.map +1 -0
- package/dist/multiplayer-contract/room.d.ts +126 -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 +61 -0
- package/dist/multiplayer-contract/state.js +15 -0
- package/dist/multiplayer-contract/state.js.map +1 -0
- package/dist/multiplayer.d.ts +133 -0
- package/dist/multiplayer.js +334 -0
- package/dist/multiplayer.js.map +1 -0
- package/dist/protocol.d.ts +196 -1
- package/dist/protocol.js +16 -4
- package/dist/protocol.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +14 -1
package/dist/index.js
CHANGED
|
@@ -1,26 +1,77 @@
|
|
|
1
1
|
import { isShellMessage, PROTOCOL_VERSION, } from './protocol';
|
|
2
|
-
|
|
2
|
+
import { HelixMultiplayer } from './multiplayer';
|
|
3
|
+
import { captureCanvas } from './camera';
|
|
4
|
+
export { cropRectForAspect, captureCanvas } from './camera';
|
|
5
|
+
// The multiplayer wire contract. Re-exported here so `@hypersoniclabs/helix-sdk` root consumers (and
|
|
6
|
+
// classic node-resolution type imports, e.g. the backend minting RoomCredentialClaims) get it; bundler
|
|
7
|
+
// consumers that want only the contract import the lighter '@hypersoniclabs/helix-sdk/multiplayer-contract'.
|
|
8
|
+
export * from './multiplayer-contract';
|
|
9
|
+
// Statuses where the player ends up owning the thing.
|
|
10
|
+
const COMPLETED_STATUSES = new Set([
|
|
11
|
+
'Granted',
|
|
12
|
+
'Claimed',
|
|
13
|
+
'AlreadyOwned',
|
|
14
|
+
]);
|
|
15
|
+
const INIT_TIMEOUT_MS = 8000; // re-post helix:ready up to this long before falling back to standalone — a cold shell (Next route compile) can take >3s to mount its frame + reply
|
|
16
|
+
const READY_RETRY_MS = 200; // re-post helix:ready this often until the shell answers (handshake race — see waitForInit)
|
|
3
17
|
const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
|
|
18
|
+
const DEBUG_LOG_MAX = 200; // bounded ring of recent log entries (overlay backfill + pre-init forward flush)
|
|
19
|
+
// Reads/grants should resolve fast; a purchase may sit on the confirm popup, so
|
|
20
|
+
// it uses the longer LOGIN_TIMEOUT_MS instead.
|
|
21
|
+
const REQUEST_TIMEOUT_MS = 30 * 1000;
|
|
22
|
+
// A photo upload (encode + multipart POST to R2) is slower than a read; give it
|
|
23
|
+
// its own budget, shorter than the confirm-popup login window.
|
|
24
|
+
const UPLOAD_TIMEOUT_MS = 60 * 1000;
|
|
4
25
|
class HelixSdk {
|
|
5
26
|
shellOrigin = null;
|
|
6
27
|
session = null;
|
|
7
28
|
world = null;
|
|
8
29
|
initialized = false;
|
|
9
30
|
listeners = new Set();
|
|
31
|
+
debugEnabled = false;
|
|
32
|
+
debugRing = [];
|
|
33
|
+
debugListeners = new Set();
|
|
34
|
+
consoleHooked = false;
|
|
10
35
|
pendingLogins = new Map();
|
|
36
|
+
pendingRequests = new Map();
|
|
37
|
+
balanceListeners = new Set();
|
|
38
|
+
inventoryListeners = new Set();
|
|
39
|
+
avatarListeners = new Set();
|
|
11
40
|
// Performs the shell handshake. Call once at world start, before any other
|
|
12
41
|
// Helix API. Resolves with embedded=false if no shell answers (local dev).
|
|
13
42
|
async init() {
|
|
14
43
|
if (this.initialized)
|
|
15
44
|
return this.snapshot();
|
|
16
45
|
window.addEventListener('message', this.onMessage);
|
|
46
|
+
window.addEventListener('keydown', this.onKeyDown);
|
|
17
47
|
if (window.parent !== window) {
|
|
18
|
-
this.post({ type: 'helix:ready', protocolVersion: PROTOCOL_VERSION }, '*');
|
|
19
48
|
await this.waitForInit();
|
|
20
49
|
}
|
|
21
50
|
this.initialized = true;
|
|
22
51
|
return this.snapshot();
|
|
23
52
|
}
|
|
53
|
+
// Multiplayer (pillar D): Helix.multiplayer.joinRoom(). Reads the world_session token + world id off
|
|
54
|
+
// this singleton; the heavy Colyseus client is dynamically imported only on join.
|
|
55
|
+
multiplayer = new HelixMultiplayer({
|
|
56
|
+
isInitialized: () => this.initialized,
|
|
57
|
+
getToken: () => this.session?.token ?? null,
|
|
58
|
+
getWorldId: () => this.world?.id ?? null,
|
|
59
|
+
});
|
|
60
|
+
// Debug surface. A world's own console lives in its cross-origin iframe — invisible to DevTools / an
|
|
61
|
+
// automation harness attached to the shell, and to teammates without that frame selected. debug.log feeds
|
|
62
|
+
// a bounded ring an in-world overlay can render (onLog/recent), and — when the shell enabled debug
|
|
63
|
+
// (?debug) — is mirrored to the shell frame's console via helix:log. enableDebug() also hooks console.*
|
|
64
|
+
// so ALL world output is captured, not just explicit debug.log calls. enabled() is a fn (the flag flips
|
|
65
|
+
// at init, after the field initializer runs).
|
|
66
|
+
debug = {
|
|
67
|
+
enabled: () => this.debugEnabled,
|
|
68
|
+
log: (...args) => this.captureLog('info', args),
|
|
69
|
+
onLog: (cb) => {
|
|
70
|
+
this.debugListeners.add(cb);
|
|
71
|
+
return () => this.debugListeners.delete(cb);
|
|
72
|
+
},
|
|
73
|
+
recent: () => this.debugRing.slice(),
|
|
74
|
+
};
|
|
24
75
|
auth = {
|
|
25
76
|
getUser: async () => {
|
|
26
77
|
this.assertInitialized();
|
|
@@ -65,11 +116,475 @@ class HelixSdk {
|
|
|
65
116
|
return () => this.listeners.delete(listener);
|
|
66
117
|
},
|
|
67
118
|
};
|
|
119
|
+
notify = {
|
|
120
|
+
show: (notification) => {
|
|
121
|
+
this.assertInitialized();
|
|
122
|
+
return this.postToShell({ type: 'helix:notify', notification });
|
|
123
|
+
},
|
|
124
|
+
success: (title, message) => this.notify.show({ kind: 'success', title, message }),
|
|
125
|
+
failure: (title, message) => this.notify.show({ kind: 'failure', title, message }),
|
|
126
|
+
notification: (title, message) => this.notify.show({ kind: 'notification', title, message }),
|
|
127
|
+
message: (title, message) => this.notify.show({ kind: 'message', title, message }),
|
|
128
|
+
};
|
|
129
|
+
prompts = {
|
|
130
|
+
set: (prompt) => {
|
|
131
|
+
this.assertInitialized();
|
|
132
|
+
return this.postToShell({ type: 'helix:set-interaction-prompt', prompt });
|
|
133
|
+
},
|
|
134
|
+
clear: (promptId) => {
|
|
135
|
+
this.assertInitialized();
|
|
136
|
+
return this.postToShell({ type: 'helix:clear-interaction-prompt', promptId });
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
device = {
|
|
140
|
+
openTablet: () => this.openDevice('tablet'),
|
|
141
|
+
openPhone: () => this.openDevice('phone'),
|
|
142
|
+
};
|
|
68
143
|
// World-scoped session token for direct platform API calls (used by later
|
|
69
144
|
// SDK modules; exposed for advanced cases). Null when unauthenticated.
|
|
70
145
|
getSessionToken() {
|
|
71
146
|
return this.session?.token ?? null;
|
|
72
147
|
}
|
|
148
|
+
// ─────────────────────────── wallet ───────────────────────────
|
|
149
|
+
wallet = {
|
|
150
|
+
// The player's current LIX + Coins balances.
|
|
151
|
+
getBalance: async () => {
|
|
152
|
+
this.assertInitialized();
|
|
153
|
+
if (!this.shellOrigin)
|
|
154
|
+
return { lix: 0, coins: 0 };
|
|
155
|
+
return this.request('wallet.getBalance');
|
|
156
|
+
},
|
|
157
|
+
// Fires after the wallet changes (e.g. a purchase settles). Returns an
|
|
158
|
+
// unsubscribe fn.
|
|
159
|
+
onBalanceChanged: (cb) => {
|
|
160
|
+
this.balanceListeners.add(cb);
|
|
161
|
+
return () => this.balanceListeners.delete(cb);
|
|
162
|
+
},
|
|
163
|
+
};
|
|
164
|
+
// ────────────────────────── marketplace ──────────────────────────
|
|
165
|
+
marketplace = {
|
|
166
|
+
// Request a server-settled purchase of a marketplace (catalog) item. The
|
|
167
|
+
// shell raises the confirm popup and settles; the world reacts to the result.
|
|
168
|
+
purchaseItem: (itemId) => this.purchase(`item:${itemId}`),
|
|
169
|
+
// Request a server-settled purchase of a product registered on the world.
|
|
170
|
+
purchaseProduct: (productId) => this.purchase(productId),
|
|
171
|
+
// Browse marketplace listings.
|
|
172
|
+
getListings: async (query) => {
|
|
173
|
+
this.assertInitialized();
|
|
174
|
+
if (!this.shellOrigin)
|
|
175
|
+
return [];
|
|
176
|
+
return this.request('marketplace.getListings', query ?? {});
|
|
177
|
+
},
|
|
178
|
+
// Product/listing + the player's live balance + eligibility, in one call —
|
|
179
|
+
// for building a custom confirm UI (the built-in popup uses this internally).
|
|
180
|
+
getPurchaseContext: async (ref) => {
|
|
181
|
+
this.assertInitialized();
|
|
182
|
+
if (!this.shellOrigin)
|
|
183
|
+
return null;
|
|
184
|
+
return this.request('iwp.getContext', { ref });
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
analytics = {
|
|
188
|
+
track: (eventName, input = {}) => this.trackAnalytics(eventName, input),
|
|
189
|
+
};
|
|
190
|
+
// ─────────────────────────── inventory ───────────────────────────
|
|
191
|
+
inventory = {
|
|
192
|
+
// Whether the current player owns at least one of an item. Works across
|
|
193
|
+
// worlds and creators (universal items) — the basis for VIP / season passes.
|
|
194
|
+
hasItem: async (itemId) => {
|
|
195
|
+
this.assertInitialized();
|
|
196
|
+
if (!this.shellOrigin)
|
|
197
|
+
return false;
|
|
198
|
+
return this.request('inventory.hasItem', { itemId });
|
|
199
|
+
},
|
|
200
|
+
getQuantity: async (itemId) => {
|
|
201
|
+
this.assertInitialized();
|
|
202
|
+
if (!this.shellOrigin)
|
|
203
|
+
return 0;
|
|
204
|
+
return this.request('inventory.getQuantity', { itemId });
|
|
205
|
+
},
|
|
206
|
+
// All items the current player owns.
|
|
207
|
+
getMyItems: async () => {
|
|
208
|
+
this.assertInitialized();
|
|
209
|
+
if (!this.shellOrigin)
|
|
210
|
+
return [];
|
|
211
|
+
return this.request('inventory.getMyItems');
|
|
212
|
+
},
|
|
213
|
+
// Equip an owned cosmetic item (visual).
|
|
214
|
+
equipItem: async (itemId) => {
|
|
215
|
+
this.assertInitialized();
|
|
216
|
+
if (!this.shellOrigin)
|
|
217
|
+
return;
|
|
218
|
+
await this.request('inventory.equipItem', { itemId });
|
|
219
|
+
},
|
|
220
|
+
onInventoryChanged: (cb) => {
|
|
221
|
+
this.inventoryListeners.add(cb);
|
|
222
|
+
return () => this.inventoryListeners.delete(cb);
|
|
223
|
+
},
|
|
224
|
+
};
|
|
225
|
+
// Durable, per-world key–value storage (the Roblox DataStore analog). The
|
|
226
|
+
// right place for anything that must survive a session: player progress,
|
|
227
|
+
// settings, world state. Scoped to THIS world; namespace per-player data
|
|
228
|
+
// yourself (e.g. `player:${userId}`). Value-bearing writes should be made
|
|
229
|
+
// server-authoritatively. Free for every world (quotas + write rate limits
|
|
230
|
+
// apply). See https://docs3.helixgame.com/docs/platform-api/data-store
|
|
231
|
+
dataStore = {
|
|
232
|
+
// Read a durable value by key. Returns null if unset (or in preview mode,
|
|
233
|
+
// when the world is opened directly with no shell).
|
|
234
|
+
get: async (key) => {
|
|
235
|
+
this.assertInitialized();
|
|
236
|
+
if (!this.shellOrigin)
|
|
237
|
+
return null;
|
|
238
|
+
return this.request('dataStore.get', { key });
|
|
239
|
+
},
|
|
240
|
+
// Create or overwrite a durable value. No-op in preview mode (read-only).
|
|
241
|
+
// Subject to the world's free-tier quotas and write rate limit; a rejected
|
|
242
|
+
// write surfaces as a thrown error (e.g. RateLimited / quota exceeded).
|
|
243
|
+
set: async (key, value) => {
|
|
244
|
+
this.assertInitialized();
|
|
245
|
+
if (!this.shellOrigin)
|
|
246
|
+
return;
|
|
247
|
+
await this.request('dataStore.set', { key, value });
|
|
248
|
+
},
|
|
249
|
+
// Remove a durable value by key. No-op in preview mode.
|
|
250
|
+
delete: async (key) => {
|
|
251
|
+
this.assertInitialized();
|
|
252
|
+
if (!this.shellOrigin)
|
|
253
|
+
return;
|
|
254
|
+
await this.request('dataStore.delete', { key });
|
|
255
|
+
},
|
|
256
|
+
// List stored keys, optionally filtered by prefix (e.g. `player:`). Returns
|
|
257
|
+
// keys only (fetch values with get), mirroring Roblox ListKeysAsync.
|
|
258
|
+
list: async (prefix) => {
|
|
259
|
+
this.assertInitialized();
|
|
260
|
+
if (!this.shellOrigin)
|
|
261
|
+
return [];
|
|
262
|
+
return this.request('dataStore.list', { prefix });
|
|
263
|
+
},
|
|
264
|
+
};
|
|
265
|
+
// ─────────────────────────── camera ───────────────────────────
|
|
266
|
+
//
|
|
267
|
+
// The universal world camera's cloud side. Photo-mode UI + camera control live
|
|
268
|
+
// in the engine (which owns three.js + the render loop); the engine hands the
|
|
269
|
+
// captured pixels here to persist them to the player's account, where they show
|
|
270
|
+
// up in the phone's Gallery on any device (account-scoped, cross-device).
|
|
271
|
+
//
|
|
272
|
+
// `capture` is a pure DOM helper a world/engine can use to turn its rendered
|
|
273
|
+
// canvas into an encoded, aspect-cropped Blob; `savePhoto` is the shell-mediated
|
|
274
|
+
// upload. See https://docs3.helixgame.com/docs/platform-api/camera
|
|
275
|
+
camera = {
|
|
276
|
+
// True when running inside a HELIX shell (so a save can actually reach the
|
|
277
|
+
// account). False in local/preview — capture still works, cloud save no-ops.
|
|
278
|
+
available: () => {
|
|
279
|
+
this.assertInitialized();
|
|
280
|
+
return this.shellOrigin !== null;
|
|
281
|
+
},
|
|
282
|
+
// Encode a (already-rendered) canvas to a Blob, centre-cropped to `aspect`.
|
|
283
|
+
// Pure capture — no upload. The caller must render into the canvas in the
|
|
284
|
+
// same tick (WebGL clears its buffer between frames). Re-exported as
|
|
285
|
+
// `captureCanvas` for non-camera use.
|
|
286
|
+
capture: (canvas, opts) => captureCanvas(canvas, opts),
|
|
287
|
+
// Persist a captured photo to the player's account; it appears in the phone
|
|
288
|
+
// Gallery on every device, tagged with the world it was taken in (the shell
|
|
289
|
+
// stamps the world name authoritatively). Resolves null in preview mode
|
|
290
|
+
// (no shell) — never a fake success. Requires the `camera.capture` scope in
|
|
291
|
+
// the world manifest; a missing scope rejects.
|
|
292
|
+
savePhoto: async (image, meta) => {
|
|
293
|
+
this.assertInitialized();
|
|
294
|
+
if (!this.shellOrigin)
|
|
295
|
+
return null;
|
|
296
|
+
const { bytes, contentType } = await toBytes(image, meta?.contentType);
|
|
297
|
+
return this.request('camera.savePhoto', { bytes, contentType, caption: meta?.caption, aspect: meta?.aspect ?? 'free' }, UPLOAD_TIMEOUT_MS);
|
|
298
|
+
},
|
|
299
|
+
};
|
|
300
|
+
// ─────────────────────────── avatar ───────────────────────────
|
|
301
|
+
avatar = {
|
|
302
|
+
openCreator: async () => {
|
|
303
|
+
this.assertInitialized();
|
|
304
|
+
if (!this.shellOrigin)
|
|
305
|
+
return false;
|
|
306
|
+
return this.request('avatar.openCreator');
|
|
307
|
+
},
|
|
308
|
+
getLoadout: async () => {
|
|
309
|
+
this.assertInitialized();
|
|
310
|
+
if (!this.shellOrigin)
|
|
311
|
+
return this.fetchAvatarLoadout();
|
|
312
|
+
try {
|
|
313
|
+
return await this.request('avatar.getLoadout');
|
|
314
|
+
}
|
|
315
|
+
catch {
|
|
316
|
+
return this.fetchAvatarLoadout();
|
|
317
|
+
}
|
|
318
|
+
},
|
|
319
|
+
updateLoadout: async (patch) => {
|
|
320
|
+
this.assertInitialized();
|
|
321
|
+
if (!this.shellOrigin)
|
|
322
|
+
return this.fetchAvatarLoadout(patch);
|
|
323
|
+
try {
|
|
324
|
+
const loadout = await this.request('avatar.updateLoadout', patch);
|
|
325
|
+
this.emitAvatarChanged();
|
|
326
|
+
return loadout;
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
const loadout = await this.fetchAvatarLoadout(patch);
|
|
330
|
+
if (loadout)
|
|
331
|
+
this.emitAvatarChanged();
|
|
332
|
+
return loadout;
|
|
333
|
+
}
|
|
334
|
+
},
|
|
335
|
+
// The local player's equipped "universal avatar" — the single avatar a world
|
|
336
|
+
// renders for them (equipped → auto-equip first owned → default). Resolved by
|
|
337
|
+
// a DIRECT call to the platform's public equipped-avatar endpoint — no shell
|
|
338
|
+
// round-trip (the generic helix:request bridge is not implemented by the
|
|
339
|
+
// shells). The session supplies the player's own user id; the API base is
|
|
340
|
+
// Helix.multiplayer.configure({ apiBaseUrl }) else the session token's `iss`.
|
|
341
|
+
// Returns null for guests / outside a shell / on ANY resolution failure — the
|
|
342
|
+
// world falls back to its default body, never breaks.
|
|
343
|
+
getEquipped: async () => {
|
|
344
|
+
this.assertInitialized();
|
|
345
|
+
const user = this.session?.user;
|
|
346
|
+
const token = this.session?.token ?? null;
|
|
347
|
+
if (!user || token === null)
|
|
348
|
+
return null;
|
|
349
|
+
const apiBase = this.multiplayer.resolveApiBase(token);
|
|
350
|
+
if (apiBase === null)
|
|
351
|
+
return null;
|
|
352
|
+
try {
|
|
353
|
+
const res = await fetch(`${apiBase}/api/v1/universal-items/avatar/equipped/users/${encodeURIComponent(user.id)}`);
|
|
354
|
+
if (!res.ok)
|
|
355
|
+
return null;
|
|
356
|
+
const dto = (await res.json());
|
|
357
|
+
if (!dto || (dto.source !== 'equipped' && dto.source !== 'auto' && dto.source !== 'default'))
|
|
358
|
+
return null;
|
|
359
|
+
return {
|
|
360
|
+
source: dto.source,
|
|
361
|
+
inventoryItemId: typeof dto.inventoryItemId === 'string' ? dto.inventoryItemId : null,
|
|
362
|
+
itemId: typeof dto.itemId === 'string' ? dto.itemId : null,
|
|
363
|
+
glbUrl: typeof dto.glbUrl === 'string' ? dto.glbUrl : null,
|
|
364
|
+
skeleton: typeof dto.skeleton === 'string' ? dto.skeleton : null,
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
catch {
|
|
368
|
+
return null;
|
|
369
|
+
}
|
|
370
|
+
},
|
|
371
|
+
onAvatarChanged: (cb) => {
|
|
372
|
+
this.avatarListeners.add(cb);
|
|
373
|
+
return () => this.avatarListeners.delete(cb);
|
|
374
|
+
},
|
|
375
|
+
};
|
|
376
|
+
// ─────────────────────────── presence ───────────────────────────
|
|
377
|
+
presence = {
|
|
378
|
+
// Push a live rich-presence activity for the local player — enriches the
|
|
379
|
+
// baseline "In [World]" shown to their friends (sidebar + profile), e.g.
|
|
380
|
+
// "Racing — lap 3/5". Dynamic: pass whatever the moment calls for, no
|
|
381
|
+
// registration. `image` defaults to the world thumbnail when omitted.
|
|
382
|
+
//
|
|
383
|
+
// SERVER-AUTHORITATIVE (by design): this posts to the authenticated presence
|
|
384
|
+
// endpoint as the player's own session; the server sets activity ONLY for
|
|
385
|
+
// that player and ONLY for the world they are currently in — a world can
|
|
386
|
+
// never set another player's status. When the room runtime lands it will set
|
|
387
|
+
// activity server-to-server after authenticating the player into its
|
|
388
|
+
// instance; the API and validation are already shaped for that.
|
|
389
|
+
//
|
|
390
|
+
// Governed by the player's privacy settings (visibility + hide-activity):
|
|
391
|
+
// if they've hidden activity or restricted who sees them, the server never
|
|
392
|
+
// emits it. Text is length-capped, rate-limited, and moderated server-side.
|
|
393
|
+
//
|
|
394
|
+
// Returns true on success; false for guests / outside a shell / not in a
|
|
395
|
+
// world / rejected — never throws into the world loop.
|
|
396
|
+
setActivity: async (activity) => {
|
|
397
|
+
this.assertInitialized();
|
|
398
|
+
const token = this.session?.token ?? null;
|
|
399
|
+
if (token === null)
|
|
400
|
+
return false;
|
|
401
|
+
const apiBase = this.multiplayer.resolveApiBase(token);
|
|
402
|
+
if (apiBase === null)
|
|
403
|
+
return false;
|
|
404
|
+
const worldId = this.world?.id ?? undefined;
|
|
405
|
+
try {
|
|
406
|
+
const res = await fetch(`${apiBase}/api/v1/users/me/presence/activity`, {
|
|
407
|
+
method: 'POST',
|
|
408
|
+
headers: {
|
|
409
|
+
'Content-Type': 'application/json',
|
|
410
|
+
Authorization: `Bearer ${token}`,
|
|
411
|
+
},
|
|
412
|
+
body: JSON.stringify({
|
|
413
|
+
state: activity.state,
|
|
414
|
+
details: activity.details,
|
|
415
|
+
image: activity.image,
|
|
416
|
+
party: activity.party,
|
|
417
|
+
joinable: activity.joinable,
|
|
418
|
+
worldId,
|
|
419
|
+
}),
|
|
420
|
+
});
|
|
421
|
+
return res.ok;
|
|
422
|
+
}
|
|
423
|
+
catch {
|
|
424
|
+
return false;
|
|
425
|
+
}
|
|
426
|
+
},
|
|
427
|
+
// Clear any activity the world set, falling back to the baseline "In
|
|
428
|
+
// [World]". Also happens automatically when the player leaves the world.
|
|
429
|
+
clearActivity: async () => {
|
|
430
|
+
this.assertInitialized();
|
|
431
|
+
const token = this.session?.token ?? null;
|
|
432
|
+
if (token === null)
|
|
433
|
+
return false;
|
|
434
|
+
const apiBase = this.multiplayer.resolveApiBase(token);
|
|
435
|
+
if (apiBase === null)
|
|
436
|
+
return false;
|
|
437
|
+
try {
|
|
438
|
+
const res = await fetch(`${apiBase}/api/v1/users/me/presence/activity`, {
|
|
439
|
+
method: 'DELETE',
|
|
440
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
441
|
+
});
|
|
442
|
+
return res.ok;
|
|
443
|
+
}
|
|
444
|
+
catch {
|
|
445
|
+
return false;
|
|
446
|
+
}
|
|
447
|
+
},
|
|
448
|
+
};
|
|
449
|
+
// Shared purchase path. The SDK mints a stable idempotency key per attempt
|
|
450
|
+
// (reused by the shell across confirm-popup retries) and asks the shell to
|
|
451
|
+
// settle. Not embedded (local dev) → Unauthorized, never a fake success.
|
|
452
|
+
purchase(ref) {
|
|
453
|
+
this.assertInitialized();
|
|
454
|
+
if (!this.shellOrigin) {
|
|
455
|
+
return Promise.resolve({ status: 'Unauthorized', completed: false });
|
|
456
|
+
}
|
|
457
|
+
const idempotencyKey = this.newId();
|
|
458
|
+
return this.request('marketplace.purchase', { ref, idempotencyKey }, LOGIN_TIMEOUT_MS).then((raw) => ({
|
|
459
|
+
...raw,
|
|
460
|
+
completed: COMPLETED_STATUSES.has(raw.status),
|
|
461
|
+
}));
|
|
462
|
+
}
|
|
463
|
+
async trackAnalytics(eventName, input) {
|
|
464
|
+
this.assertInitialized();
|
|
465
|
+
const token = this.session?.token ?? null;
|
|
466
|
+
const apiBase = this.multiplayer.resolveApiBase(token);
|
|
467
|
+
if (!apiBase)
|
|
468
|
+
return;
|
|
469
|
+
const body = {
|
|
470
|
+
event_name: eventName,
|
|
471
|
+
event_id: input.eventId ?? `sdk:${this.newId()}`,
|
|
472
|
+
occurred_at: new Date().toISOString(),
|
|
473
|
+
user_id: this.session?.user.id,
|
|
474
|
+
anonymous_id: this.session?.user.id ? undefined : `sdk:${this.newId()}`,
|
|
475
|
+
session_id: token ? `world:${this.session?.user.id ?? 'guest'}` : undefined,
|
|
476
|
+
platform: 'web',
|
|
477
|
+
source: 'client',
|
|
478
|
+
world_id: this.world?.id,
|
|
479
|
+
instance_id: input.instanceId ?? undefined,
|
|
480
|
+
item_id: input.itemId ?? undefined,
|
|
481
|
+
invite_id: input.inviteId ?? undefined,
|
|
482
|
+
referrer: input.referrer ?? undefined,
|
|
483
|
+
properties: this.safeAnalyticsProperties(input.properties),
|
|
484
|
+
};
|
|
485
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
486
|
+
if (token)
|
|
487
|
+
headers.Authorization = `Bearer ${token}`;
|
|
488
|
+
const res = await fetch(`${apiBase}/api/v1/analytics/events`, {
|
|
489
|
+
method: 'POST',
|
|
490
|
+
headers,
|
|
491
|
+
body: JSON.stringify(body),
|
|
492
|
+
keepalive: true,
|
|
493
|
+
});
|
|
494
|
+
if (!res.ok)
|
|
495
|
+
throw new Error(`Helix.analytics: collector responded ${res.status}`);
|
|
496
|
+
}
|
|
497
|
+
safeAnalyticsProperties(properties) {
|
|
498
|
+
if (!properties)
|
|
499
|
+
return undefined;
|
|
500
|
+
const out = {};
|
|
501
|
+
for (const [key, value] of Object.entries(properties)) {
|
|
502
|
+
if (value === undefined || /password|token|secret|authorization|cookie|payment|card|cvv|private_message|raw_chat|raw_voice|email/i.test(key)) {
|
|
503
|
+
continue;
|
|
504
|
+
}
|
|
505
|
+
out[key] = typeof value === 'string' && value.length > 256 ? `${value.slice(0, 253)}...` : value;
|
|
506
|
+
}
|
|
507
|
+
return Object.keys(out).length ? out : undefined;
|
|
508
|
+
}
|
|
509
|
+
openDevice(form) {
|
|
510
|
+
this.assertInitialized();
|
|
511
|
+
return this.postToShell({ type: 'helix:open-device', form });
|
|
512
|
+
}
|
|
513
|
+
onKeyDown = (event) => {
|
|
514
|
+
if (!this.initialized)
|
|
515
|
+
return;
|
|
516
|
+
if (event.key !== 'Escape' || event.repeat || event.defaultPrevented)
|
|
517
|
+
return;
|
|
518
|
+
const target = event.target;
|
|
519
|
+
const tag = target?.tagName?.toLowerCase();
|
|
520
|
+
const isTyping = target?.isContentEditable ||
|
|
521
|
+
tag === 'input' ||
|
|
522
|
+
tag === 'textarea' ||
|
|
523
|
+
tag === 'select';
|
|
524
|
+
if (isTyping)
|
|
525
|
+
return;
|
|
526
|
+
if (this.device.openTablet())
|
|
527
|
+
event.preventDefault();
|
|
528
|
+
};
|
|
529
|
+
// Generic shell-mediated request/response over postMessage.
|
|
530
|
+
request(method, payload, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
531
|
+
this.assertInitialized();
|
|
532
|
+
if (!this.shellOrigin) {
|
|
533
|
+
return Promise.reject(new Error('Helix: not embedded in a HELIX shell'));
|
|
534
|
+
}
|
|
535
|
+
const requestId = this.newId();
|
|
536
|
+
return new Promise((resolve, reject) => {
|
|
537
|
+
const timer = setTimeout(() => {
|
|
538
|
+
this.pendingRequests.delete(requestId);
|
|
539
|
+
reject(new Error(`Helix: ${method} timed out`));
|
|
540
|
+
}, timeoutMs);
|
|
541
|
+
this.pendingRequests.set(requestId, {
|
|
542
|
+
resolve: (v) => {
|
|
543
|
+
clearTimeout(timer);
|
|
544
|
+
resolve(v);
|
|
545
|
+
},
|
|
546
|
+
reject: (e) => {
|
|
547
|
+
clearTimeout(timer);
|
|
548
|
+
reject(e);
|
|
549
|
+
},
|
|
550
|
+
});
|
|
551
|
+
this.post({ type: 'helix:request', requestId, method, payload }, this.shellOrigin);
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
newId() {
|
|
555
|
+
const c = globalThis.crypto;
|
|
556
|
+
if (c?.randomUUID)
|
|
557
|
+
return c.randomUUID();
|
|
558
|
+
return Math.random().toString(36).slice(2) + Date.now().toString(36);
|
|
559
|
+
}
|
|
560
|
+
async fetchAvatarLoadout(patch) {
|
|
561
|
+
const token = this.session?.token ?? null;
|
|
562
|
+
if (token === null)
|
|
563
|
+
return null;
|
|
564
|
+
const apiBase = this.multiplayer.resolveApiBase(token);
|
|
565
|
+
if (apiBase === null)
|
|
566
|
+
return null;
|
|
567
|
+
try {
|
|
568
|
+
const res = await fetch(`${apiBase}/api/v1/universal-items/avatar/loadout/me`, {
|
|
569
|
+
method: patch ? 'PATCH' : 'GET',
|
|
570
|
+
headers: {
|
|
571
|
+
Authorization: `Bearer ${token}`,
|
|
572
|
+
...(patch ? { 'Content-Type': 'application/json' } : {}),
|
|
573
|
+
},
|
|
574
|
+
body: patch ? JSON.stringify(patch) : undefined,
|
|
575
|
+
});
|
|
576
|
+
if (!res.ok)
|
|
577
|
+
return null;
|
|
578
|
+
return (await res.json());
|
|
579
|
+
}
|
|
580
|
+
catch {
|
|
581
|
+
return null;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
emitAvatarChanged() {
|
|
585
|
+
for (const listener of this.avatarListeners)
|
|
586
|
+
listener();
|
|
587
|
+
}
|
|
73
588
|
snapshot() {
|
|
74
589
|
return {
|
|
75
590
|
embedded: this.shellOrigin !== null,
|
|
@@ -82,19 +597,25 @@ class HelixSdk {
|
|
|
82
597
|
throw new Error('Helix: call Helix.init() before using the SDK');
|
|
83
598
|
}
|
|
84
599
|
}
|
|
600
|
+
// Handshake: announce readiness and wait for the shell's helix:init reply. We RE-POST helix:ready until the
|
|
601
|
+
// shell answers (or we time out) because the shell may attach its message listener AFTER our first post — it
|
|
602
|
+
// registers in a post-hydration effect, and a lightweight world (no heavy assets, cached) can fire helix:ready
|
|
603
|
+
// before then, so a single post would be lost and we'd fall back to embedded=false. Retrying closes that race;
|
|
604
|
+
// the moment the shell answers (shellOrigin set) we stop, so a shell that's already listening sees just one post.
|
|
85
605
|
waitForInit() {
|
|
86
606
|
return new Promise((resolve) => {
|
|
87
|
-
const
|
|
607
|
+
const deadline = Date.now() + INIT_TIMEOUT_MS;
|
|
608
|
+
const ready = () => this.post({ type: 'helix:ready', protocolVersion: PROTOCOL_VERSION }, '*');
|
|
609
|
+
ready();
|
|
88
610
|
const check = () => {
|
|
89
|
-
if (this.shellOrigin) {
|
|
90
|
-
clearTimeout(timer);
|
|
611
|
+
if (this.shellOrigin || Date.now() >= deadline) {
|
|
91
612
|
resolve();
|
|
613
|
+
return;
|
|
92
614
|
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
}
|
|
615
|
+
ready();
|
|
616
|
+
setTimeout(check, READY_RETRY_MS);
|
|
96
617
|
};
|
|
97
|
-
check
|
|
618
|
+
setTimeout(check, READY_RETRY_MS);
|
|
98
619
|
});
|
|
99
620
|
}
|
|
100
621
|
onMessage = (event) => {
|
|
@@ -111,6 +632,8 @@ class HelixSdk {
|
|
|
111
632
|
this.shellOrigin = event.origin;
|
|
112
633
|
this.world = msg.world;
|
|
113
634
|
this.setSession(msg.session);
|
|
635
|
+
if (msg.debug)
|
|
636
|
+
this.enableDebug();
|
|
114
637
|
break;
|
|
115
638
|
case 'helix:session':
|
|
116
639
|
this.setSession(msg.session);
|
|
@@ -126,6 +649,32 @@ class HelixSdk {
|
|
|
126
649
|
pending.reject(new Error(`Helix: login ${msg.reason ?? 'failed'}`));
|
|
127
650
|
break;
|
|
128
651
|
}
|
|
652
|
+
case 'helix:response': {
|
|
653
|
+
const pending = this.pendingRequests.get(msg.requestId);
|
|
654
|
+
if (!pending)
|
|
655
|
+
return;
|
|
656
|
+
this.pendingRequests.delete(msg.requestId);
|
|
657
|
+
if (msg.ok)
|
|
658
|
+
pending.resolve(msg.result);
|
|
659
|
+
else
|
|
660
|
+
pending.reject(new Error(msg.error ?? 'Helix: request failed'));
|
|
661
|
+
break;
|
|
662
|
+
}
|
|
663
|
+
case 'helix:event': {
|
|
664
|
+
if (msg.event === 'balance-changed') {
|
|
665
|
+
const b = msg.data ?? { lix: 0, coins: 0 };
|
|
666
|
+
for (const l of this.balanceListeners)
|
|
667
|
+
l(b);
|
|
668
|
+
}
|
|
669
|
+
else if (msg.event === 'inventory-changed') {
|
|
670
|
+
for (const l of this.inventoryListeners)
|
|
671
|
+
l();
|
|
672
|
+
}
|
|
673
|
+
else if (msg.event === 'avatar-changed' || msg.event === 'equipment-changed') {
|
|
674
|
+
this.emitAvatarChanged();
|
|
675
|
+
}
|
|
676
|
+
break;
|
|
677
|
+
}
|
|
129
678
|
}
|
|
130
679
|
};
|
|
131
680
|
setSession(session) {
|
|
@@ -137,9 +686,91 @@ class HelixSdk {
|
|
|
137
686
|
listener(session?.user ?? null);
|
|
138
687
|
}
|
|
139
688
|
}
|
|
689
|
+
enableDebug() {
|
|
690
|
+
if (this.debugEnabled)
|
|
691
|
+
return;
|
|
692
|
+
this.debugEnabled = true;
|
|
693
|
+
this.hookConsole();
|
|
694
|
+
// Flush anything buffered before the shell turned debug on (e.g. early lifecycle logs).
|
|
695
|
+
if (this.shellOrigin)
|
|
696
|
+
for (const entry of this.debugRing)
|
|
697
|
+
this.post({ type: 'helix:log', entry }, this.shellOrigin);
|
|
698
|
+
}
|
|
699
|
+
// Capture ALL console output once debug is on (three.js warnings, SDK errors, uncaught logs) — not just
|
|
700
|
+
// explicit debug.log calls. Pass-through preserves normal console behaviour in the iframe.
|
|
701
|
+
hookConsole() {
|
|
702
|
+
if (this.consoleHooked || typeof console === 'undefined')
|
|
703
|
+
return;
|
|
704
|
+
this.consoleHooked = true;
|
|
705
|
+
const levels = ['log', 'info', 'warn', 'error', 'debug'];
|
|
706
|
+
const c = console;
|
|
707
|
+
for (const level of levels) {
|
|
708
|
+
const orig = c[level]?.bind(console);
|
|
709
|
+
if (!orig)
|
|
710
|
+
continue;
|
|
711
|
+
c[level] = (...args) => {
|
|
712
|
+
this.captureLog(level, args);
|
|
713
|
+
orig(...args);
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
captureLog(level, args) {
|
|
718
|
+
const entry = { level, args: args.map(stringifyArg), t: Date.now() };
|
|
719
|
+
this.debugRing.push(entry);
|
|
720
|
+
if (this.debugRing.length > DEBUG_LOG_MAX)
|
|
721
|
+
this.debugRing.shift();
|
|
722
|
+
for (const cb of this.debugListeners) {
|
|
723
|
+
try {
|
|
724
|
+
cb(entry);
|
|
725
|
+
}
|
|
726
|
+
catch {
|
|
727
|
+
/* a listener must never break logging */
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
if (this.debugEnabled && this.shellOrigin)
|
|
731
|
+
this.post({ type: 'helix:log', entry }, this.shellOrigin);
|
|
732
|
+
}
|
|
140
733
|
post(message, targetOrigin) {
|
|
141
734
|
window.parent.postMessage(message, targetOrigin);
|
|
142
735
|
}
|
|
736
|
+
postToShell(message) {
|
|
737
|
+
if (!this.shellOrigin)
|
|
738
|
+
return false;
|
|
739
|
+
this.post(message, this.shellOrigin);
|
|
740
|
+
return true;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
// Normalize a captured image to a transferable ArrayBuffer + a content type for
|
|
744
|
+
// the shell to upload. Accepts a Blob (browser capture), an ArrayBuffer, or a
|
|
745
|
+
// Uint8Array. A Blob carries its own MIME; otherwise default to JPEG.
|
|
746
|
+
async function toBytes(image, contentTypeOverride) {
|
|
747
|
+
if (typeof Blob !== 'undefined' && image instanceof Blob) {
|
|
748
|
+
return {
|
|
749
|
+
bytes: await image.arrayBuffer(),
|
|
750
|
+
contentType: contentTypeOverride || image.type || 'image/jpeg',
|
|
751
|
+
};
|
|
752
|
+
}
|
|
753
|
+
if (image instanceof Uint8Array) {
|
|
754
|
+
const copy = image.slice();
|
|
755
|
+
return { bytes: copy.buffer, contentType: contentTypeOverride || 'image/jpeg' };
|
|
756
|
+
}
|
|
757
|
+
// Remaining case is ArrayBuffer (the Blob branch above returns); the compound
|
|
758
|
+
// typeof-guard stops TS from negative-narrowing Blob, so assert it here.
|
|
759
|
+
return { bytes: image, contentType: contentTypeOverride || 'image/jpeg' };
|
|
760
|
+
}
|
|
761
|
+
// Serialize a console arg to a string the shell can print: strings as-is, Errors to their stack, other
|
|
762
|
+
// objects to compact JSON (falling back to String() on cyclic/unserializable values).
|
|
763
|
+
function stringifyArg(a) {
|
|
764
|
+
if (typeof a === 'string')
|
|
765
|
+
return a;
|
|
766
|
+
if (a instanceof Error)
|
|
767
|
+
return a.stack ?? `${a.name}: ${a.message}`;
|
|
768
|
+
try {
|
|
769
|
+
return typeof a === 'object' && a !== null ? JSON.stringify(a) : String(a);
|
|
770
|
+
}
|
|
771
|
+
catch {
|
|
772
|
+
return String(a);
|
|
773
|
+
}
|
|
143
774
|
}
|
|
144
775
|
// Worlds import this singleton: `import { Helix } from '@hypersoniclabs/helix-sdk'`.
|
|
145
776
|
export const Helix = new HelixSdk();
|