@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.
Files changed (120) hide show
  1. package/README.md +954 -2
  2. package/dist/action-surface.d.ts +182 -0
  3. package/dist/action-surface.js +1032 -0
  4. package/dist/action-surface.js.map +1 -0
  5. package/dist/camera.d.ts +78 -0
  6. package/dist/camera.js +640 -0
  7. package/dist/camera.js.map +1 -0
  8. package/dist/dev-shell/criteria.d.ts +46 -0
  9. package/dist/dev-shell/criteria.js +98 -0
  10. package/dist/dev-shell/criteria.js.map +1 -0
  11. package/dist/dev-shell/index.d.ts +189 -0
  12. package/dist/dev-shell/index.js +287 -0
  13. package/dist/dev-shell/index.js.map +1 -0
  14. package/dist/dev-shell/keys.d.ts +14 -0
  15. package/dist/dev-shell/keys.js +78 -0
  16. package/dist/dev-shell/keys.js.map +1 -0
  17. package/dist/dev-shell/simulator.d.ts +436 -0
  18. package/dist/dev-shell/simulator.js +1634 -0
  19. package/dist/dev-shell/simulator.js.map +1 -0
  20. package/dist/dev-shell/state.d.ts +148 -0
  21. package/dist/dev-shell/state.js +196 -0
  22. package/dist/dev-shell/state.js.map +1 -0
  23. package/dist/device-definition-resolver.d.ts +34 -0
  24. package/dist/device-definition-resolver.js +172 -0
  25. package/dist/device-definition-resolver.js.map +1 -0
  26. package/dist/device-trial.d.ts +3 -0
  27. package/dist/device-trial.js +132 -0
  28. package/dist/device-trial.js.map +1 -0
  29. package/dist/devices.d.ts +228 -0
  30. package/dist/devices.js +198 -0
  31. package/dist/devices.js.map +1 -0
  32. package/dist/dreamerAudio.d.ts +126 -0
  33. package/dist/dreamerAudio.js +135 -0
  34. package/dist/dreamerAudio.js.map +1 -0
  35. package/dist/generated/runtime-contract.d.ts +15529 -0
  36. package/dist/generated/runtime-contract.js +20470 -0
  37. package/dist/generated/runtime-contract.js.map +1 -0
  38. package/dist/index.d.ts +364 -3
  39. package/dist/index.js +1954 -13
  40. package/dist/index.js.map +1 -1
  41. package/dist/interaction-mode.d.ts +172 -0
  42. package/dist/interaction-mode.js +553 -0
  43. package/dist/interaction-mode.js.map +1 -0
  44. package/dist/internal/avatar-pose.d.ts +25 -0
  45. package/dist/internal/avatar-pose.js +46 -0
  46. package/dist/internal/avatar-pose.js.map +1 -0
  47. package/dist/internal/keyed-collection.d.ts +2 -0
  48. package/dist/internal/keyed-collection.js +12 -0
  49. package/dist/internal/keyed-collection.js.map +1 -0
  50. package/dist/internal/vehicle-detach-action.d.ts +2 -0
  51. package/dist/internal/vehicle-detach-action.js +6 -0
  52. package/dist/internal/vehicle-detach-action.js.map +1 -0
  53. package/dist/matchmaking.d.ts +433 -0
  54. package/dist/matchmaking.js +1487 -0
  55. package/dist/matchmaking.js.map +1 -0
  56. package/dist/materials.d.ts +122 -0
  57. package/dist/materials.js +217 -0
  58. package/dist/materials.js.map +1 -0
  59. package/dist/multiplayer-accessors.d.ts +100 -0
  60. package/dist/multiplayer-accessors.js +200 -0
  61. package/dist/multiplayer-accessors.js.map +1 -0
  62. package/dist/multiplayer-contract/avatar-pose.d.ts +112 -0
  63. package/dist/multiplayer-contract/avatar-pose.js +250 -0
  64. package/dist/multiplayer-contract/avatar-pose.js.map +1 -0
  65. package/dist/multiplayer-contract/credential.d.ts +80 -0
  66. package/dist/multiplayer-contract/credential.js +5 -0
  67. package/dist/multiplayer-contract/credential.js.map +1 -0
  68. package/dist/multiplayer-contract/final-rest.d.ts +66 -0
  69. package/dist/multiplayer-contract/final-rest.js +38 -0
  70. package/dist/multiplayer-contract/final-rest.js.map +1 -0
  71. package/dist/multiplayer-contract/index.d.ts +20 -0
  72. package/dist/multiplayer-contract/index.js +41 -0
  73. package/dist/multiplayer-contract/index.js.map +1 -0
  74. package/dist/multiplayer-contract/messages.d.ts +731 -0
  75. package/dist/multiplayer-contract/messages.js +237 -0
  76. package/dist/multiplayer-contract/messages.js.map +1 -0
  77. package/dist/multiplayer-contract/room.d.ts +177 -0
  78. package/dist/multiplayer-contract/room.js +17 -0
  79. package/dist/multiplayer-contract/room.js.map +1 -0
  80. package/dist/multiplayer-contract/state.d.ts +241 -0
  81. package/dist/multiplayer-contract/state.js +15 -0
  82. package/dist/multiplayer-contract/state.js.map +1 -0
  83. package/dist/multiplayer-final-rest.d.ts +32 -0
  84. package/dist/multiplayer-final-rest.js +217 -0
  85. package/dist/multiplayer-final-rest.js.map +1 -0
  86. package/dist/multiplayer.d.ts +624 -0
  87. package/dist/multiplayer.js +2503 -0
  88. package/dist/multiplayer.js.map +1 -0
  89. package/dist/package.json +3 -0
  90. package/dist/protocol.d.ts +859 -1
  91. package/dist/protocol.js +117 -5
  92. package/dist/protocol.js.map +1 -1
  93. package/dist/runtime-contract/index.d.ts +15 -0
  94. package/dist/runtime-contract/index.js +12 -0
  95. package/dist/runtime-contract/index.js.map +1 -0
  96. package/dist/server-clock.d.ts +25 -0
  97. package/dist/server-clock.js +88 -0
  98. package/dist/server-clock.js.map +1 -0
  99. package/dist/tsconfig.build.tsbuildinfo +1 -1
  100. package/dist/universal-vehicles.d.ts +111 -0
  101. package/dist/universal-vehicles.js +2 -0
  102. package/dist/universal-vehicles.js.map +1 -0
  103. package/dist/vault.d.ts +562 -0
  104. package/dist/vault.js +365 -0
  105. package/dist/vault.js.map +1 -0
  106. package/dist/vehicle-specialty-placement.d.ts +28 -0
  107. package/dist/vehicle-specialty-placement.js +154 -0
  108. package/dist/vehicle-specialty-placement.js.map +1 -0
  109. package/dist/vehicle-specialty-transport.d.ts +78 -0
  110. package/dist/vehicle-specialty-transport.js +183 -0
  111. package/dist/vehicle-specialty-transport.js.map +1 -0
  112. package/dist/voice.d.ts +229 -0
  113. package/dist/voice.js +1348 -0
  114. package/dist/voice.js.map +1 -0
  115. package/generated/runtime-contract/helix-runtime-contract.json +13332 -0
  116. package/generated/runtime-contract/known-answer.json +20471 -0
  117. package/generated/runtime-contract/known-answer.schema.json +630 -0
  118. package/generated/runtime-contract/runtime-contract.schema.json +607 -0
  119. package/generated/runtime-contract/unreal/HelixRuntimeContract.generated.h +908 -0
  120. package/package.json +44 -5
