@threenative/core 0.3.11 → 0.3.12

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 (157) hide show
  1. package/capabilities.json +1096 -26
  2. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  3. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-CWuFRT7G.d.ts} +1 -1
  4. package/dist/chunk-2Z44XSI2.js +35 -0
  5. package/dist/chunk-5O73CDMR.js +1849 -0
  6. package/dist/chunk-6KLNISRJ.js +153 -0
  7. package/dist/chunk-7UUT3TY5.js +133 -0
  8. package/dist/chunk-CFGTPFUH.js +231 -0
  9. package/dist/chunk-DBELTTTM.js +615 -0
  10. package/dist/chunk-GMHATRPW.js +7701 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-KIRUKTBQ.js +187 -0
  13. package/dist/chunk-N5LRP4BR.js +220 -0
  14. package/dist/chunk-OKXUCASC.js +2238 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-VAZM36TV.js +497 -0
  17. package/dist/{game-DzMcitDO.d.ts → game-D7pAzZUY.d.ts} +15 -3
  18. package/dist/hot.d.ts +3 -3
  19. package/dist/hot.js +2 -46
  20. package/dist/index.d.ts +329 -302
  21. package/dist/index.js +10566 -22552
  22. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-B6BMqS1r.d.ts} +33 -3
  23. package/dist/playtest.d.ts +3 -3
  24. package/dist/playtest.js +24 -75
  25. package/dist/react-css.js +1 -215
  26. package/dist/react.d.ts +2 -2
  27. package/dist/{renderer-rZm0hVqq.d.ts → renderer-DvFVoAgj.d.ts} +13 -4
  28. package/dist/spells/index.d.ts +643 -0
  29. package/dist/spells/index.js +1558 -0
  30. package/dist/spells/ultra/index.d.ts +1600 -0
  31. package/dist/spells/ultra/index.js +6804 -0
  32. package/dist/terrain-jobs-worker.js +1 -123
  33. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  34. package/dist/ui-layer.js +5 -384
  35. package/dist/worker.js +4 -41
  36. package/dist/world.d.ts +725 -259
  37. package/dist/world.js +16714 -18284
  38. package/mcp/animation-server.mjs +1 -1
  39. package/mcp/animation.mjs +2 -3
  40. package/mcp/engine-server.mjs +142 -47
  41. package/mcp/servers.mjs +9 -2
  42. package/mcp/terrain.mjs +8 -0
  43. package/package.json +14 -6
  44. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  45. package/patches/three@0.187.0.patch +2004 -407
  46. package/src/assets.ts +9 -2
  47. package/src/card-lod.ts +152 -0
  48. package/src/compressed-texture-preparation.ts +1008 -0
  49. package/src/frame-budget.ts +31 -20
  50. package/src/game-dev-tools.ts +93 -0
  51. package/src/game-frame-loop.ts +995 -0
  52. package/src/game-renderer-metrics.ts +77 -0
  53. package/src/game-startup.ts +1001 -0
  54. package/src/game-validate.ts +70 -0
  55. package/src/game.ts +253 -1935
  56. package/src/index.ts +27 -2
  57. package/src/launch-diagnostics.ts +22 -12
  58. package/src/look/ao-admission.ts +24 -0
  59. package/src/look/filmic-tone-mapping.ts +15 -13
  60. package/src/look/look-diagnostics.ts +3 -3
  61. package/src/look/quality.ts +10 -5
  62. package/src/look/world-environment.ts +76 -9
  63. package/src/loop.ts +29 -0
  64. package/src/model-lod.ts +42 -3
  65. package/src/particle-kinds.ts +515 -0
  66. package/src/picking.ts +17 -3
  67. package/src/playtest.ts +27 -1
  68. package/src/projection-apply.ts +4 -1
  69. package/src/projection-plan.ts +9 -6
  70. package/src/render/mesh-pool.ts +1 -1
  71. package/src/render/resolution-subrect.ts +2 -0
  72. package/src/render/rough-diffuse.ts +46 -12
  73. package/src/render/soft-shadow.ts +27 -12
  74. package/src/render/virtual-shadow-adaptive.ts +55 -0
  75. package/src/render/virtual-shadow-casters.ts +175 -0
  76. package/src/render/virtual-shadow-layers.ts +76 -0
  77. package/src/render/virtual-shadow-level.ts +224 -0
  78. package/src/render/virtual-shadow-markers.ts +193 -0
  79. package/src/render/virtual-shadow-options.ts +370 -0
  80. package/src/render/virtual-shadow-pages.ts +5 -0
  81. package/src/render/virtual-shadow.ts +213 -992
  82. package/src/render/world-impostor-surface.ts +293 -34
  83. package/src/render-pass-budget.ts +34 -7
  84. package/src/renderProjection.ts +22 -0
  85. package/src/renderer.ts +92 -37
  86. package/src/snow-field.ts +1 -1
  87. package/src/spells/cast-pool.ts +361 -0
  88. package/src/spells/index.ts +177 -0
  89. package/src/spells/mechanisms.ts +295 -0
  90. package/src/spells/reaction-field.ts +415 -0
  91. package/src/spells/spell-lights.ts +139 -0
  92. package/src/spells/spell-world.ts +187 -0
  93. package/src/spells/spell.ts +397 -0
  94. package/src/spells/spells.ts +283 -0
  95. package/src/spells/ultra/engine/camera.ts +184 -0
  96. package/src/spells/ultra/engine/quality.ts +96 -0
  97. package/src/spells/ultra/index.ts +52 -0
  98. package/src/spells/ultra/main.ts +305 -0
  99. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  100. package/src/spells/ultra/spells/cast.ts +233 -0
  101. package/src/spells/ultra/spells/fire.ts +1267 -0
  102. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  103. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  104. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  105. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  106. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  107. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  108. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  109. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  110. package/src/spells/ultra/vfx/common.ts +1195 -0
  111. package/src/spells/ultra/vfx/noise.ts +441 -0
  112. package/src/startup-readiness.ts +128 -34
  113. package/src/version.ts +1 -1
  114. package/src/warmup.ts +56 -8
  115. package/src/water-surface.ts +9 -3
  116. package/src/world-bundle-safety.ts +401 -0
  117. package/src/world-cell-batches.ts +1216 -0
  118. package/src/world-cell-chunks.ts +1132 -0
  119. package/src/world-cell-data.ts +995 -0
  120. package/src/world-cell-impostors.ts +1449 -0
  121. package/src/world-cell-lod-bias.ts +151 -0
  122. package/src/world-cell-models.ts +1074 -0
  123. package/src/world-cell-options.ts +189 -0
  124. package/src/world-cell-placements.ts +694 -0
  125. package/src/world-cell-prewarm.ts +557 -0
  126. package/src/world-cell-readiness.ts +357 -0
  127. package/src/world-cell-render-bundles.ts +459 -0
  128. package/src/world-cell-render-gpu-dress.ts +714 -0
  129. package/src/world-cell-render-main-cull.ts +484 -0
  130. package/src/world-cell-render-shadow-claims.ts +198 -0
  131. package/src/world-cell-render-util.ts +246 -0
  132. package/src/world-cell-render.ts +1493 -0
  133. package/src/world-cell-residency.ts +745 -0
  134. package/src/world-cells.ts +1318 -10418
  135. package/src/world-chunk-shadow.ts +308 -0
  136. package/src/world-collar.ts +315 -0
  137. package/src/world-gpu-flags.ts +163 -0
  138. package/src/world-gpu-readback.ts +881 -0
  139. package/src/world-gpu-reference.ts +510 -0
  140. package/src/world-gpu-scene.ts +214 -2264
  141. package/src/world-gpu-shadow.ts +190 -0
  142. package/src/world-gpu-types.ts +381 -0
  143. package/src/world-gpu-validation.ts +518 -0
  144. package/src/world-heightfield.ts +802 -0
  145. package/src/world-load-limiter.ts +106 -0
  146. package/src/world-noise.ts +241 -0
  147. package/src/world-package.ts +42 -0
  148. package/src/world-region.ts +1 -1
  149. package/src/world-terrain-splat.ts +365 -149
  150. package/src/world-tile-budget.ts +256 -0
  151. package/src/world-tile-geometry.ts +469 -0
  152. package/src/world-tile-lod.ts +408 -0
  153. package/src/world-tile-observation.ts +566 -0
  154. package/src/world-tile-stitch.ts +166 -0
  155. package/src/world-tiles.ts +170 -1745
  156. package/src/world-water-bodies.ts +359 -0
  157. package/src/world.ts +35 -741