@@ -0,0 +1,46 @@
1
+ export declare const DEV_SHELL_CRITERIA_SIGNALS: readonly ["datastore", "iwp", "analytics", "playtime"];
2
+ export type DevShellCriteriaSignal = (typeof DEV_SHELL_CRITERIA_SIGNALS)[number];
3
+ export declare const DEV_SHELL_CRITERIA_OPS: readonly ["gte", "lte", "eq"];
4
+ export type DevShellCriteriaOp = (typeof DEV_SHELL_CRITERIA_OPS)[number];
5
+ export declare const DEV_SHELL_CRITERIA_METRICS: readonly ["count", "lix"];
6
+ export type DevShellCriteriaMetric = (typeof DEV_SHELL_CRITERIA_METRICS)[number];
7
+ /** The only two documents a `datastore` criteria may read. `{userId}` resolves to the simulated player. */
8
+ export declare const DEV_SHELL_CRITERIA_KEY_TEMPLATES: readonly ["player:{userId}", "mp:player:{userId}"];
9
+ export type DevShellCriteriaKeyTemplate = (typeof DEV_SHELL_CRITERIA_KEY_TEMPLATES)[number];
10
+ /** A `datastore` criteria's `field`: a dot-path of letters, digits and underscores. */
11
+ export declare const DEV_SHELL_CRITERIA_FIELD_PATTERN: RegExp;
12
+ /** Shaped exactly as registration stores it — the same JSON `helix achievement register` sends. */
13
+ export type DevShellAchievementCriteria = {
14
+ signal: DevShellCriteriaSignal;
15
+ op: DevShellCriteriaOp;
16
+ value: number;
17
+ eventName?: string;
18
+ key?: DevShellCriteriaKeyTemplate;
19
+ field?: string;
20
+ metric?: DevShellCriteriaMetric;
21
+ };
22
+ /**
23
+ * The stored evidence a measurement re-derives from. The caller (the simulator) pre-filters
24
+ * `completedPurchases` to settled rows that resolve to a seeded WORLD product — listing purchases are
25
+ * marketplace, not IWP, and never count.
26
+ */
27
+ export type DevShellCriteriaEvidence = {
28
+ userId: string;
29
+ documents: Record<string, {
30
+ value: unknown;
31
+ }>;
32
+ completedPurchases: Array<{
33
+ priceLix: number;
34
+ }>;
35
+ playtimeSeconds: number;
36
+ analyticsCounts: Record<string, number>;
37
+ };
38
+ /**
39
+ * Measure one criteria against the evidence, or null when it cannot be measured (fail-closed).
40
+ * Counts measure 0 when nothing happened yet — zero events is a real measurement; a missing document
41
+ * field is not.
42
+ */
43
+ export declare function measureDevShellCriteria(criteria: DevShellAchievementCriteria, evidence: DevShellCriteriaEvidence): number | null;
44
+ export declare function devShellCriteriaSatisfied(measured: number | null, criteria: DevShellAchievementCriteria): boolean;
45
+ /** One-line render for the debug menu's progress print — same shape as the CLI's `list` column. */
46
+ export declare function formatDevShellCriteria(criteria: DevShellAchievementCriteria | null | undefined): string;
@@ -0,0 +1,98 @@
1
+ // The achievement criteria grammar + evaluator for `helix dev` — how a simulated unlock is measured.
2
+ //
3
+ // SYNC OBLIGATION: a hand-mirror of the closed criteria vocabulary.
4
+ // AUTHORITY: helix-backend-api → src/achievements/dtos/achievement.dtos.ts (normalizeCriteria) +
5
+ // src/database/enums/achievement-criteria.enum.ts. SIBLING MIRROR: helix-creator-cli/src/achievement.ts
6
+ // (the registration fast path) — widen all three in lockstep.
7
+ //
8
+ // Evaluation mirrors production's poke → re-derive model: a measurement is always re-derived from the
9
+ // stored evidence, never accumulated, so evaluating twice is free and a lost poke heals on the next one.
10
+ // Fail-closed everywhere production is: a missing document or field, a non-numeric or stringified leaf,
11
+ // an array in the path, or a signal this copy does not know all read as null — never a zero.
12
+ export const DEV_SHELL_CRITERIA_SIGNALS = ['datastore', 'iwp', 'analytics', 'playtime'];
13
+ export const DEV_SHELL_CRITERIA_OPS = ['gte', 'lte', 'eq'];
14
+ export const DEV_SHELL_CRITERIA_METRICS = ['count', 'lix'];
15
+ /** The only two documents a `datastore` criteria may read. `{userId}` resolves to the simulated player. */
16
+ export const DEV_SHELL_CRITERIA_KEY_TEMPLATES = ['player:{userId}', 'mp:player:{userId}'];
17
+ /** A `datastore` criteria's `field`: a dot-path of letters, digits and underscores. */
18
+ export const DEV_SHELL_CRITERIA_FIELD_PATTERN = /^[A-Za-z0-9_]+(\.[A-Za-z0-9_]+)*$/;
19
+ const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
20
+ // The numeric-leaf rule is runtime-only in production (registration cannot see the document), so this
21
+ // walk is the first place a creator can watch a stringified "12" fail to unlock. Arrays not descendable.
22
+ function numericLeaf(root, fieldPath) {
23
+ let node = root;
24
+ for (const segment of fieldPath.split('.')) {
25
+ if (!isRecord(node))
26
+ return null;
27
+ node = node[segment];
28
+ }
29
+ return typeof node === 'number' && Number.isFinite(node) ? node : null;
30
+ }
31
+ /**
32
+ * Measure one criteria against the evidence, or null when it cannot be measured (fail-closed).
33
+ * Counts measure 0 when nothing happened yet — zero events is a real measurement; a missing document
34
+ * field is not.
35
+ */
36
+ export function measureDevShellCriteria(criteria, evidence) {
37
+ switch (criteria.signal) {
38
+ case 'playtime':
39
+ return evidence.playtimeSeconds;
40
+ case 'analytics':
41
+ return criteria.eventName ? (evidence.analyticsCounts[criteria.eventName] ?? 0) : null;
42
+ case 'iwp': {
43
+ if (criteria.metric === 'lix') {
44
+ return evidence.completedPurchases.reduce((sum, p) => sum + p.priceLix, 0);
45
+ }
46
+ return evidence.completedPurchases.length;
47
+ }
48
+ case 'datastore': {
49
+ if (!criteria.key || !criteria.field)
50
+ return null;
51
+ const doc = evidence.documents[criteria.key.replace('{userId}', evidence.userId)];
52
+ if (!doc)
53
+ return null;
54
+ let root = doc.value;
55
+ if (criteria.key.startsWith('mp:')) {
56
+ // The room flushes persistent playerVars as a { v, vars } envelope and production unwraps it;
57
+ // a document without that shape reads null rather than being walked raw.
58
+ if (!isRecord(root) || !isRecord(root.vars))
59
+ return null;
60
+ root = root.vars;
61
+ }
62
+ return numericLeaf(root, criteria.field);
63
+ }
64
+ default:
65
+ return null;
66
+ }
67
+ }
68
+ export function devShellCriteriaSatisfied(measured, criteria) {
69
+ if (measured === null)
70
+ return false;
71
+ switch (criteria.op) {
72
+ case 'gte':
73
+ return measured >= criteria.value;
74
+ case 'lte':
75
+ return measured <= criteria.value;
76
+ case 'eq':
77
+ return measured === criteria.value;
78
+ default:
79
+ return false;
80
+ }
81
+ }
82
+ /** One-line render for the debug menu's progress print — same shape as the CLI's `list` column. */
83
+ export function formatDevShellCriteria(criteria) {
84
+ if (!criteria)
85
+ return '';
86
+ const cmp = `${criteria.op} ${criteria.value}`;
87
+ switch (criteria.signal) {
88
+ case 'datastore':
89
+ return `datastore ${criteria.key}.${criteria.field} ${cmp}`;
90
+ case 'iwp':
91
+ return `iwp ${criteria.metric ?? 'count'} ${cmp}`;
92
+ case 'analytics':
93
+ return `analytics ${criteria.eventName} ${cmp}`;
94
+ default:
95
+ return `${criteria.signal} ${cmp}`;
96
+ }
97
+ }
98
+ //# sourceMappingURL=criteria.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"criteria.js","sourceRoot":"","sources":["../../src/dev-shell/criteria.ts"],"names":[],"mappings":"AAAA,qGAAqG;AACrG,EAAE;AACF,oEAAoE;AACpE,mGAAmG;AACnG,0GAA0G;AAC1G,gEAAgE;AAChE,EAAE;AACF,sGAAsG;AACtG,yGAAyG;AACzG,wGAAwG;AACxG,6FAA6F;AAE7F,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,WAAW,EAAE,KAAK,EAAE,WAAW,EAAE,UAAU,CAAU,CAAC;AAGjG,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,IAAI,CAAU,CAAC;AAGpE,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,OAAO,EAAE,KAAK,CAAU,CAAC;AAGpE,2GAA2G;AAC3G,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,iBAAiB,EAAE,oBAAoB,CAAU,CAAC;AAGnG,uFAAuF;AACvF,MAAM,CAAC,MAAM,gCAAgC,GAAG,mCAAmC,CAAC;AA0BpF,MAAM,QAAQ,GAAG,CAAC,CAAU,EAAgC,EAAE,CAC5D,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AAE3D,sGAAsG;AACtG,yGAAyG;AACzG,SAAS,WAAW,CAAC,IAAa,EAAE,SAAiB;IACnD,IAAI,IAAI,GAAY,IAAI,CAAC;IACzB,KAAK,MAAM,OAAO,IAAI,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QAC3C,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;YAAE,OAAO,IAAI,CAAC;QACjC,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC;IACvB,CAAC;IACD,OAAO,OAAO,IAAI,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;AACzE,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CACrC,QAAqC,EACrC,QAAkC;IAElC,QAAQ,QAAQ,CAAC,MAAM,EAAE,CAAC;QACxB,KAAK,UAAU;YACb,OAAO,QAAQ,CAAC,eAAe,CAAC;QAClC,KAAK,WAAW;YACd,OAAO,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,eAAe,CAAC,QAAQ,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QACzF,KAAK,KAAK,CAAC,CAAC,CAAC;YACX,IAAI,QAAQ,CAAC,MAAM,KAAK,KAAK,EAAE,CAAC;gBAC9B,OAAO,QAAQ,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;YAC7E,CAAC;YACD,OAAO,QAAQ,CAAC,kBAAkB,CAAC,MAAM,CAAC;QAC5C,CAAC;QACD,KAAK,WAAW,CAAC,CAAC,CAAC;YACjB,IAAI,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK;gBAAE,OAAO,IAAI,CAAC;YAClD,MAAM,GAAG,GAAG,QAAQ,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;YAClF,IAAI,CAAC,GAAG;gBAAE,OAAO,IAAI,CAAC;YACtB,IAAI,IAAI,GAAY,GAAG,CAAC,KAAK,CAAC;YAC9B,IAAI,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;gBACnC,8FAA8F;gBAC9F,yEAAyE;gBACzE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC;oBAAE,OAAO,IAAI,CAAC;gBACzD,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;YACnB,CAAC;YACD,OAAO,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC;QAC3C,CAAC;QACD;YACE,OAAO,IAAI,CAAC;IAChB,CAAC;AACH,CAAC;AAED,MAAM,UAAU,yBAAyB,CAAC,QAAuB,EAAE,QAAqC;IACtG,IAAI,QAAQ,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IACpC,QAAQ,QAAQ,CAAC,EAAE,EAAE,CAAC;QACpB,KAAK,KAAK;YACR,OAAO,QAAQ,IAAI,QAAQ,CAAC,KAAK,CAAC;QACpC,KAAK,KAAK;YACR,OAAO,QAAQ,IAAI,QAAQ,CAAC,KAAK,CAAC;QACpC,KAAK,IAAI;YACP,OAAO,QAAQ,KAAK,QAAQ,CAAC,KAAK,CAAC;QACrC;YACE,OAAO,KAAK,CAAC;IACjB,CAAC;AACH,CAAC;AAED,mGAAmG;AACnG,MAAM,UAAU,sBAAsB,CAAC,QAAwD;IAC7F,IAAI,CAAC,QAAQ;QAAE,OAAO,EAAE,CAAC;IACzB,MAAM,GAAG,GAAG,GAAG,QAAQ,CAAC,EAAE,IAAI,QAAQ,CAAC,KAAK,EAAE,CAAC;IAC/C,QAAQ,QAAQ,CAAC,MAAM,EAAE,CAAC;QACxB,KAAK,WAAW;YACd,OAAO,aAAa,QAAQ,CAAC,GAAG,IAAI,QAAQ,CAAC,KAAK,IAAI,GAAG,EAAE,CAAC;QAC9D,KAAK,KAAK;YACR,OAAO,OAAO,QAAQ,CAAC,MAAM,IAAI,OAAO,IAAI,GAAG,EAAE,CAAC;QACpD,KAAK,WAAW;YACd,OAAO,aAAa,QAAQ,CAAC,SAAS,IAAI,GAAG,EAAE,CAAC;QAClD;YACE,OAAO,GAAG,QAAQ,CAAC,MAAM,IAAI,GAAG,EAAE,CAAC;IACvC,CAAC;AACH,CAAC"}
@@ -0,0 +1,189 @@
1
+ import type { Balance, Entitlements, HelixCameraCapability, HelixCameraState, HelixEvent, HelixSession, HelixVoiceSettings, HelixWorldContext, RuntimeFidelityIntent, WorldToShellMessage } from '../protocol.js';
2
+ import { type DevShellAchievementProgress, type DevShellEarnedAchievement, type DevShellJoinAnswer, type DevShellJoinBody, type DevShellLogger, type DevShellPartyCode, type DevShellPartyInvite, type DevShellPartyMember, type DevShellPlatformAnswer, type DevShellPurchaseConfirm, type DevShellPurchaseFailureMode, type DevShellQueuesSeed, type DevShellRejoinAnswer, type DevShellRoomTicket, type DevShellRoomTypesSeed } from './simulator.js';
3
+ import { type DevShellIdentity, type DevShellProductsSeed, type DevShellState } from './state.js';
4
+ export { DEV_SHELL_ACHIEVEMENT_DEBOUNCE_MS, DEV_SHELL_CAPS, DEV_SHELL_LOG_PREFIX, DEV_SHELL_PARTY_CODE_TTL_MS, DEV_SHELL_PARTY_INVITE_TTL_MS, DEV_SHELL_PARTY_MAX_SIZE, DEV_SHELL_PARTY_PENDING_INVITES_MAX, DEV_SHELL_PURCHASE_FAILURE_MODES, DEV_SHELL_QUEUES_MAX, DEV_SHELL_QUEUE_ID_PATTERN, DEV_SHELL_REFUSED_METHODS, DEV_SHELL_ROOM_REFUSALS, DEV_SHELL_ROOM_TICKET_TTL_MS, DEV_SHELL_ROOM_TYPES_MAX, DEV_SHELL_ROOM_TYPE_NAME_PATTERN, DEV_SHELL_SIMULATED_METHODS, DevShellSimulator, } from './simulator.js';
5
+ export type { DevShellAchievementProgress, DevShellAnswer, DevShellEarnedAchievement, DevShellJoinAnswer, DevShellJoinBody, DevShellLogger, DevShellParty, DevShellPartyCode, DevShellPartyInvite, DevShellPartyMember, DevShellPlatformAnswer, DevShellPurchaseConfirm, DevShellPurchaseFailureMode, DevShellQueueSeed, DevShellQueuesSeed, DevShellRejoinAnswer, DevShellRoomRefusalBody, DevShellRoomRefusalCode, DevShellRoomTicket, DevShellRoomTypeSeed, DevShellRoomTypesSeed, } from './simulator.js';
6
+ export { DEV_SHELL_CRITERIA_FIELD_PATTERN, DEV_SHELL_CRITERIA_KEY_TEMPLATES, DEV_SHELL_CRITERIA_METRICS, DEV_SHELL_CRITERIA_OPS, DEV_SHELL_CRITERIA_SIGNALS, devShellCriteriaSatisfied, formatDevShellCriteria, measureDevShellCriteria, } from './criteria.js';
7
+ export type { DevShellAchievementCriteria, DevShellCriteriaEvidence, DevShellCriteriaKeyTemplate, DevShellCriteriaMetric, DevShellCriteriaOp, DevShellCriteriaSignal, } from './criteria.js';
8
+ export { DEV_SHELL_DEFAULT_IDENTITY, DEV_SHELL_DEFAULT_WALLET, DEV_SHELL_STATE_VERSION, cloneDevShellState, createDevShellState, devShellProductRef, normalizeDevShellState, } from './state.js';
9
+ export type { DevShellAchievement, DevShellBoard, DevShellDocument, DevShellIdentity, DevShellProduct, DevShellProductsSeed, DevShellPurchaseRecord, DevShellState, } from './state.js';
10
+ export { checkDevShellRead, checkDevShellWrite, playerSaveKey } from './keys.js';
11
+ export type { DevShellKeyVerdict, DevShellWriteRule } from './keys.js';
12
+ /** The world frame's window — anything that can receive a postMessage. */
13
+ export type DevShellPostTarget = {
14
+ postMessage(message: unknown, targetOrigin: string): void;
15
+ };
16
+ /** An <iframe> whose contentWindow is the world. Resolved lazily, so the frame may still be loading. */
17
+ export type DevShellFrameLike = {
18
+ contentWindow: DevShellPostTarget | null;
19
+ };
20
+ /** Where the shell hears the world. The host page's `window` in the browser; a fake bus in tests. */
21
+ export type DevShellHostWindow = {
22
+ addEventListener(type: 'message', listener: (event: MessageEvent) => void): void;
23
+ removeEventListener(type: 'message', listener: (event: MessageEvent) => void): void;
24
+ };
25
+ export type DevShellOptions = {
26
+ /** The world iframe (or its contentWindow) this shell answers. */
27
+ worldWindow: DevShellPostTarget | DevShellFrameLike;
28
+ /** The origin the world bundle is served from. Every inbound message is checked against it; '*' accepts any. */
29
+ worldOrigin: string;
30
+ /** Defaults to the ambient `window`. Injectable so a jsdom spec can wire both ends in one page. */
31
+ hostWindow?: DevShellHostWindow;
32
+ /** The world identity announced in helix:init. */
33
+ world?: HelixWorldContext;
34
+ /** The simulated player. Used only when no `state` is supplied — a loaded state carries its own identity. */
35
+ user?: Partial<DevShellIdentity>;
36
+ /** Session scopes to announce. Default ['auth.profile'] — camera.capture is absent, matching the refusal. */
37
+ scopes?: string[];
38
+ /** Previously persisted state. Omit for a fresh player. */
39
+ state?: DevShellState;
40
+ /** Called with a serializable copy after every mutation. The embedder persists it; this module does no I/O. */
41
+ onStateChange?: (state: DevShellState) => void;
42
+ /** Product catalog seed (the CLI's `.helix/dev-products.json`). */
43
+ products?: DevShellProductsSeed;
44
+ /** The world's declared room types (manifest `multiplayer.roomTypes`) — drives the simulated join API. */
45
+ roomTypes?: DevShellRoomTypesSeed;
46
+ /** The world's declared matchmaking queues (manifest `matchmaking.queues`) — drives the simulated queue routes. */
47
+ queues?: DevShellQueuesSeed;
48
+ /** Mirror the world's console into the host frame (helix:init `debug`). */
49
+ debug?: boolean;
50
+ /** Versioned presentation intent, matching the production shell handshake. */
51
+ runtimeFidelity?: RuntimeFidelityIntent;
52
+ /** Where simulated-response lines go. Default console. */
53
+ log?: DevShellLogger;
54
+ /** Every world→shell message, after the origin check — for the page's own UI (notifications, prompts). */
55
+ onWorldMessage?: (message: WorldToShellMessage) => void;
56
+ /** A simulated unlock happened — host-page feedback (toast). Worlds observe it only by re-polling. */
57
+ onAchievementEarned?: (achievement: DevShellEarnedAchievement) => void;
58
+ /** Criteria re-evaluation delay after a write/settle. Default 3 s (production's debounce); 0 = sync. */
59
+ achievementDebounceMs?: number;
60
+ /**
61
+ * The real shell raises a confirm dialog before settling a purchase; provide this to simulate it.
62
+ * Resolve true to settle (injected failures still apply), false to answer `Cancelled` with nothing
63
+ * recorded — so a retried attempt confirms again, as production's cancel-before-charge does. Omitted,
64
+ * purchases settle immediately (the pre-dialog behavior; what every headless spec uses). The SDK gives
65
+ * this request its long human-in-the-loop timeout, so the dialog may sit open while a human decides.
66
+ */
67
+ confirmPurchase?: (request: DevShellPurchaseConfirm) => Promise<boolean>;
68
+ };
69
+ export type DevShellHandle = {
70
+ /** Always 'simulated'. Never call this mode "test": Roblox's test mode costs real money. */
71
+ readonly mode: 'simulated';
72
+ readonly world: HelixWorldContext;
73
+ /** True once the world's helix:ready has been answered with helix:init. */
74
+ isConnected(): boolean;
75
+ getSession(): HelixSession;
76
+ /** A serializable copy of the whole simulated player — what the embedder persists. */
77
+ getState(): DevShellState;
78
+ /** Swap the state in place (the `--reset` seam). Does NOT call onStateChange — the caller already knows. */
79
+ setState(state: DevShellState): void;
80
+ setProducts(products: DevShellProductsSeed | undefined): void;
81
+ grantAllEntitlements(): void;
82
+ grantEntitlement(ref: string): void;
83
+ removeEntitlement(ref: string): void;
84
+ getEntitlementsSnapshot(): Entitlements;
85
+ setPurchasesAlwaysFail(mode: DevShellPurchaseFailureMode | 'off'): void;
86
+ /** The menu button: off → InsufficientFunds → PriceChanged → Pending → off. Returns the new mode. */
87
+ cyclePurchasesAlwaysFail(): DevShellPurchaseFailureMode | 'off';
88
+ purchasesAlwaysFail(): DevShellPurchaseFailureMode | 'off';
89
+ resetPlayerDocument(): void;
90
+ setForceSaveFailure(on: boolean): void;
91
+ exhaustConsumeFence(): void;
92
+ setWallet(wallet: Partial<Balance>): void;
93
+ /** Award by key — the room/platform lanes' stand-in. False when the key is not in the local registry. */
94
+ awardAchievement(key: string): boolean;
95
+ /** Clear earned[] for re-testing. Local-only convenience — production never revokes. */
96
+ resetAchievements(): void;
97
+ /** Accumulate playtime evidence. The `helix dev` page ticks this every 15 s while open. */
98
+ addPlaytime(seconds: number): void;
99
+ /** Bump an analytics event count — real events never reach a shell, so this is the only local writer. */
100
+ bumpAnalyticsEvent(eventName: string, count?: number): void;
101
+ /** Write one persistent playerVar into the mp:player:{userId} envelope, as a room flush would. */
102
+ setMpPlayerVar(field: string, value: number): void;
103
+ /** Measured-vs-target for every registered achievement — the menu's progress print. */
104
+ getAchievementsProgress(): DevShellAchievementProgress[];
105
+ /** The room's leaderboard submit, by hand — declared boards a world only reads stay empty without it. */
106
+ seedLeaderboardScore(board: string, score: number, opts?: {
107
+ subject?: string;
108
+ displayName?: string;
109
+ order?: 'asc' | 'desc';
110
+ }): void;
111
+ /** The server's hand on the data store: write ANY key (world-global, mp:world:*, reserved namespaces). */
112
+ seedDocument(key: string, value: unknown): void;
113
+ setRoomTypes(roomTypes: DevShellRoomTypesSeed | undefined): void;
114
+ /** What `POST …/join` would answer for this body: none / `{}`, `{ roomType }`, or `{ ticket }`. */
115
+ simulateRoomJoin(body?: DevShellJoinBody): DevShellJoinAnswer;
116
+ /** The `openRoom` effect, by hand: a ticket to a ticketed type. Null when the type is not declared ticketed. */
117
+ issueRoomTicket(roomType: string, opts?: {
118
+ instanceId?: string;
119
+ ttlMs?: number;
120
+ }): DevShellRoomTicket | null;
121
+ /** What `POST …/room-instances/:instanceId/rejoin` would answer (410 once the instance has closed). */
122
+ rejoinRoomInstance(instanceId: string): DevShellRejoinAnswer;
123
+ /** The ticketed room disposing. Idempotent; false when no such instance exists. */
124
+ closeRoomInstance(instanceId: string): boolean;
125
+ setQueues(queues: DevShellQueuesSeed | undefined): void;
126
+ /**
127
+ * What a v1 matchmaking / party route would answer: `{ status, body }`, with the backend's real
128
+ * `{ statusCode, code, message }` refusal bodies. E.g. `('POST', '/instant-worlds/w/queues/duel/tickets')`,
129
+ * `('GET', '/instant-worlds/w/queues/tickets/current')`, `('GET', '/parties/current')`.
130
+ */
131
+ simulatePlatformRequest(method: string, path: string, body?: unknown): DevShellPlatformAnswer;
132
+ /** The matcher, by hand: the waiting ticket's match forms and a room ticket is issued. Null when nothing is waiting. */
133
+ formMatch(opts?: {
134
+ ttlMs?: number;
135
+ }): DevShellRoomTicket | null;
136
+ /** The platform ends the waiting ticket (`timeout`, `member-absent`, `replaced`, …). False when nothing is waiting. */
137
+ endQueueTicket(reason: string): boolean;
138
+ /** A party member holds a standing match (null clears it): enqueue is refused with `already-matched`, naming them. */
139
+ setPartyMemberMatch(userId: string | null): void;
140
+ /** Another player invites the simulated player to their party. */
141
+ receivePartyInvite(from?: Partial<DevShellPartyMember>, opts?: {
142
+ ttlMs?: number;
143
+ }): DevShellPartyInvite;
144
+ /** The player an invite was sent to accepts it. False when there is no such pending invite. */
145
+ acceptPartyInvite(inviteId: string, displayName?: string): boolean;
146
+ /** Another player's party has a join code: returns it, to try `POST /parties/join` with. */
147
+ openPartyCode(host?: Partial<DevShellPartyMember>, opts?: {
148
+ ttlMs?: number;
149
+ }): DevShellPartyCode;
150
+ /** Another player joins the simulated player's party with its code. False when the code is not live. */
151
+ usePartyCode(code: string, member?: Partial<DevShellPartyMember>): boolean;
152
+ /** Push helix:session — false simulates a sign-out (the world's onAuthChanged fires with null). */
153
+ setSignedIn(signedIn: boolean): void;
154
+ sendVoiceSettings(settings: HelixVoiceSettings): void;
155
+ /**
156
+ * Push helix:camera-state — the native avatar camera, as HELIX OS would drive it. The
157
+ * world's reported capability is echoed back in it (the real shell does the same), so a
158
+ * runtime that reported `video: false` sees that reflected instead of two views drifting.
159
+ * There is no simulated RIG behind it: this moves the state, and the world renders it.
160
+ */
161
+ sendCameraState(state: HelixCameraState): void;
162
+ /** The capability the world last reported via camera.reportCapability (all-false until it does). */
163
+ getCameraCapability(): HelixCameraCapability;
164
+ /**
165
+ * Push helix:leave — the deliberate-exit path (consented room close, voice leave). Like the real shell's,
166
+ * it ends the world: `Helix.hasLeft()` turns true, `Helix.onLeave` subscribers run, and room joins reject
167
+ * `left`. The real shell then destroys the frame; here the frame stays, so reload it to enter again.
168
+ */
169
+ sendLeave(): void;
170
+ pushEvent(event: HelixEvent, data?: unknown): void;
171
+ dispose(): void;
172
+ };
173
+ /**
174
+ * The simulated session token. Deliberately NOT a JWT and obviously fake, because the SDK surfaces that
175
+ * carry no shell guard (presence.*, analytics.track, avatar.getEquipped, the loadout fallbacks) fetch the
176
+ * platform API directly the moment a session token exists. They resolve their base through
177
+ * multiplayer.resolveApiBase(token) = configure() ?? the shell's helix:init apiBaseUrl ?? the token's
178
+ * `iss` claim — so a non-JWT token plus a null apiBaseUrl below resolves to NO api base, and every one
179
+ * of those calls returns its neutral value without a fetch ever leaving the page.
180
+ */
181
+ export declare const DEV_SHELL_SESSION_TOKEN = "helix-dev-simulated";
182
+ /**
183
+ * Start a simulated HELIX shell around a world frame. The world must be IFRAMED — the SDK only performs
184
+ * the handshake when `window.parent !== window` — and helix:ready is answered immediately, because an
185
+ * unanswered handshake costs every boot the SDK's full 8 s INIT_TIMEOUT_MS.
186
+ */
187
+ export declare function createDevShell(options: DevShellOptions): DevShellHandle;
188
+ /** A fresh, empty state for a given identity — the `--fresh` / `--reset` seed. */
189
+ export declare function createFreshDevShellState(identity?: Partial<DevShellIdentity>): DevShellState;
@@ -0,0 +1,287 @@
1
+ // `@hypersoniclabs/helix-sdk/dev-shell` — the HOST half of the world↔shell postMessage protocol, for
2
+ // `helix dev`. A local page iframes a world bundle and hands the frame to createDevShell(); the SDK
3
+ // inside that frame then behaves as if it were embedded in helixgame.com, answered entirely from
4
+ // simulated state. Simulates the SHELL lane only: the room lane (DSL rules, the consume/save/saveRoom
5
+ // verbs) is NOT exercised — multiplayer still needs the dev-stack. The debug menu can stand in for two
6
+ // room-lane OUTCOMES (awardAchievement, a persistent-var flush) without running any rules.
7
+ //
8
+ // This module is a SEPARATE module graph from the SDK root: nothing reachable from src/index.ts may
9
+ // import it (a published world must carry zero bytes of it), and it imports nothing but ../protocol and
10
+ // its own files, because its dist is served raw to a browser as native ESM.
11
+ import { PROTOCOL_VERSION } from '../protocol.js';
12
+ import { DEV_SHELL_LOG_PREFIX, DevShellSimulator, } from './simulator.js';
13
+ import { DEV_SHELL_DEFAULT_IDENTITY, createDevShellState, normalizeDevShellState, } from './state.js';
14
+ export { DEV_SHELL_ACHIEVEMENT_DEBOUNCE_MS, DEV_SHELL_CAPS, DEV_SHELL_LOG_PREFIX, DEV_SHELL_PARTY_CODE_TTL_MS, DEV_SHELL_PARTY_INVITE_TTL_MS, DEV_SHELL_PARTY_MAX_SIZE, DEV_SHELL_PARTY_PENDING_INVITES_MAX, DEV_SHELL_PURCHASE_FAILURE_MODES, DEV_SHELL_QUEUES_MAX, DEV_SHELL_QUEUE_ID_PATTERN, DEV_SHELL_REFUSED_METHODS, DEV_SHELL_ROOM_REFUSALS, DEV_SHELL_ROOM_TICKET_TTL_MS, DEV_SHELL_ROOM_TYPES_MAX, DEV_SHELL_ROOM_TYPE_NAME_PATTERN, DEV_SHELL_SIMULATED_METHODS, DevShellSimulator, } from './simulator.js';
15
+ export { DEV_SHELL_CRITERIA_FIELD_PATTERN, DEV_SHELL_CRITERIA_KEY_TEMPLATES, DEV_SHELL_CRITERIA_METRICS, DEV_SHELL_CRITERIA_OPS, DEV_SHELL_CRITERIA_SIGNALS, devShellCriteriaSatisfied, formatDevShellCriteria, measureDevShellCriteria, } from './criteria.js';
16
+ export { DEV_SHELL_DEFAULT_IDENTITY, DEV_SHELL_DEFAULT_WALLET, DEV_SHELL_STATE_VERSION, cloneDevShellState, createDevShellState, devShellProductRef, normalizeDevShellState, } from './state.js';
17
+ export { checkDevShellRead, checkDevShellWrite, playerSaveKey } from './keys.js';
18
+ const DEFAULT_WORLD = {
19
+ id: '00000000-0000-4000-8000-000000000001',
20
+ slug: 'dev-world',
21
+ title: 'Dev World',
22
+ };
23
+ /**
24
+ * The simulated session token. Deliberately NOT a JWT and obviously fake, because the SDK surfaces that
25
+ * carry no shell guard (presence.*, analytics.track, avatar.getEquipped, the loadout fallbacks) fetch the
26
+ * platform API directly the moment a session token exists. They resolve their base through
27
+ * multiplayer.resolveApiBase(token) = configure() ?? the shell's helix:init apiBaseUrl ?? the token's
28
+ * `iss` claim — so a non-JWT token plus a null apiBaseUrl below resolves to NO api base, and every one
29
+ * of those calls returns its neutral value without a fetch ever leaving the page.
30
+ */
31
+ export const DEV_SHELL_SESSION_TOKEN = 'helix-dev-simulated';
32
+ // Announced as null in helix:init: adoptShellApiBase() only fires for a non-empty string, so the SDK is
33
+ // left with no resolvable API base at all. A dev shell that named a real host would silently turn
34
+ // "offline simulated" into live backend writes as the wrong player.
35
+ const DEV_SHELL_API_BASE = null;
36
+ // What the dev shell believes the world's camera can do before the world says so: nothing. Spelled out
37
+ // here rather than imported from src/camera.ts because this module graph may reach ../protocol and its
38
+ // own files ONLY — a published world must carry zero bytes of the dev shell, and the cheapest way to
39
+ // keep that true is to keep the import edge from ever existing.
40
+ const DEV_SHELL_CAMERA_CAPABILITY = {
41
+ photo: false,
42
+ video: false,
43
+ drone: false,
44
+ twoHandPose: false,
45
+ focusPoint: false,
46
+ exposureBias: false,
47
+ worldAudio: false,
48
+ unavailableReason: 'the world has not called camera.reportCapability',
49
+ };
50
+ const defaultLogger = (message, detail) => {
51
+ if (detail === undefined)
52
+ console.log(message);
53
+ else
54
+ console.log(message, detail);
55
+ };
56
+ // Exhaustive over WorldToShellMessage — a message type added to the protocol breaks this Record, which is
57
+ // what keeps the dev shell from silently dropping a message the real shell handles.
58
+ const WORLD_MESSAGE_TYPES = {
59
+ 'helix:ready': true,
60
+ 'helix:request-login': true,
61
+ 'helix:log': true,
62
+ 'helix:open-device': true,
63
+ 'helix:multiplayer-state': true,
64
+ 'helix:multiplayer-join-error': true,
65
+ 'helix:voice-state': true,
66
+ 'helix:voice-level': true,
67
+ 'helix:camera-capability': true,
68
+ 'helix:request': true,
69
+ 'helix:notify': true,
70
+ 'helix:set-interaction-prompt': true,
71
+ 'helix:clear-interaction-prompt': true,
72
+ // The engine XR module's session state, forwarded by the SDK. Surfaced through onWorldMessage only: the
73
+ // dev shell has no overlays to hold back or input to hand back.
74
+ 'helix:xr-session': true,
75
+ // ADR-0003: answers a request only the real shell sends (World-route Claim/Buy); the dev shell never asks.
76
+ 'helix:distribution-capability-result': true,
77
+ };
78
+ function isWorldMessage(data) {
79
+ return (typeof data === 'object' &&
80
+ data !== null &&
81
+ typeof data.type === 'string' &&
82
+ Object.prototype.hasOwnProperty.call(WORLD_MESSAGE_TYPES, data.type));
83
+ }
84
+ // postMessage is cross-origin accessible on a real Window, so testing for it (rather than for
85
+ // `contentWindow`) resolves an iframe element and a window without ever touching a guarded property.
86
+ const resolveTarget = (target) => {
87
+ if (typeof target.postMessage === 'function')
88
+ return target;
89
+ return target.contentWindow;
90
+ };
91
+ /**
92
+ * Start a simulated HELIX shell around a world frame. The world must be IFRAMED — the SDK only performs
93
+ * the handshake when `window.parent !== window` — and helix:ready is answered immediately, because an
94
+ * unanswered handshake costs every boot the SDK's full 8 s INIT_TIMEOUT_MS.
95
+ */
96
+ export function createDevShell(options) {
97
+ const log = options.log ?? defaultLogger;
98
+ const world = options.world ?? DEFAULT_WORLD;
99
+ const worldOrigin = options.worldOrigin === '*' ? '*' : options.worldOrigin.replace(/\/$/, '');
100
+ const host = options.hostWindow ??
101
+ globalThis.window ??
102
+ null;
103
+ if (!host)
104
+ throw new Error('createDevShell: no window to listen on — pass options.hostWindow');
105
+ const identity = { ...DEV_SHELL_DEFAULT_IDENTITY, ...options.user };
106
+ let state = options.state
107
+ ? normalizeDevShellState(options.state, identity)
108
+ : createDevShellState({ identity });
109
+ let connected = false;
110
+ let signedIn = true;
111
+ let cameraCapability = DEV_SHELL_CAMERA_CAPABILITY;
112
+ const post = (message) => {
113
+ const target = resolveTarget(options.worldWindow);
114
+ if (!target)
115
+ return;
116
+ target.postMessage(message, worldOrigin);
117
+ };
118
+ const sessionOf = () => ({
119
+ token: DEV_SHELL_SESSION_TOKEN,
120
+ expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
121
+ scopes: options.scopes ?? ['auth.profile'],
122
+ user: {
123
+ id: state.userId,
124
+ username: state.username,
125
+ displayName: state.displayName,
126
+ },
127
+ });
128
+ const simulator = new DevShellSimulator({
129
+ state,
130
+ products: options.products,
131
+ roomTypes: options.roomTypes,
132
+ queues: options.queues,
133
+ emit: (event, data) => post({ type: 'helix:event', event, data }),
134
+ log,
135
+ onStateChange: (next) => {
136
+ state = next;
137
+ options.onStateChange?.(next);
138
+ },
139
+ onAchievementEarned: options.onAchievementEarned,
140
+ achievementDebounceMs: options.achievementDebounceMs,
141
+ });
142
+ const onMessage = (event) => {
143
+ if (worldOrigin !== '*' && event.origin !== worldOrigin)
144
+ return;
145
+ // `source` is absent on a synthetic event (and on some sandboxed frames), so it narrows the check
146
+ // when present rather than gating it.
147
+ const target = resolveTarget(options.worldWindow);
148
+ if (event.source && target && event.source !== target)
149
+ return;
150
+ if (!isWorldMessage(event.data))
151
+ return;
152
+ const message = event.data;
153
+ options.onWorldMessage?.(message);
154
+ switch (message.type) {
155
+ case 'helix:ready':
156
+ // Answered immediately AND on every retry: the SDK re-posts helix:ready until a shell replies,
157
+ // and it ignores a second helix:init, so re-answering is free.
158
+ connected = true;
159
+ post({
160
+ type: 'helix:init',
161
+ protocolVersion: PROTOCOL_VERSION,
162
+ world,
163
+ session: signedIn ? sessionOf() : null,
164
+ apiBaseUrl: DEV_SHELL_API_BASE,
165
+ ...(options.runtimeFidelity
166
+ ? { runtimeFidelity: options.runtimeFidelity }
167
+ : {}),
168
+ ...(options.debug ? { debug: true } : {}),
169
+ });
170
+ log(`${DEV_SHELL_LOG_PREFIX} handshake → helix:init (world "${world.slug}", player ${state.userId})`);
171
+ break;
172
+ case 'helix:request': {
173
+ const requestId = message.requestId;
174
+ const respond = (answer) => post({
175
+ type: 'helix:response',
176
+ requestId,
177
+ ...(answer.ok
178
+ ? { ok: true, result: answer.result }
179
+ : { ok: false, error: answer.error, ...(answer.errorCode ? { errorCode: answer.errorCode } : {}) }),
180
+ });
181
+ // The real shell confirms a purchase with the player before settling; with a confirmPurchase
182
+ // hook, so does this one. Replays and refusals skip the dialog, exactly as production does.
183
+ if (message.method === 'marketplace.purchase' && options.confirmPurchase) {
184
+ const payload = (message.payload ?? {});
185
+ const confirm = simulator.purchaseConfirmContext(typeof payload.ref === 'string' ? payload.ref : '', typeof payload.idempotencyKey === 'string' ? payload.idempotencyKey : '');
186
+ if (confirm) {
187
+ options
188
+ .confirmPurchase(confirm)
189
+ .then((buy) => respond(buy ? simulator.handle(message.method, message.payload) : simulator.cancelPurchase(confirm.ref)))
190
+ .catch(() => respond(simulator.cancelPurchase(confirm.ref)));
191
+ break;
192
+ }
193
+ }
194
+ respond(simulator.handle(message.method, message.payload));
195
+ break;
196
+ }
197
+ case 'helix:request-login':
198
+ // The simulated player is always available, so a login ask succeeds unless we are "signed out".
199
+ if (!signedIn) {
200
+ signedIn = true;
201
+ post({ type: 'helix:session', session: sessionOf() });
202
+ }
203
+ post({ type: 'helix:login-result', requestId: message.requestId, ok: true });
204
+ break;
205
+ case 'helix:log':
206
+ log(`[world] ${message.entry.level}: ${message.entry.args.join(' ')}`);
207
+ break;
208
+ case 'helix:camera-capability':
209
+ // The world is the only authority on what its rig can do, so this is RECORDED, never
210
+ // second-guessed. sendCameraState echoes it back down, which is what the real shell does
211
+ // and what stops the two sides holding two different answers to the same question.
212
+ cameraCapability = message.capability;
213
+ log(`${DEV_SHELL_LOG_PREFIX} camera capability ← world`, message.capability);
214
+ break;
215
+ default:
216
+ // notify / prompts / device / multiplayer + voice status: page-level concerns, surfaced through
217
+ // onWorldMessage above. Nothing to answer.
218
+ break;
219
+ }
220
+ };
221
+ host.addEventListener('message', onMessage);
222
+ return {
223
+ mode: 'simulated',
224
+ world,
225
+ isConnected: () => connected,
226
+ getSession: sessionOf,
227
+ getState: () => simulator.snapshot(),
228
+ setState: (next) => {
229
+ state = normalizeDevShellState(next, identity);
230
+ simulator.replaceState(state);
231
+ },
232
+ setProducts: (products) => simulator.setProducts(products),
233
+ grantAllEntitlements: () => simulator.grantAllEntitlements(),
234
+ grantEntitlement: (ref) => simulator.grantEntitlement(ref),
235
+ removeEntitlement: (ref) => simulator.removeEntitlement(ref),
236
+ getEntitlementsSnapshot: () => simulator.entitlementsSnapshot(),
237
+ setPurchasesAlwaysFail: (mode) => simulator.setPurchasesAlwaysFail(mode),
238
+ cyclePurchasesAlwaysFail: () => simulator.cyclePurchasesAlwaysFail(),
239
+ purchasesAlwaysFail: () => simulator.purchasesAlwaysFail(),
240
+ resetPlayerDocument: () => simulator.resetPlayerDocument(),
241
+ setForceSaveFailure: (on) => simulator.setForceSaveFailure(on),
242
+ exhaustConsumeFence: () => simulator.exhaustConsumeFence(),
243
+ setWallet: (wallet) => simulator.setWallet(wallet),
244
+ awardAchievement: (key) => simulator.awardAchievement(key),
245
+ resetAchievements: () => simulator.resetAchievements(),
246
+ addPlaytime: (seconds) => simulator.addPlaytime(seconds),
247
+ bumpAnalyticsEvent: (eventName, count) => simulator.bumpAnalyticsEvent(eventName, count),
248
+ setMpPlayerVar: (field, value) => simulator.setMpPlayerVar(field, value),
249
+ getAchievementsProgress: () => simulator.achievementsProgress(),
250
+ seedLeaderboardScore: (board, score, opts) => simulator.seedLeaderboardScore(board, score, opts),
251
+ seedDocument: (key, value) => simulator.seedDocument(key, value),
252
+ setRoomTypes: (roomTypes) => simulator.setRoomTypes(roomTypes),
253
+ simulateRoomJoin: (body) => simulator.joinRoom(body),
254
+ issueRoomTicket: (roomType, opts) => simulator.issueRoomTicket(roomType, opts),
255
+ rejoinRoomInstance: (instanceId) => simulator.rejoinRoomInstance(instanceId),
256
+ closeRoomInstance: (instanceId) => simulator.closeRoomInstance(instanceId),
257
+ setQueues: (queues) => simulator.setQueues(queues),
258
+ simulatePlatformRequest: (method, path, body) => simulator.platformRequest(method, path, body),
259
+ formMatch: (opts) => simulator.formMatch(opts),
260
+ endQueueTicket: (reason) => simulator.endQueueTicket(reason),
261
+ setPartyMemberMatch: (userId) => simulator.setPartyMemberMatch(userId),
262
+ receivePartyInvite: (from, opts) => simulator.receivePartyInvite(from, opts),
263
+ acceptPartyInvite: (inviteId, displayName) => simulator.acceptPartyInvite(inviteId, displayName),
264
+ openPartyCode: (host, opts) => simulator.openPartyCode(host, opts),
265
+ usePartyCode: (code, member) => simulator.usePartyCode(code, member),
266
+ setSignedIn: (next) => {
267
+ signedIn = next;
268
+ log(`${DEV_SHELL_LOG_PREFIX} session → ${next ? 'signed in' : 'signed out'}`);
269
+ post({ type: 'helix:session', session: next ? sessionOf() : null });
270
+ },
271
+ sendVoiceSettings: (settings) => post({ type: 'helix:voice-settings', settings }),
272
+ sendCameraState: (cameraState) => post({ type: 'helix:camera-state', state: { ...cameraState, capability: cameraCapability } }),
273
+ getCameraCapability: () => ({ ...cameraCapability }),
274
+ sendLeave: () => post({ type: 'helix:leave' }),
275
+ pushEvent: (event, data) => post({ type: 'helix:event', event, data }),
276
+ dispose: () => {
277
+ host.removeEventListener('message', onMessage);
278
+ simulator.cancelPendingAchievementPoke();
279
+ connected = false;
280
+ },
281
+ };
282
+ }
283
+ /** A fresh, empty state for a given identity — the `--fresh` / `--reset` seed. */
284
+ export function createFreshDevShellState(identity) {
285
+ return createDevShellState({ identity });
286
+ }
287
+ //# sourceMappingURL=index.js.map