@@ -0,0 +1,153 @@
1
+ // src/platform.ts
2
+ var DESKTOP_OS = /* @__PURE__ */ new Set(["linux", "macos", "windows"]);
3
+ var MOBILE_OS = /* @__PURE__ */ new Set(["android", "ios"]);
4
+ function isRecord(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+ function freezePlatform(value) {
8
+ return Object.freeze(value);
9
+ }
10
+ function invalidNativePlatform(reason) {
11
+ throw new Error(`TN_NATIVE_PLATFORM_INVALID: ${reason}`);
12
+ }
13
+ function nativePlatform(source) {
14
+ if (!isRecord(source)) invalidNativePlatform("the native marker is not an object");
15
+ const descriptor = source.platform;
16
+ if (!isRecord(descriptor)) invalidNativePlatform("platform descriptor is missing");
17
+ const runtime = descriptor.runtime;
18
+ const os = descriptor.os;
19
+ const formFactor = descriptor.formFactor;
20
+ const maxTouchPoints = descriptor.maxTouchPoints;
21
+ if (runtime !== "native") invalidNativePlatform("runtime must be native");
22
+ if (os !== "android" && os !== "ios" && os !== "linux" && os !== "macos" && os !== "windows" && os !== "unknown") {
23
+ invalidNativePlatform("os is unknown");
24
+ }
25
+ if (formFactor !== "mobile" && formFactor !== "desktop" && formFactor !== "unknown") {
26
+ invalidNativePlatform("formFactor is unknown");
27
+ }
28
+ if (!Number.isInteger(maxTouchPoints) || maxTouchPoints < 0) {
29
+ invalidNativePlatform("maxTouchPoints must be a non-negative integer");
30
+ }
31
+ const expectedFormFactor = MOBILE_OS.has(os) ? "mobile" : DESKTOP_OS.has(os) ? "desktop" : "unknown";
32
+ if (formFactor !== expectedFormFactor) {
33
+ invalidNativePlatform("os and formFactor disagree");
34
+ }
35
+ return freezePlatform({
36
+ formFactor,
37
+ maxTouchPoints,
38
+ os,
39
+ runtime
40
+ });
41
+ }
42
+ function text(value) {
43
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
44
+ }
45
+ function parseOS(value) {
46
+ if (value === void 0) return void 0;
47
+ const normalized = value.toLowerCase();
48
+ if (normalized.includes("android")) return "android";
49
+ if (/(iphone|ipad|ipod|ios)/u.test(normalized)) return "ios";
50
+ if (/(windows|win32|win64|winnt|wince)/u.test(normalized)) return "windows";
51
+ if (/(macintosh|mac os|macos|macintel|macppc|mac68k)/u.test(normalized)) return "macos";
52
+ if (/(linux|x11)/u.test(normalized)) return "linux";
53
+ return void 0;
54
+ }
55
+ function compatibleBrowserOS(left, right, iosUserAgent) {
56
+ if (left === right) return true;
57
+ if (left === "android" && right === "linux" || left === "linux" && right === "android")
58
+ return true;
59
+ if (iosUserAgent && (left === "ios" && right === "macos" || left === "macos" && right === "ios"))
60
+ return true;
61
+ return false;
62
+ }
63
+ function resolveBrowserOS(userAgentDataOS, navigatorOS, userAgentOS, iosUserAgent) {
64
+ let resolved;
65
+ for (const candidate of [userAgentDataOS, navigatorOS, userAgentOS]) {
66
+ if (candidate === void 0) continue;
67
+ if (resolved === void 0) {
68
+ resolved = candidate;
69
+ continue;
70
+ }
71
+ if (!compatibleBrowserOS(resolved, candidate, iosUserAgent)) return "unknown";
72
+ if (resolved === "linux" && candidate === "android" || resolved === "macos" && candidate === "ios") {
73
+ resolved = candidate;
74
+ }
75
+ }
76
+ return resolved ?? "unknown";
77
+ }
78
+ function readTouchPoints(value) {
79
+ return Number.isInteger(value) && value >= 0 ? value : 0;
80
+ }
81
+ function browserPlatform(source) {
82
+ if (!isRecord(source)) {
83
+ return freezePlatform({
84
+ formFactor: "unknown",
85
+ maxTouchPoints: 0,
86
+ os: "unknown",
87
+ runtime: "web"
88
+ });
89
+ }
90
+ const userAgentData = isRecord(source.userAgentData) ? source.userAgentData : void 0;
91
+ const userAgentDataOS = parseOS(text(userAgentData?.platform));
92
+ const navigatorOS = parseOS(text(source.platform));
93
+ const userAgent = text(source.userAgent);
94
+ const userAgentOS = parseOS(userAgent);
95
+ const iosUserAgent = userAgentOS === "ios";
96
+ const os = resolveBrowserOS(userAgentDataOS, navigatorOS, userAgentOS, iosUserAgent);
97
+ let formFactor = "unknown";
98
+ if (typeof userAgentData?.mobile === "boolean") {
99
+ formFactor = userAgentData.mobile ? "mobile" : "desktop";
100
+ } else if (MOBILE_OS.has(os)) {
101
+ formFactor = "mobile";
102
+ } else if (DESKTOP_OS.has(os)) {
103
+ formFactor = "desktop";
104
+ }
105
+ if (os === "unknown") formFactor = "unknown";
106
+ return freezePlatform({
107
+ formFactor,
108
+ maxTouchPoints: readTouchPoints(source.maxTouchPoints),
109
+ os,
110
+ runtime: "web"
111
+ });
112
+ }
113
+ function globalPlatformSource() {
114
+ const globals = globalThis;
115
+ return {
116
+ native: globals.__THREENATIVE_NATIVE__,
117
+ navigator: globals.__tnPageNavigator ?? globals.navigator
118
+ };
119
+ }
120
+ function detectPlatform(source = globalPlatformSource()) {
121
+ return source.native === void 0 ? browserPlatform(source.navigator) : nativePlatform(source.native);
122
+ }
123
+ var platformSnapshot;
124
+ function getPlatform() {
125
+ platformSnapshot ??= detectPlatform();
126
+ return platformSnapshot;
127
+ }
128
+ function isWeb() {
129
+ return getPlatform().runtime === "web";
130
+ }
131
+ function isNative() {
132
+ return getPlatform().runtime === "native";
133
+ }
134
+ function isMobile() {
135
+ return getPlatform().formFactor === "mobile";
136
+ }
137
+ function isTouchscreenAvailable() {
138
+ return getPlatform().maxTouchPoints > 0;
139
+ }
140
+ function hostWindow() {
141
+ return typeof window === "undefined" ? void 0 : window;
142
+ }
143
+ function hostGestureTarget() {
144
+ return hostWindow() ?? globalThis.__tnGamePlatform?.inputTarget;
145
+ }
146
+ function hostDocument() {
147
+ return typeof document === "undefined" ? void 0 : document;
148
+ }
149
+ function hostResizeObserver() {
150
+ return typeof ResizeObserver === "undefined" ? void 0 : ResizeObserver;
151
+ }
152
+
153
+ export { getPlatform, hostDocument, hostGestureTarget, hostResizeObserver, hostWindow, isMobile, isNative, isTouchscreenAvailable, isWeb };
@@ -0,0 +1,133 @@
1
+ import { debugRequested, countDebug, measureDebug } from './chunk-N5LRP4BR.js';
2
+ import { UI_STARTUP_MESSAGE, GAME_STATE_MESSAGE, UI_INTENT_MESSAGE, postUiState, serializeUiState } from './chunk-CFGTPFUH.js';
3
+
4
+ // src/ui-state.ts
5
+ var microtask = (flush) => {
6
+ void Promise.resolve().then(flush);
7
+ };
8
+ function publishUiState(bridge, store, options = {}) {
9
+ if (bridge.end !== "game") {
10
+ throw new Error(
11
+ `TN_UI_STATE_WRONG_END: state is published by the 'game' end, not '${bridge.end}'.`
12
+ );
13
+ }
14
+ const schedule = options.schedule ?? microtask;
15
+ const debug = debugRequested();
16
+ const serialize = debug ? (state) => {
17
+ countDebug("uiSerializations", 1, "ui", "publishUiState");
18
+ return measureDebug("uiSerialize", "ui", "publishUiState", () => serializeUiState(state));
19
+ } : serializeUiState;
20
+ const read = () => store.getPublishedState === void 0 ? store.getState() : store.getPublishedState();
21
+ let stopped = false;
22
+ let queued = false;
23
+ let lastFrame = "";
24
+ const send = (state, frame) => {
25
+ lastFrame = frame;
26
+ postUiState(bridge, state, frame);
27
+ if (debug) {
28
+ countDebug("uiMessages", 1, "ui", "publishUiState");
29
+ countDebug(
30
+ "uiMessageBytes",
31
+ new TextEncoder().encode(frame).byteLength,
32
+ "ui",
33
+ "publishUiState"
34
+ );
35
+ }
36
+ };
37
+ const publish = () => {
38
+ if (stopped) return;
39
+ const state = read();
40
+ send(state, serialize(state));
41
+ };
42
+ const flush = () => {
43
+ queued = false;
44
+ if (stopped) return;
45
+ if (!bridge.hasPeer()) return;
46
+ const state = read();
47
+ const frame = serialize(state);
48
+ if (frame === lastFrame) return;
49
+ send(state, frame);
50
+ };
51
+ const unsubscribe = store.subscribe(() => {
52
+ if (stopped || queued) return;
53
+ queued = true;
54
+ schedule(flush);
55
+ });
56
+ if (bridge.hasPeer()) publish();
57
+ return {
58
+ publish,
59
+ stop() {
60
+ stopped = true;
61
+ unsubscribe();
62
+ }
63
+ };
64
+ }
65
+ function subscribeUiState(bridge) {
66
+ if (bridge.end !== "ui") {
67
+ throw new Error(
68
+ `TN_UI_STATE_WRONG_END: state is mirrored by the 'ui' end, not '${bridge.end}'.`
69
+ );
70
+ }
71
+ const listeners = /* @__PURE__ */ new Set();
72
+ let current;
73
+ let covered = false;
74
+ const off = bridge.onMessage((message) => {
75
+ if (message.type === UI_STARTUP_MESSAGE) {
76
+ const next = message.phase !== "ready";
77
+ if (next === covered) return;
78
+ covered = next;
79
+ for (const listener of [...listeners]) listener();
80
+ return;
81
+ }
82
+ if (message.type !== GAME_STATE_MESSAGE) return;
83
+ const state = message.state;
84
+ if (typeof state !== "object" || state === null || Array.isArray(state)) {
85
+ throw new Error("TN_UI_STATE_FRAME_INVALID: a published state frame must carry an object.");
86
+ }
87
+ current = state;
88
+ for (const listener of [...listeners]) listener();
89
+ });
90
+ return {
91
+ get: () => current,
92
+ covered: () => covered,
93
+ subscribe(listener) {
94
+ listeners.add(listener);
95
+ return () => listeners.delete(listener);
96
+ },
97
+ stop() {
98
+ off();
99
+ listeners.clear();
100
+ }
101
+ };
102
+ }
103
+ function sendUiIntent(bridge, intent, payload) {
104
+ if (bridge.end !== "ui") {
105
+ throw new Error(
106
+ `TN_UI_INTENT_WRONG_END: intents are sent by the 'ui' end, not '${bridge.end}'.`
107
+ );
108
+ }
109
+ if (typeof intent !== "string" || intent.length === 0) {
110
+ throw new Error("TN_UI_INTENT_INVALID: an intent needs a non-empty name.");
111
+ }
112
+ bridge.post({
113
+ type: UI_INTENT_MESSAGE,
114
+ intent,
115
+ ...payload === void 0 ? {} : { payload }
116
+ });
117
+ }
118
+ function onUiIntent(bridge, listener) {
119
+ if (bridge.end !== "game") {
120
+ throw new Error(
121
+ `TN_UI_INTENT_WRONG_END: intents are received by the 'game' end, not '${bridge.end}'.`
122
+ );
123
+ }
124
+ return bridge.onMessage((message) => {
125
+ if (message.type !== UI_INTENT_MESSAGE) return;
126
+ if (typeof message.intent !== "string" || message.intent.length === 0) {
127
+ throw new Error("TN_UI_INTENT_INVALID: an intent frame must carry a non-empty name.");
128
+ }
129
+ listener(message.intent, message.payload);
130
+ });
131
+ }
132
+
133
+ export { onUiIntent, publishUiState, sendUiIntent, subscribeUiState };
@@ -0,0 +1,231 @@
1
+ // src/ui-bridge.ts
2
+ var HIT_REGIONS_MESSAGE = "tn:hit-regions";
3
+ var GAME_STATE_MESSAGE = "tn:state";
4
+ var UI_INTENT_MESSAGE = "tn:intent";
5
+ var UI_DEV_METRICS_MESSAGE = "tn:dev-metrics";
6
+ var UI_STARTUP_MESSAGE = "tn:startup";
7
+ var UI_READY_INTENT = "tn:ready";
8
+ var UI_BRIDGE_GLOBALS = {
9
+ /** UI end, inbound: the host calls this with one JSON string. */
10
+ uiReceive: "__tnUiReceive",
11
+ /** UI end, outbound: an injected object with `postMessage(string)`. */
12
+ uiHost: "tnHost",
13
+ /** Game end, inbound: the runtime calls this with one JSON string. */
14
+ gameReceive: "__tnUiGameReceive",
15
+ /** Game end, outbound: the runtime installs this and forwards to the web view. */
16
+ gamePost: "__tnUiPost"
17
+ };
18
+ var stateFrames = /* @__PURE__ */ new WeakMap();
19
+ function serializeUiState(state) {
20
+ return assertSendable({ type: GAME_STATE_MESSAGE, state });
21
+ }
22
+ function postUiState(bridge, state, frame) {
23
+ const message = { type: GAME_STATE_MESSAGE, state };
24
+ stateFrames.set(message, frame);
25
+ try {
26
+ bridge.post(message);
27
+ } finally {
28
+ stateFrames.delete(message);
29
+ }
30
+ }
31
+ function assertSendable(message) {
32
+ if (typeof message !== "object" || message === null || Array.isArray(message)) {
33
+ throw new Error("TN_UI_BRIDGE_MESSAGE_INVALID: a bridge message must be a JSON object.");
34
+ }
35
+ if (typeof message.type !== "string" || message.type.length === 0) {
36
+ throw new Error("TN_UI_BRIDGE_MESSAGE_INVALID: a bridge message must carry a string 'type'.");
37
+ }
38
+ let frame;
39
+ try {
40
+ frame = stateFrames.get(message) ?? JSON.stringify(message);
41
+ } catch (error) {
42
+ throw new Error(
43
+ `TN_UI_BRIDGE_MESSAGE_INVALID: '${message.type}' is not JSON-serialisable: ${error instanceof Error ? error.message : String(error)}`
44
+ );
45
+ }
46
+ if (frame === void 0) {
47
+ throw new Error(`TN_UI_BRIDGE_MESSAGE_INVALID: '${message.type}' serialised to nothing.`);
48
+ }
49
+ return frame;
50
+ }
51
+ function parseFrame(frame) {
52
+ const text = typeof frame === "string" ? frame : frame?.data;
53
+ if (typeof text !== "string") {
54
+ throw new Error("TN_UI_BRIDGE_FRAME_INVALID: expected a JSON string from the host.");
55
+ }
56
+ let parsed;
57
+ try {
58
+ parsed = JSON.parse(text);
59
+ } catch (error) {
60
+ throw new Error(
61
+ `TN_UI_BRIDGE_FRAME_INVALID: not JSON: ${error instanceof Error ? error.message : String(error)}`
62
+ );
63
+ }
64
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
65
+ throw new Error("TN_UI_BRIDGE_FRAME_INVALID: a bridge frame must be a JSON object.");
66
+ }
67
+ if (typeof parsed.type !== "string") {
68
+ throw new Error("TN_UI_BRIDGE_FRAME_INVALID: a bridge frame must carry a string 'type'.");
69
+ }
70
+ return parsed;
71
+ }
72
+ function findOutbound(scope, end) {
73
+ if (end === "game") {
74
+ const post = scope[UI_BRIDGE_GLOBALS.gamePost];
75
+ return typeof post === "function" ? (frame) => post(frame) : void 0;
76
+ }
77
+ const injected = scope[UI_BRIDGE_GLOBALS.uiHost];
78
+ if (typeof injected?.postMessage === "function") {
79
+ return (frame) => injected.postMessage(frame);
80
+ }
81
+ const webkit = scope.webkit;
82
+ const handler = webkit?.messageHandlers?.[UI_BRIDGE_GLOBALS.uiHost];
83
+ if (typeof handler?.postMessage === "function") {
84
+ return (frame) => handler.postMessage(frame);
85
+ }
86
+ const ipc = scope.ipc;
87
+ if (typeof ipc?.postMessage === "function") {
88
+ return (frame) => ipc.postMessage(frame);
89
+ }
90
+ return void 0;
91
+ }
92
+ var BROKER_KEY = "__tnUiBridgeBroker";
93
+ function broker(scope) {
94
+ const existing = scope[BROKER_KEY];
95
+ if (existing !== void 0) return existing;
96
+ const created = { game: /* @__PURE__ */ new Set(), ui: /* @__PURE__ */ new Set(), inbound: /* @__PURE__ */ new Map() };
97
+ scope[BROKER_KEY] = created;
98
+ return created;
99
+ }
100
+ function installInbound(scope, key, deliver) {
101
+ const bus = broker(scope);
102
+ let slot = bus.inbound.get(key);
103
+ if (slot === void 0) {
104
+ const receivers = /* @__PURE__ */ new Set();
105
+ slot = {
106
+ receivers,
107
+ dispatch: (frame) => {
108
+ let firstError;
109
+ let failed = false;
110
+ for (const receiver of [...receivers]) {
111
+ try {
112
+ receiver(frame);
113
+ } catch (error) {
114
+ if (!failed) {
115
+ failed = true;
116
+ firstError = error;
117
+ }
118
+ }
119
+ }
120
+ if (failed) throw firstError;
121
+ }
122
+ };
123
+ bus.inbound.set(key, slot);
124
+ }
125
+ slot.receivers.add(deliver);
126
+ scope[key] = slot.dispatch;
127
+ const installed = slot;
128
+ return () => {
129
+ installed.receivers.delete(deliver);
130
+ if (installed.receivers.size === 0 && scope[key] === installed.dispatch) scope[key] = void 0;
131
+ };
132
+ }
133
+ var LOOPBACK_KEY = "__tnUiLoopback";
134
+ function installLoopback(scope) {
135
+ const search = scope.location?.search;
136
+ if (typeof search !== "string" || new URLSearchParams(search).get("tnUiLoopback") !== "1") return;
137
+ if (scope[LOOPBACK_KEY] !== void 0) return;
138
+ const { port1: gamePort, port2: uiPort } = new MessageChannel();
139
+ const receive = (key) => (event) => scope[key]?.(event.data);
140
+ gamePort.onmessage = receive(UI_BRIDGE_GLOBALS.gameReceive);
141
+ uiPort.onmessage = receive(UI_BRIDGE_GLOBALS.uiReceive);
142
+ scope[UI_BRIDGE_GLOBALS.gamePost] = (frame) => gamePort.postMessage(frame);
143
+ scope[UI_BRIDGE_GLOBALS.uiHost] = { postMessage: (frame) => uiPort.postMessage(frame) };
144
+ scope.__tnUiOverlayAttached = () => true;
145
+ scope[LOOPBACK_KEY] = {
146
+ close() {
147
+ gamePort.close();
148
+ uiPort.close();
149
+ for (const key of [UI_BRIDGE_GLOBALS.gamePost, UI_BRIDGE_GLOBALS.uiHost, LOOPBACK_KEY])
150
+ scope[key] = void 0;
151
+ scope.__tnUiOverlayAttached = void 0;
152
+ }
153
+ };
154
+ }
155
+ function connectUiBridge(options) {
156
+ const { end } = options;
157
+ if (end !== "game" && end !== "ui") {
158
+ throw new Error(`TN_UI_BRIDGE_END_INVALID: expected 'game' or 'ui', got '${String(end)}'.`);
159
+ }
160
+ const scope = options.scope ?? globalThis;
161
+ installLoopback(scope);
162
+ const listeners = /* @__PURE__ */ new Set();
163
+ const deliver = (frame) => {
164
+ const message = parseFrame(frame);
165
+ for (const listener of [...listeners]) listener(message);
166
+ };
167
+ const outbound = findOutbound(scope, end);
168
+ const inboundKey = end === "ui" ? UI_BRIDGE_GLOBALS.uiReceive : UI_BRIDGE_GLOBALS.gameReceive;
169
+ let closed = false;
170
+ if (outbound === void 0) {
171
+ const bus = broker(scope);
172
+ const peer = end === "ui" ? "game" : "ui";
173
+ const own = (message) => {
174
+ for (const listener of [...listeners]) listener(message);
175
+ };
176
+ bus[end].add(own);
177
+ return {
178
+ end,
179
+ transport: "in-process",
180
+ hasPeer: () => bus[peer].size > 0,
181
+ post(message) {
182
+ const frame = assertSendable(message);
183
+ if (closed) throw new Error("TN_UI_BRIDGE_CLOSED: post on a closed bridge.");
184
+ const copy = JSON.parse(frame);
185
+ for (const listener of [...bus[peer]]) listener(copy);
186
+ },
187
+ onMessage(listener) {
188
+ listeners.add(listener);
189
+ return () => listeners.delete(listener);
190
+ },
191
+ close() {
192
+ closed = true;
193
+ listeners.clear();
194
+ bus[end].delete(own);
195
+ }
196
+ };
197
+ }
198
+ const uninstall = installInbound(scope, inboundKey, deliver);
199
+ const injected = scope[UI_BRIDGE_GLOBALS.uiHost];
200
+ if (end === "ui" && injected !== void 0 && typeof injected === "object") {
201
+ injected.onmessage = (event) => deliver(event);
202
+ }
203
+ return {
204
+ end,
205
+ transport: "host",
206
+ hasPeer() {
207
+ const attached = scope.__tnUiOverlayAttached;
208
+ if (end === "ui") return true;
209
+ return typeof attached === "function" ? attached() === true : false;
210
+ },
211
+ post(message) {
212
+ const frame = assertSendable(message);
213
+ if (closed) throw new Error("TN_UI_BRIDGE_CLOSED: post on a closed bridge.");
214
+ outbound(frame);
215
+ },
216
+ onMessage(listener) {
217
+ listeners.add(listener);
218
+ return () => listeners.delete(listener);
219
+ },
220
+ close() {
221
+ closed = true;
222
+ listeners.clear();
223
+ uninstall();
224
+ if (end === "ui" && injected !== void 0 && typeof injected === "object") {
225
+ injected.onmessage = void 0;
226
+ }
227
+ }
228
+ };
229
+ }
230
+
231
+ export { GAME_STATE_MESSAGE, HIT_REGIONS_MESSAGE, UI_BRIDGE_GLOBALS, UI_DEV_METRICS_MESSAGE, UI_INTENT_MESSAGE, UI_READY_INTENT, UI_STARTUP_MESSAGE, connectUiBridge, postUiState, serializeUiState };