@textadventures/quest-viva-wasmplayer 6.0.0-beta.50

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 (227) hide show
  1. package/.stamp +0 -0
  2. package/WasmPlayer.runtimeconfig.json +46 -0
  3. package/_framework/Common.wasm +0 -0
  4. package/_framework/Engine.wasm +0 -0
  5. package/_framework/ExtendedNumerics.BigDecimal.wasm +0 -0
  6. package/_framework/Legacy.wasm +0 -0
  7. package/_framework/Microsoft.CSharp.wasm +0 -0
  8. package/_framework/Microsoft.Extensions.DependencyInjection.Abstractions.wasm +0 -0
  9. package/_framework/Microsoft.Extensions.Logging.Abstractions.wasm +0 -0
  10. package/_framework/Microsoft.VisualBasic.Core.wasm +0 -0
  11. package/_framework/Microsoft.VisualBasic.wasm +0 -0
  12. package/_framework/Microsoft.Win32.Primitives.wasm +0 -0
  13. package/_framework/Microsoft.Win32.Registry.wasm +0 -0
  14. package/_framework/NCalc.Async.wasm +0 -0
  15. package/_framework/NCalc.Core.wasm +0 -0
  16. package/_framework/NCalc.Domain.wasm +0 -0
  17. package/_framework/NCalc.Parser.wasm +0 -0
  18. package/_framework/Parlot.wasm +0 -0
  19. package/_framework/PlayerCore.wasm +0 -0
  20. package/_framework/System.AppContext.wasm +0 -0
  21. package/_framework/System.Buffers.wasm +0 -0
  22. package/_framework/System.Collections.Concurrent.wasm +0 -0
  23. package/_framework/System.Collections.Immutable.wasm +0 -0
  24. package/_framework/System.Collections.NonGeneric.wasm +0 -0
  25. package/_framework/System.Collections.Specialized.wasm +0 -0
  26. package/_framework/System.Collections.wasm +0 -0
  27. package/_framework/System.ComponentModel.Annotations.wasm +0 -0
  28. package/_framework/System.ComponentModel.DataAnnotations.wasm +0 -0
  29. package/_framework/System.ComponentModel.EventBasedAsync.wasm +0 -0
  30. package/_framework/System.ComponentModel.Primitives.wasm +0 -0
  31. package/_framework/System.ComponentModel.TypeConverter.wasm +0 -0
  32. package/_framework/System.ComponentModel.wasm +0 -0
  33. package/_framework/System.Configuration.wasm +0 -0
  34. package/_framework/System.Console.wasm +0 -0
  35. package/_framework/System.Core.wasm +0 -0
  36. package/_framework/System.Data.Common.wasm +0 -0
  37. package/_framework/System.Data.DataSetExtensions.wasm +0 -0
  38. package/_framework/System.Data.wasm +0 -0
  39. package/_framework/System.Diagnostics.Contracts.wasm +0 -0
  40. package/_framework/System.Diagnostics.Debug.wasm +0 -0
  41. package/_framework/System.Diagnostics.DiagnosticSource.wasm +0 -0
  42. package/_framework/System.Diagnostics.FileVersionInfo.wasm +0 -0
  43. package/_framework/System.Diagnostics.Process.wasm +0 -0
  44. package/_framework/System.Diagnostics.StackTrace.wasm +0 -0
  45. package/_framework/System.Diagnostics.TextWriterTraceListener.wasm +0 -0
  46. package/_framework/System.Diagnostics.Tools.wasm +0 -0
  47. package/_framework/System.Diagnostics.TraceSource.wasm +0 -0
  48. package/_framework/System.Diagnostics.Tracing.wasm +0 -0
  49. package/_framework/System.Drawing.Primitives.wasm +0 -0
  50. package/_framework/System.Drawing.wasm +0 -0
  51. package/_framework/System.Dynamic.Runtime.wasm +0 -0
  52. package/_framework/System.Formats.Asn1.wasm +0 -0
  53. package/_framework/System.Formats.Tar.wasm +0 -0
  54. package/_framework/System.Globalization.Calendars.wasm +0 -0
  55. package/_framework/System.Globalization.Extensions.wasm +0 -0
  56. package/_framework/System.Globalization.wasm +0 -0
  57. package/_framework/System.IO.Compression.Brotli.wasm +0 -0
  58. package/_framework/System.IO.Compression.FileSystem.wasm +0 -0
  59. package/_framework/System.IO.Compression.ZipFile.wasm +0 -0
  60. package/_framework/System.IO.Compression.wasm +0 -0
  61. package/_framework/System.IO.FileSystem.AccessControl.wasm +0 -0
  62. package/_framework/System.IO.FileSystem.DriveInfo.wasm +0 -0
  63. package/_framework/System.IO.FileSystem.Primitives.wasm +0 -0
  64. package/_framework/System.IO.FileSystem.Watcher.wasm +0 -0
  65. package/_framework/System.IO.FileSystem.wasm +0 -0
  66. package/_framework/System.IO.IsolatedStorage.wasm +0 -0
  67. package/_framework/System.IO.MemoryMappedFiles.wasm +0 -0
  68. package/_framework/System.IO.Pipelines.wasm +0 -0
  69. package/_framework/System.IO.Pipes.AccessControl.wasm +0 -0
  70. package/_framework/System.IO.Pipes.wasm +0 -0
  71. package/_framework/System.IO.UnmanagedMemoryStream.wasm +0 -0
  72. package/_framework/System.IO.wasm +0 -0
  73. package/_framework/System.Linq.AsyncEnumerable.wasm +0 -0
  74. package/_framework/System.Linq.Expressions.wasm +0 -0
  75. package/_framework/System.Linq.Parallel.wasm +0 -0
  76. package/_framework/System.Linq.Queryable.wasm +0 -0
  77. package/_framework/System.Linq.wasm +0 -0
  78. package/_framework/System.Memory.wasm +0 -0
  79. package/_framework/System.Net.Http.Json.wasm +0 -0
  80. package/_framework/System.Net.Http.wasm +0 -0
  81. package/_framework/System.Net.HttpListener.wasm +0 -0
  82. package/_framework/System.Net.Mail.wasm +0 -0
  83. package/_framework/System.Net.NameResolution.wasm +0 -0
  84. package/_framework/System.Net.NetworkInformation.wasm +0 -0
  85. package/_framework/System.Net.Ping.wasm +0 -0
  86. package/_framework/System.Net.Primitives.wasm +0 -0
  87. package/_framework/System.Net.Quic.wasm +0 -0
  88. package/_framework/System.Net.Requests.wasm +0 -0
  89. package/_framework/System.Net.Security.wasm +0 -0
  90. package/_framework/System.Net.ServerSentEvents.wasm +0 -0
  91. package/_framework/System.Net.ServicePoint.wasm +0 -0
  92. package/_framework/System.Net.Sockets.wasm +0 -0
  93. package/_framework/System.Net.WebClient.wasm +0 -0
  94. package/_framework/System.Net.WebHeaderCollection.wasm +0 -0
  95. package/_framework/System.Net.WebProxy.wasm +0 -0
  96. package/_framework/System.Net.WebSockets.Client.wasm +0 -0
  97. package/_framework/System.Net.WebSockets.wasm +0 -0
  98. package/_framework/System.Net.wasm +0 -0
  99. package/_framework/System.Numerics.Vectors.wasm +0 -0
  100. package/_framework/System.Numerics.wasm +0 -0
  101. package/_framework/System.ObjectModel.wasm +0 -0
  102. package/_framework/System.Private.CoreLib.wasm +0 -0
  103. package/_framework/System.Private.DataContractSerialization.wasm +0 -0
  104. package/_framework/System.Private.Uri.wasm +0 -0
  105. package/_framework/System.Private.Xml.Linq.wasm +0 -0
  106. package/_framework/System.Private.Xml.wasm +0 -0
  107. package/_framework/System.Reflection.DispatchProxy.wasm +0 -0
  108. package/_framework/System.Reflection.Emit.ILGeneration.wasm +0 -0
  109. package/_framework/System.Reflection.Emit.Lightweight.wasm +0 -0
  110. package/_framework/System.Reflection.Emit.wasm +0 -0
  111. package/_framework/System.Reflection.Extensions.wasm +0 -0
  112. package/_framework/System.Reflection.Metadata.wasm +0 -0
  113. package/_framework/System.Reflection.Primitives.wasm +0 -0
  114. package/_framework/System.Reflection.TypeExtensions.wasm +0 -0
  115. package/_framework/System.Reflection.wasm +0 -0
  116. package/_framework/System.Resources.Reader.wasm +0 -0
  117. package/_framework/System.Resources.ResourceManager.wasm +0 -0
  118. package/_framework/System.Resources.Writer.wasm +0 -0
  119. package/_framework/System.Runtime.CompilerServices.Unsafe.wasm +0 -0
  120. package/_framework/System.Runtime.CompilerServices.VisualC.wasm +0 -0
  121. package/_framework/System.Runtime.Extensions.wasm +0 -0
  122. package/_framework/System.Runtime.Handles.wasm +0 -0
  123. package/_framework/System.Runtime.InteropServices.JavaScript.wasm +0 -0
  124. package/_framework/System.Runtime.InteropServices.RuntimeInformation.wasm +0 -0
  125. package/_framework/System.Runtime.InteropServices.wasm +0 -0
  126. package/_framework/System.Runtime.Intrinsics.wasm +0 -0
  127. package/_framework/System.Runtime.Loader.wasm +0 -0
  128. package/_framework/System.Runtime.Numerics.wasm +0 -0
  129. package/_framework/System.Runtime.Serialization.Formatters.wasm +0 -0
  130. package/_framework/System.Runtime.Serialization.Json.wasm +0 -0
  131. package/_framework/System.Runtime.Serialization.Primitives.wasm +0 -0
  132. package/_framework/System.Runtime.Serialization.Xml.wasm +0 -0
  133. package/_framework/System.Runtime.Serialization.wasm +0 -0
  134. package/_framework/System.Runtime.wasm +0 -0
  135. package/_framework/System.Security.AccessControl.wasm +0 -0
  136. package/_framework/System.Security.Claims.wasm +0 -0
  137. package/_framework/System.Security.Cryptography.Algorithms.wasm +0 -0
  138. package/_framework/System.Security.Cryptography.Cng.wasm +0 -0
  139. package/_framework/System.Security.Cryptography.Csp.wasm +0 -0
  140. package/_framework/System.Security.Cryptography.Encoding.wasm +0 -0
  141. package/_framework/System.Security.Cryptography.OpenSsl.wasm +0 -0
  142. package/_framework/System.Security.Cryptography.Primitives.wasm +0 -0
  143. package/_framework/System.Security.Cryptography.X509Certificates.wasm +0 -0
  144. package/_framework/System.Security.Cryptography.wasm +0 -0
  145. package/_framework/System.Security.Principal.Windows.wasm +0 -0
  146. package/_framework/System.Security.Principal.wasm +0 -0
  147. package/_framework/System.Security.SecureString.wasm +0 -0
  148. package/_framework/System.Security.wasm +0 -0
  149. package/_framework/System.ServiceModel.Web.wasm +0 -0
  150. package/_framework/System.ServiceProcess.wasm +0 -0
  151. package/_framework/System.Text.Encoding.CodePages.wasm +0 -0
  152. package/_framework/System.Text.Encoding.Extensions.wasm +0 -0
  153. package/_framework/System.Text.Encoding.wasm +0 -0
  154. package/_framework/System.Text.Encodings.Web.wasm +0 -0
  155. package/_framework/System.Text.Json.wasm +0 -0
  156. package/_framework/System.Text.RegularExpressions.wasm +0 -0
  157. package/_framework/System.Threading.AccessControl.wasm +0 -0
  158. package/_framework/System.Threading.Channels.wasm +0 -0
  159. package/_framework/System.Threading.Overlapped.wasm +0 -0
  160. package/_framework/System.Threading.Tasks.Dataflow.wasm +0 -0
  161. package/_framework/System.Threading.Tasks.Extensions.wasm +0 -0
  162. package/_framework/System.Threading.Tasks.Parallel.wasm +0 -0
  163. package/_framework/System.Threading.Tasks.wasm +0 -0
  164. package/_framework/System.Threading.Thread.wasm +0 -0
  165. package/_framework/System.Threading.ThreadPool.wasm +0 -0
  166. package/_framework/System.Threading.Timer.wasm +0 -0
  167. package/_framework/System.Threading.wasm +0 -0
  168. package/_framework/System.Transactions.Local.wasm +0 -0
  169. package/_framework/System.Transactions.wasm +0 -0
  170. package/_framework/System.ValueTuple.wasm +0 -0
  171. package/_framework/System.Web.HttpUtility.wasm +0 -0
  172. package/_framework/System.Web.wasm +0 -0
  173. package/_framework/System.Windows.wasm +0 -0
  174. package/_framework/System.Xml.Linq.wasm +0 -0
  175. package/_framework/System.Xml.ReaderWriter.wasm +0 -0
  176. package/_framework/System.Xml.Serialization.wasm +0 -0
  177. package/_framework/System.Xml.XDocument.wasm +0 -0
  178. package/_framework/System.Xml.XPath.XDocument.wasm +0 -0
  179. package/_framework/System.Xml.XPath.wasm +0 -0
  180. package/_framework/System.Xml.XmlDocument.wasm +0 -0
  181. package/_framework/System.Xml.XmlSerializer.wasm +0 -0
  182. package/_framework/System.Xml.wasm +0 -0
  183. package/_framework/System.wasm +0 -0
  184. package/_framework/WasmPlayer.wasm +0 -0
  185. package/_framework/WindowsBase.wasm +0 -0
  186. package/_framework/dotnet.boot.js +1003 -0
  187. package/_framework/dotnet.js +4 -0
  188. package/_framework/dotnet.native.js +6687 -0
  189. package/_framework/dotnet.native.wasm +0 -0
  190. package/_framework/dotnet.runtime.js +4 -0
  191. package/_framework/icudt_CJK.dat +0 -0
  192. package/_framework/icudt_EFIGS.dat +0 -0
  193. package/_framework/icudt_no_CJK.dat +0 -0
  194. package/_framework/mscorlib.wasm +0 -0
  195. package/_framework/netstandard.wasm +0 -0
  196. package/chrome.css +22 -0
  197. package/favicon.svg +1 -0
  198. package/grid.js +446 -0
  199. package/index.html +214 -0
  200. package/lib/images/ui-bg_flat_0_aaaaaa_40x100.png +0 -0
  201. package/lib/images/ui-bg_flat_55_fbec88_40x100.png +0 -0
  202. package/lib/images/ui-bg_glass_75_d0e5f5_1x400.png +0 -0
  203. package/lib/images/ui-bg_glass_85_dfeffc_1x400.png +0 -0
  204. package/lib/images/ui-bg_glass_95_fef1ec_1x400.png +0 -0
  205. package/lib/images/ui-bg_gloss-wave_55_5c9ccc_500x100.png +0 -0
  206. package/lib/images/ui-bg_inset-hard_100_f5f8f9_1x100.png +0 -0
  207. package/lib/images/ui-bg_inset-hard_100_fcfdfd_1x100.png +0 -0
  208. package/lib/images/ui-icons_217bc0_256x240.png +0 -0
  209. package/lib/images/ui-icons_2e83ff_256x240.png +0 -0
  210. package/lib/images/ui-icons_469bdd_256x240.png +0 -0
  211. package/lib/images/ui-icons_6da8d5_256x240.png +0 -0
  212. package/lib/images/ui-icons_cd0a0a_256x240.png +0 -0
  213. package/lib/images/ui-icons_d8e7f3_256x240.png +0 -0
  214. package/lib/images/ui-icons_f9bd01_256x240.png +0 -0
  215. package/lib/jquery-2.1.1.min.js +4 -0
  216. package/lib/jquery-ui.min.css +7 -0
  217. package/lib/jquery-ui.min.js +13 -0
  218. package/lib/jquery.multi-open-accordion-1.5.3.js +261 -0
  219. package/lib/paper.js +12848 -0
  220. package/logo.svg +1 -0
  221. package/package.json +13 -0
  222. package/player.js +258 -0
  223. package/playercore.css +293 -0
  224. package/playercore.htm +206 -0
  225. package/playercore.js +2639 -0
  226. package/quest-config.js +13 -0
  227. package/wasm-player.js +2024 -0
package/wasm-player.js ADDED
@@ -0,0 +1,2024 @@
1
+ // WasmPlayer JS bootstrap — replaces playerweb.js for the WASM-hosted player.
2
+ // Defines the WebPlayer object surface that playercore.js / player.js call into,
3
+ // then initialises the .NET WASM runtime and wires up [JSImport] callbacks.
4
+
5
+ // Printed as soon as this script runs (i.e. as the start screen appears) —
6
+ // window.QuestVivaVersion comes from the repo-root VERSION file, spliced in
7
+ // at build time by scripts/inject-version.mjs, so this doesn't need to wait
8
+ // for the WASM runtime to boot (which only happens once a game loads).
9
+ console.log(
10
+ '%cQuest Viva %c' + (window.QuestVivaVersion || 'dev') + '\n%chttps://questviva.com',
11
+ 'font-weight:700;font-size:14px;color:#0ea5e9',
12
+ 'font-weight:400;color:#64748b',
13
+ 'color:#64748b'
14
+ );
15
+
16
+ // Captured synchronously while this classic script is still `document.
17
+ // currentScript` (true only during its own initial top-level execution) —
18
+ // used below to build an absolute URL for the dynamic `import()` of
19
+ // dotnet.js. A relative specifier there (`import('./_framework/dotnet.js')`)
20
+ // works when this script is same-origin, but when it's loaded cross-origin
21
+ // (the single-file CDN-linked export, see scripts/export-embedded.mjs)
22
+ // Chromium has no usable base URL for a relative dynamic import from a
23
+ // classic (non-module) cross-origin script and fails the whole import with
24
+ // "The base URL is about:blank because import() is called from a
25
+ // CORS-cross-origin script" — confirmed empirically, `crossorigin="anonymous"`
26
+ // on the <script> tag does not change this. Passing an absolute URL sidesteps
27
+ // relative resolution entirely, so it works either way.
28
+ const wasmPlayerScriptUrl = document.currentScript?.src;
29
+
30
+ var _audio = null;
31
+
32
+ const pendingResources = new Map();
33
+ let editorChannel = null;
34
+ let resourceRoot = null;
35
+
36
+ // ── Walkthrough recording/playback status banner ────────────────────────────
37
+ // Drives the #qv-recording banner (element ids kept as-is from the original
38
+ // record-only implementation — they're internal, not user-facing) through
39
+ // three mutually exclusive modes, all only ever entered via the 'game'
40
+ // message's recordWalkthrough/runWalkthrough fields (AppShell's
41
+ // ListEditor.svelte Play/Record buttons → editor-store.ts's
42
+ // playWalkthrough/recordWalkthrough/previewInWasmPlayer) — never set for a
43
+ // normal Play/source=local session, which never sends either field:
44
+ // 'replay' — replaying a walkthrough's existing steps before recording
45
+ // continues (see beginRecordWithReplay). Banner button cancels.
46
+ // 'record' — capturing new commands into recordedSteps (see recordStep).
47
+ // Banner button stops and relays them to the editor tab.
48
+ // 'play' — a standalone Play (see runWalkthroughStandalone), no
49
+ // recording follows. Banner button cancels.
50
+ // recordedSteps is plain module state, not tied to the DOM, so it survives a
51
+ // mid-recording restart (see swapInPlayerUi's doc comment).
52
+ let walkthroughStatusMode = null; // null | 'replay' | 'record' | 'play'
53
+ let recordWalkthroughName = null;
54
+ let recordedSteps = [];
55
+
56
+ function recordStep(step) {
57
+ if (walkthroughStatusMode !== 'record') return;
58
+ recordedSteps.push(step);
59
+ updateWalkthroughStatusUi();
60
+ }
61
+
62
+ function updateWalkthroughStatusUi() {
63
+ const el = document.getElementById('qv-recording');
64
+ if (!el) return;
65
+ el.classList.toggle('hidden', !walkthroughStatusMode);
66
+ const status = document.getElementById('qv-recording-status');
67
+ const stopBtn = document.getElementById('qv-recording-stop');
68
+ if (walkthroughStatusMode === 'replay') {
69
+ if (status) status.textContent = 'Replaying existing steps…';
70
+ stopBtn?.setAttribute('aria-label', 'Cancel replay');
71
+ } else if (walkthroughStatusMode === 'play') {
72
+ if (status) status.textContent = 'Playing…';
73
+ stopBtn?.setAttribute('aria-label', 'Cancel');
74
+ } else if (walkthroughStatusMode === 'record') {
75
+ if (status) {
76
+ const n = recordedSteps.length;
77
+ status.textContent = `Recording — ${n} step${n === 1 ? '' : 's'}`;
78
+ }
79
+ stopBtn?.setAttribute('aria-label', 'Stop recording');
80
+ }
81
+ }
82
+
83
+ function beginRecording(name) {
84
+ walkthroughStatusMode = 'record';
85
+ recordWalkthroughName = name;
86
+ recordedSteps = [];
87
+ updateWalkthroughStatusUi();
88
+ }
89
+
90
+ // Relays the captured steps back to the editor tab over the same channel used
91
+ // to hand off the game itself — see editor-store.ts's 'walkthrough-recorded'
92
+ // handler, which appends them onto the walkthrough element via
93
+ // WasmEditorBridge.RecordWalkthroughSteps. Stopping only ends the *recording*
94
+ // — the preview session itself carries on exactly as an ordinary Preview
95
+ // would (no Save button, Debugger still available, etc.).
96
+ function stopRecording() {
97
+ if (walkthroughStatusMode !== 'record' || !editorChannel) return;
98
+ editorChannel.postMessage({ type: 'walkthrough-recorded', name: recordWalkthroughName, steps: recordedSteps });
99
+ walkthroughStatusMode = null;
100
+ recordWalkthroughName = null;
101
+ recordedSteps = [];
102
+ updateWalkthroughStatusUi();
103
+ }
104
+
105
+ // Runs a walkthrough's existing steps (if any) before switching into live
106
+ // recording, so re-recording into a walkthrough that already has steps
107
+ // starts from the right game state instead of a blank slate. Must run after
108
+ // Bridge.Begin() — WalkthroughRunner drives the game via SendCommand, which
109
+ // needs an already-started game (current room, game.pov, etc. all set).
110
+ // Proceeds to recording regardless of how the replay ends (finished, failed,
111
+ // or cancelled via the banner's button — Bridge.RunWalkthrough never throws,
112
+ // see its own try/catch) since aborting instead would leave the author with
113
+ // no way to add new steps after a bad replay.
114
+ async function beginRecordWithReplay(name) {
115
+ let stepCount = 0;
116
+ try {
117
+ stepCount = JSON.parse(Bridge.GetWalkthroughStepsJson(name)).length;
118
+ } catch { /* treat as no existing steps */ }
119
+
120
+ if (stepCount > 0) {
121
+ walkthroughStatusMode = 'replay';
122
+ updateWalkthroughStatusUi();
123
+ const error = await Bridge.RunWalkthrough(name);
124
+ if (error) console.error('[Quest] Walkthrough replay before recording failed:', error);
125
+ }
126
+
127
+ beginRecording(name);
128
+ }
129
+
130
+ // Standalone playback (the ListEditor.svelte "Play" button) — no recording
131
+ // follows. Must run after Bridge.Begin(), same reasoning as beginRecordWithReplay.
132
+ async function runWalkthroughStandalone(name) {
133
+ walkthroughStatusMode = 'play';
134
+ updateWalkthroughStatusUi();
135
+ const error = await Bridge.RunWalkthrough(name);
136
+ if (error) console.error('[Quest] Walkthrough playback failed:', error);
137
+ walkthroughStatusMode = null;
138
+ updateWalkthroughStatusUi();
139
+ }
140
+
141
+ function wireRecordingStopButton() {
142
+ document.getElementById('qv-recording-stop')?.addEventListener('click', () => {
143
+ if (walkthroughStatusMode === 'record') stopRecording();
144
+ else if (walkthroughStatusMode === 'replay' || walkthroughStatusMode === 'play') Bridge.CancelWalkthrough();
145
+ });
146
+ }
147
+
148
+ // Best-effort — BroadcastChannel.postMessage during pagehide isn't guaranteed
149
+ // to be delivered, but costs nothing to attempt, so closing the tab mid-
150
+ // recording (instead of clicking Stop) doesn't silently lose the steps.
151
+ window.addEventListener('pagehide', () => {
152
+ if (walkthroughStatusMode === 'record' && editorChannel && recordedSteps.length > 0) {
153
+ editorChannel.postMessage({ type: 'walkthrough-recorded', name: recordWalkthroughName, steps: recordedSteps });
154
+ }
155
+ });
156
+
157
+ // The *original* game bytes/filename for the current session — always the
158
+ // primary game file, never a save. Saves are loaded as an overlay on top of
159
+ // these via Bridge.InitialiseWithSave, so resource lookups (images/sounds
160
+ // bundled in a .quest package) keep working. Set once per boot in startGame()
161
+ // and never reassigned by a slot/file load.
162
+ let originalGameBytes = null;
163
+ let originalGameFilename = null;
164
+ // The pristine player chrome markup (playercore.htm), fetched once at boot
165
+ // and reused verbatim by restartGame() so a mid-session restart gets exactly
166
+ // the same clean slate as the initial boot, instead of the previous game's
167
+ // live DOM (see swapInPlayerUi()).
168
+ let originalPlayerHtml = null;
169
+
170
+ function computeGameId(filename) {
171
+ return filename.split('/').pop();
172
+ }
173
+
174
+ // Nothing guarantees a 'resource-response' ever arrives: a raw picked File in
175
+ // the browser build's Play-tab flow has no responder for anything beyond the
176
+ // game file itself (see the source=local boot branch's comment), and even a
177
+ // real responder (the editor tab, Electron's ElectronFileAdapter) can vanish
178
+ // mid-request if that tab/window closes. Either way, without this timeout the
179
+ // promise sits pending forever, hanging whatever engine code awaited it — so
180
+ // fall back to the bare filename (same as the no-editorChannel case above),
181
+ // letting the browser attempt — and if unresolvable, cleanly fail — a plain
182
+ // relative fetch instead of hanging.
183
+ const RESOURCE_REQUEST_TIMEOUT_MS = 5000;
184
+
185
+ function getResourceUrl(name) {
186
+ if (resourceRoot) return Promise.resolve(resourceRoot + name);
187
+ if (!editorChannel) return Promise.resolve(name);
188
+ return new Promise(resolve => {
189
+ const id = crypto.randomUUID();
190
+ const timeoutId = window.setTimeout(() => {
191
+ pendingResources.delete(id);
192
+ // The subsequent fetch of the bare filename will very likely also
193
+ // fail (and the browser will log that on its own) — but that
194
+ // failure alone won't explain itself, so name the actual cause
195
+ // here: nobody answered the resource-request handoff in time.
196
+ console.error(`[Quest] Timed out waiting for resource "${name}" — the tab/window that should have supplied it never answered. Falling back to a plain relative fetch, which will likely fail unless the game is self-contained.`);
197
+ resolve(name);
198
+ }, RESOURCE_REQUEST_TIMEOUT_MS);
199
+ pendingResources.set(id, dataUrl => {
200
+ window.clearTimeout(timeoutId);
201
+ resolve(dataUrl);
202
+ });
203
+ editorChannel.postMessage({ type: 'resource-request', name, id });
204
+ });
205
+ }
206
+
207
+ function ui_init() { }
208
+
209
+ function sendEndWait() {
210
+ window.setTimeout(async function () {
211
+ await WebPlayer.uiEndWait();
212
+ }, 100);
213
+ waitEnded();
214
+ }
215
+
216
+ function afterSendCommand() { }
217
+
218
+ function playSound(url, synchronous, looped) {
219
+ stopSound();
220
+ _audio = new Audio(url);
221
+ if (looped) _audio.loop = true;
222
+ if (synchronous) {
223
+ var showCmdDiv = isElementVisible("#txtCommandDiv");
224
+ _waitingForSoundToFinish = true;
225
+ $("#txtCommandDiv").hide();
226
+ _audio.addEventListener('ended', function () { finishSync(showCmdDiv); });
227
+ }
228
+ _audio.play();
229
+ }
230
+
231
+ function stopSound() {
232
+ if (_audio !== null) {
233
+ _audio.pause();
234
+ _audio.src = '';
235
+ _audio = null;
236
+ }
237
+ }
238
+
239
+ function finishSync(showCommandDiv) {
240
+ _waitingForSoundToFinish = false;
241
+ window.setTimeout(async function () {
242
+ if (showCommandDiv) $("#txtCommandDiv").show();
243
+ await WebPlayer.uiEndWait();
244
+ }, 100);
245
+ }
246
+
247
+ // Chrome (and others) block unmuted audio until the page has "user
248
+ // activation". A click through to this page (e.g. a target=_blank Play
249
+ // button) does transfer that activation across the navigation, but it
250
+ // doesn't reliably survive WasmPlayer's boot sequence (fetching the game,
251
+ // booting the AOT WASM runtime) for a slow-enough load — by the time the
252
+ // game's start logic tries to play a sound, the activation can already be
253
+ // gone, and the browser silently rejects it. Only relevant for games that
254
+ // might play a sound before the player has had any chance to interact with
255
+ // the page themselves (typing a command is itself a fresh activation).
256
+ function activationLikelyGranted() {
257
+ // Electron's own default autoplay policy is already unrestricted (unlike
258
+ // stock Chrome's), and ipc/player.ts's player windows set it explicitly —
259
+ // true regardless of how the window was created (in-place nav, popup, or
260
+ // a main-process-created window), so the gate below would only ever add
261
+ // friction there, never actually prevent a blocked sound.
262
+ if (navigator.userAgent.includes('Electron/')) return true;
263
+ return !('userActivation' in navigator) || navigator.userActivation.hasBeenActive;
264
+ }
265
+
266
+ // Attached to the api/Game/{id} fetch below as analytics metadata (see
267
+ // ClientInfo on textadventures.co.uk's ApiController) — mirrors AppShell's
268
+ // home-catalog.ts clientInfoParams(), which does the same for the Catalog and
269
+ // GameDetails calls. This player window runs untrusted game content and
270
+ // deliberately has no preload bridge (see ipc/player.ts), so unlike
271
+ // home-catalog.ts it can't read window.electronApp.platform; Electron and its
272
+ // host OS are instead sniffed from the UA, the same signal
273
+ // activationLikelyGranted() above already relies on.
274
+ function clientInfoParams() {
275
+ const params = new URLSearchParams();
276
+ const isElectron = navigator.userAgent.includes('Electron/');
277
+ params.set('source', isElectron ? 'electron' : 'web');
278
+ if (window.QuestVivaVersion) params.set('version', window.QuestVivaVersion);
279
+ if (isElectron) {
280
+ const ua = navigator.userAgent;
281
+ const platform = ua.includes('Macintosh') ? 'Mac'
282
+ : ua.includes('Windows') ? 'Windows'
283
+ : (ua.includes('Linux') || ua.includes('X11')) ? 'Linux'
284
+ : null;
285
+ if (platform) params.set('platform', platform);
286
+ }
287
+ return params;
288
+ }
289
+
290
+ // Shows a "click to begin" prompt in the still-visible start screen and
291
+ // waits for it, so the resulting click is a fresh, same-page activation —
292
+ // but only when it's actually needed (see activationLikelyGranted) and only
293
+ // for games that could plausibly play a sound before the player interacts
294
+ // (see Bridge.GameLikelyPlaysSound). Call before Bridge.Begin() and before
295
+ // the start screen overlay is removed.
296
+ async function maybeGateOnActivation(gameBytes) {
297
+ if (activationLikelyGranted()) return;
298
+
299
+ let usesSound = true;
300
+ try { usesSound = Bridge.GameLikelyPlaysSound(gameBytes); } catch { /* don't block boot on detection failure */ }
301
+ if (!usesSound) return;
302
+
303
+ const pickers = document.getElementById('qv-pickers');
304
+ const msg = document.getElementById('qv-loading-msg');
305
+ const gate = document.getElementById('qv-clicktobegin');
306
+ if (pickers) pickers.style.display = 'none';
307
+ if (msg) msg.style.display = 'none';
308
+ if (gate) gate.style.display = 'flex';
309
+
310
+ await new Promise(resolve => {
311
+ document.getElementById('qv-clicktobegin-btn')?.addEventListener('click', resolve, { once: true });
312
+ });
313
+
314
+ if (gate) gate.style.display = 'none';
315
+ }
316
+
317
+ // The WebPlayer object — same surface API as playerweb.js so that playercore.js
318
+ // and player.js can call into it without modification.
319
+ window.WebPlayer = {
320
+ gameId: null,
321
+
322
+ initUI() { initPlayerUI(); },
323
+
324
+ setCanDebug(value) {
325
+ const cmdDebug = document.getElementById("cmdDebug");
326
+ if (cmdDebug) cmdDebug.style.display = value ? "initial" : "none";
327
+ },
328
+
329
+ setCanSave(value) {
330
+ const cmdSave = document.getElementById("cmdSave");
331
+ if (cmdSave) cmdSave.style.display = value ? "initial" : "none";
332
+ canSave = value;
333
+ if (!value) window.saveGame = () => addText("Disabled");
334
+ },
335
+
336
+ setAnimateScroll(value) { _animateScroll = value; },
337
+
338
+ runJs(scripts) {
339
+ const globalEval = window.eval;
340
+ for (const script of scripts) {
341
+ try { globalEval(script); } catch (e) { console.error(e); }
342
+ }
343
+ },
344
+
345
+ async sendCommand(command, tickCount, metadata) {
346
+ const metadataJson = metadata ? JSON.stringify(metadata) : null;
347
+ await Bridge.SendCommand(command, tickCount, metadataJson);
348
+ canSendCommand = true;
349
+ recordStep(command);
350
+ refreshDebuggerAfterTurn();
351
+ },
352
+
353
+ async uiChoice(choice) { await Bridge.SetMenuResponse(choice); recordStep(`menu:${choice}`); },
354
+ async uiChoiceCancel() { await Bridge.SetMenuResponse(null); },
355
+ async uiTick(tickCount) { await Bridge.Tick(tickCount); },
356
+ async uiEndWait() { await Bridge.FinishWait(); },
357
+ async uiEndPause() { await Bridge.FinishPause(); },
358
+ async uiSetQuestionResponse(response) { await Bridge.SetQuestionResponse(response); recordStep(`answer:${response ? 'yes' : 'no'}`); },
359
+
360
+ async uiSendEvent(eventName, param) {
361
+ await Bridge.SendEvent(eventName, param);
362
+ canSendCommand = true;
363
+ recordStep(`event:${eventName};${param ?? ''}`);
364
+ refreshDebuggerAfterTurn();
365
+ },
366
+
367
+ async uiSaveGame(html) {
368
+ await Bridge.PrepareSaveGame(html);
369
+ return Bridge.GetSaveGameBytes();
370
+ },
371
+
372
+ };
373
+
374
+ // Exported bridge reference — set once WASM is loaded.
375
+ var Bridge;
376
+
377
+ function addPaperScript() {
378
+ const canvas = document.getElementById('gridCanvas');
379
+ const gridPanel = document.getElementById('gridPanel');
380
+ if (canvas instanceof HTMLCanvasElement && gridPanel) {
381
+ gridPanel.appendChild(canvas);
382
+ canvas.style.display = '';
383
+ if (window.paper && paper.view) {
384
+ paper.view.viewSize = new paper.Size(canvas.clientWidth, canvas.clientHeight);
385
+ }
386
+ }
387
+ }
388
+
389
+ async function setupPaperJs() {
390
+ if (!window.paper) return;
391
+ const canvas = document.createElement('canvas');
392
+ canvas.id = 'gridCanvas';
393
+ canvas.width = 700;
394
+ canvas.height = 300;
395
+ canvas.style.display = 'none';
396
+ document.body.appendChild(canvas);
397
+ paper.setup(canvas);
398
+ const code = await fetch('grid.js').then(r => r.text());
399
+ paper.PaperScript.evaluate(code, paper);
400
+ }
401
+
402
+ // Replaces document.body with a fresh copy of the player chrome, preserving
403
+ // #qv-start/#qv-saves/#questVivaDebugger/#qv-recording (the static markup's overlays, which
404
+ // live outside the swapped-in playerHtml and would otherwise be destroyed by
405
+ // the innerHTML assignment). Used both for the initial boot and for a
406
+ // mid-session restart ("Start from the beginning" / Load) — a restart must
407
+ // get a genuinely new DOM, not just a cleared output pane, because games
408
+ // commonly use their external <javascript> resources to inject their own
409
+ // elements elsewhere in the chrome (e.g. a custom sidebar pane). Those run
410
+ // again on every restart (RegisterExternalScripts fires on every Initialise
411
+ // call), so anything short of a full DOM reset here leaves the previous run's
412
+ // injected elements in place for the new run to duplicate.
413
+ function swapInPlayerUi() {
414
+ const startScreenEl = document.getElementById('qv-start');
415
+ const savesDialogEl = document.getElementById('qv-saves');
416
+ const debuggerDialogEl = document.getElementById('questVivaDebugger');
417
+ const restartingEl = document.getElementById('qv-restarting');
418
+ const recordingEl = document.getElementById('qv-recording');
419
+ startScreenEl?.remove();
420
+ savesDialogEl?.remove();
421
+ debuggerDialogEl?.remove();
422
+ restartingEl?.remove();
423
+ recordingEl?.remove();
424
+
425
+ document.body.innerHTML = originalPlayerHtml;
426
+
427
+ if (startScreenEl) document.body.appendChild(startScreenEl);
428
+ if (savesDialogEl) document.body.appendChild(savesDialogEl);
429
+ if (debuggerDialogEl) document.body.appendChild(debuggerDialogEl);
430
+ if (restartingEl) document.body.appendChild(restartingEl);
431
+ if (recordingEl) document.body.appendChild(recordingEl);
432
+ // This is a genuinely fresh chrome (see above) — addExternalScript's
433
+ // dedupe-by-URL (player.js) must not carry over, or the game's external
434
+ // scripts silently no-op against it on the very next Initialise() call
435
+ // and never re-inject whatever they set up (e.g. that sidebar pane).
436
+ clearLoadedExternalScripts();
437
+ return startScreenEl;
438
+ }
439
+
440
+ // Remembered across a mid-session restart (restartGame doesn't get isPreview
441
+ // as a parameter — it just re-initialises on top of the same boot session),
442
+ // so the Debug button's visibility stays correct after "Start from the
443
+ // beginning"/Load in an editor-preview session.
444
+ let currentIsPreview = false;
445
+
446
+ async function initWasmPlayer(gameBytes, filename, bc = null, saveBytes = null, isPreview = false, recordWalkthrough = null, runWalkthrough = null) {
447
+ currentIsPreview = isPreview;
448
+ const dotnetJsUrl = wasmPlayerScriptUrl
449
+ ? new URL('_framework/dotnet.js', wasmPlayerScriptUrl).href
450
+ : './_framework/dotnet.js';
451
+ const [htmResponse, { dotnet }] = await Promise.all([
452
+ fetch('playercore.htm'),
453
+ import(dotnetJsUrl),
454
+ ]);
455
+ originalPlayerHtml = await htmResponse.text();
456
+
457
+ const runtime = await dotnet.create();
458
+ const { setModuleImports, getAssemblyExports, getConfig } = runtime;
459
+
460
+ setModuleImports("wasm-player", {
461
+ addTextAndScroll: (html) => addTextAndScroll(html),
462
+ createNewDiv: (alignment) => createNewDiv(alignment),
463
+ bindMenu: (linkId, verbs, text, elementId) => bindMenu(linkId, verbs, text, elementId),
464
+ showMenu: (caption, optionsJson, allowCancel) => showMenu(caption, JSON.parse(optionsJson), allowCancel),
465
+ showQuestion: (caption) => showQuestion(caption),
466
+ beginWait: () => beginWait(),
467
+ setTurnPending: (pending) => setTurnPending(pending),
468
+ beginPause: (ms) => beginPause(ms),
469
+ updateLocation: (loc) => updateLocation(loc),
470
+ setGameName: (name) => setGameName(name),
471
+ clearScreen: () => clearScreen(),
472
+ panesVisible: (visible) => panesVisible(visible),
473
+ updateStatus: (text) => updateStatus(text),
474
+ setBackground: (colour) => setBackground(colour),
475
+ setForeground: (colour) => setForeground(colour),
476
+ updateList: (listName, itemsJson) => updateList(listName, JSON.parse(itemsJson)),
477
+ updateCompass: (data) => updateCompass(data),
478
+ updateObjectLinks: (verbsJson) => updateObjectLinks(JSON.parse(verbsJson)),
479
+ gameFinished: () => gameFinished(),
480
+ requestNextTimerTick: (seconds) => requestNextTimerTick(seconds),
481
+ uiShow: (element) => uiShow(element),
482
+ uiHide: (element) => uiHide(element),
483
+ addExternalScript: (url) => addExternalScript(url),
484
+ addExternalStylesheet: (url) => addExternalStylesheet(url),
485
+ playSound: (url, synchronous, looped) => playSound(url, synchronous, looped),
486
+ stopSound: () => stopSound(),
487
+ runScript: (call) => {
488
+ const globalEval = window.eval;
489
+ try { globalEval(call); } catch (e) { console.error(e); }
490
+ },
491
+ jsYield: () => new Promise(resolve => setTimeout(resolve, 0)),
492
+ setCompassDirections: (dirsJson) => setCompassDirections(JSON.parse(dirsJson)),
493
+ setInterfaceString: (name, text) => setInterfaceString(name, text),
494
+ setPanelContents: (html) => setPanelContents(html),
495
+ consoleError: (msg) => console.error('[Quest]', msg),
496
+ consoleLog: (msg) => console.log('[Quest]', msg),
497
+ getResourceUrl: (name) => getResourceUrl(name),
498
+ });
499
+
500
+ await runtime.runMain();
501
+
502
+ const config = getConfig();
503
+ const exports = await getAssemblyExports(config.mainAssemblyName);
504
+ Bridge = exports.QuestViva.WasmPlayer.WasmPlayerBridge;
505
+
506
+ if (bc) {
507
+ editorChannel = bc;
508
+ bc.onmessage = ({ data }) => {
509
+ if (data.type === 'resource-response') {
510
+ pendingResources.get(data.id)?.(data.dataUrl);
511
+ pendingResources.delete(data.id);
512
+ }
513
+ };
514
+ }
515
+
516
+ // Swap in the game UI *before* Initialise/Begin run, not after. Initialise
517
+ // registers the game's external <javascript> resources (RegisterExternalScripts),
518
+ // and games commonly use those to manipulate the game UI's own DOM (e.g.
519
+ // inserting a custom pane next to the built-in Inventory/Status panes). If
520
+ // the swap happens later, those scripts execute while the start screen is
521
+ // still showing, find none of the elements they're looking for, and
522
+ // silently no-op — a real game, "A Stranger Unregarded", does exactly this
523
+ // with a custom Inventory2 pane that never appeared because of this
524
+ // ordering.
525
+ //
526
+ // #qv-start is a fixed, full-viewport overlay (see chrome.css), so keeping
527
+ // it in the DOM on top of the freshly-swapped-in game UI still covers the
528
+ // screen exactly as before — the loading spinner/error UI's visible
529
+ // behaviour is unchanged.
530
+ const startScreenEl = swapInPlayerUi();
531
+
532
+ const ok = saveBytes
533
+ ? await Bridge.InitialiseWithSave(gameBytes, filename, saveBytes)
534
+ : await Bridge.Initialise(gameBytes, filename);
535
+ if (!ok) {
536
+ console.error('[Quest] Failed to initialise game');
537
+ throw new Error('Failed to initialise game');
538
+ }
539
+
540
+ await maybeGateOnActivation(gameBytes);
541
+
542
+ // Now that startup has actually succeeded, remove the start screen overlay
543
+ // to reveal the game UI underneath.
544
+ startScreenEl?.remove();
545
+
546
+ await setupPaperJs();
547
+
548
+ WebPlayer.onSaveClick = () => openSavesDialog('manage');
549
+ WebPlayer.initUI();
550
+ wireDebuggerButton();
551
+ wireDebuggerRestartButton(isPreview);
552
+ wireRecordingStopButton();
553
+ // Editor-preview sessions (isPreview) don't offer saving at all — by
554
+ // design: a save captures the whole game state, so reloading one while
555
+ // iterating would show stale state that doesn't reflect the developer's
556
+ // latest edits, and could be mistaken for saving the edits themselves.
557
+ // Note this is distinct from bc: a source=local play session also uses a
558
+ // BroadcastChannel (to hand off the picked file's bytes and answer
559
+ // resource requests) but is a real play session and should offer saving.
560
+ WebPlayer.setCanSave(!isPreview);
561
+ // Only ever shown in editor-preview sessions (see the module doc comment
562
+ // above the Debugger section) — never for a normal play session, even
563
+ // though the loaded game itself might have DebugEnabled true.
564
+ WebPlayer.setCanDebug(isPreview && Bridge.IsDebugEnabled());
565
+
566
+ await Bridge.Begin();
567
+
568
+ // Both require the game to have already started (Begin() run) — see their
569
+ // own doc comments — so they run after Bridge.Begin(), unlike the rest of
570
+ // this function's setup above. The extra tick (matching the jsYield
571
+ // JSImport's own setTimeout(...,0) idiom used elsewhere for the same
572
+ // reason) lets the JS/WASM event loop settle after Begin()'s own async
573
+ // engine work before issuing another engine call back-to-back — chaining
574
+ // straight through without it was observed to hang indefinitely.
575
+ if (recordWalkthrough || runWalkthrough) {
576
+ await new Promise(resolve => setTimeout(resolve, 0));
577
+ }
578
+ if (recordWalkthrough) {
579
+ await beginRecordWithReplay(recordWalkthrough);
580
+ } else if (runWalkthrough) {
581
+ await runWalkthroughStandalone(runWalkthrough);
582
+ }
583
+ }
584
+
585
+ // Guards restartGame against overlapping calls — e.g. impatiently clicking
586
+ // Restart/"Start from the beginning" again while a slow restart (loading a
587
+ // large game, low-end device) is still in flight. Two concurrent restarts
588
+ // each call swapInPlayerUi() and Bridge.Initialise(...), racing to rebuild
589
+ // the DOM and reinitialise the shared WasmPlayerBridge static game/UI state
590
+ // out from under each other — the visible symptom was old game output left
591
+ // on screen alongside "This game has finished" (a stale WasmPlayerUi
592
+ // instance's HandleFinished still firing against DOM a second restart had
593
+ // already replaced). withBusyButton (used by callers below) already disables
594
+ // the clicked button for the duration, but this is the actual guard: it's
595
+ // what protects restartGame itself regardless of which control called it.
596
+ let restartInProgress = false;
597
+
598
+ // Reloads a save (or, with saveBytes null, the fresh original game) on top
599
+ // of the already-booted WASM runtime — used for in-game Load and "Start
600
+ // from the beginning". Rebuilds the player chrome from scratch via
601
+ // swapInPlayerUi() (same as the initial boot) rather than just clearing the
602
+ // output pane: RegisterExternalScripts fires again on every Initialise call,
603
+ // and games commonly use their external <javascript> resources to inject
604
+ // their own elements into the chrome (e.g. a custom sidebar pane) — without a
605
+ // full DOM reset here, that injected element from the previous run is still
606
+ // sitting in the (undisturbed) sidebar when the script re-runs and adds
607
+ // another one. A fresh DOM means initUI()/setupPaperJs() are being bound to
608
+ // brand-new elements each time, not the same live ones, so this isn't the
609
+ // double-binding repeat-init the old comment here used to warn about.
610
+ async function restartGame(saveBytes) {
611
+ if (restartInProgress) return;
612
+ restartInProgress = true;
613
+ try {
614
+ await restartGameCore(saveBytes);
615
+ } finally {
616
+ restartInProgress = false;
617
+ }
618
+ }
619
+
620
+ async function restartGameCore(saveBytes) {
621
+ document.getElementById('qv-saves')?.close();
622
+ swapInPlayerUi();
623
+ resetGameOutput();
624
+
625
+ // Bridge.Initialise/Begin re-run the whole game's startup (Bridge.Initialise
626
+ // in particular re-parses the embedded Core library XML from scratch every
627
+ // time — confirmed not cacheable) with no genuine await inside either, so
628
+ // they block the single WASM UI thread for a couple of seconds with
629
+ // nothing else able to paint meanwhile — same reasoning as withBusyButton's
630
+ // nextPaint(). Without yielding a frame *after* unhiding the spinner and
631
+ // *before* that blocking work starts, it would sit queued and invisible
632
+ // for the whole freeze, same as if it was never shown at all.
633
+ const restartingEl = document.getElementById('qv-restarting');
634
+ restartingEl?.classList.remove('hidden');
635
+ await nextPaint();
636
+
637
+ try {
638
+ const ok = saveBytes
639
+ ? await Bridge.InitialiseWithSave(originalGameBytes, originalGameFilename, saveBytes)
640
+ : await Bridge.Initialise(originalGameBytes, originalGameFilename);
641
+ if (!ok) {
642
+ showSavesError('Failed to load that save.');
643
+ return;
644
+ }
645
+
646
+ await maybeGateOnActivation(originalGameBytes);
647
+
648
+ await setupPaperJs();
649
+ WebPlayer.initUI();
650
+ wireDebuggerButton();
651
+ wireDebuggerRestartButton(currentIsPreview);
652
+ // Used to be an unconditional true — harmless while restartGame was only
653
+ // ever reachable from the Saves dialog, which editor-preview sessions
654
+ // never had access to in the first place (Save itself is hidden there).
655
+ // Now that the new Restart button (wireDebuggerRestartButton) makes
656
+ // restartGame reachable *from* a preview session too, hardcoding true
657
+ // here would wrongly re-enable Save after a preview restart.
658
+ WebPlayer.setCanSave(!currentIsPreview);
659
+ WebPlayer.setCanDebug(currentIsPreview && Bridge.IsDebugEnabled());
660
+ await Bridge.Begin();
661
+ } finally {
662
+ restartingEl?.classList.add('hidden');
663
+ }
664
+ }
665
+
666
+ // Wraps initWasmPlayer with the boot-time "Continue / New Game" prompt: if
667
+ // saves already exist for this game, ask before committing to either the
668
+ // fresh game or a chosen save. Used by all boot entry points below.
669
+ async function startGame(bytes, filename, bc = null, gameIdOverride = null, isPreview = false, recordWalkthrough = null, runWalkthrough = null) {
670
+ originalGameBytes = bytes;
671
+ originalGameFilename = filename;
672
+ // gameIdOverride lets callers with a stronger identity than the filename
673
+ // (e.g. the Text Adventures API's stable game id) use it instead.
674
+ const gameId = gameIdOverride || computeGameId(filename);
675
+ WebPlayer.gameId = gameId;
676
+
677
+ let saveBytes = null;
678
+ // Editor-preview sessions (isPreview) are excluded, same rationale as
679
+ // setCanSave's call site below: saving/loading is intentionally not part
680
+ // of the preview experience, so there's nothing to prompt about here
681
+ // either. A source=local play session goes through this same code path
682
+ // as a real play session and should get the boot prompt.
683
+ if (!isPreview) {
684
+ let saves = [];
685
+ try { saves = await GameSaver.listSaves(gameId); } catch { saves = []; }
686
+ if (saves.length > 0) {
687
+ const choice = await openSavesDialog('boot', gameId);
688
+ if (choice.type === 'load') {
689
+ saveBytes = await GameSaver.load(choice.slotIndex, gameId);
690
+ }
691
+ }
692
+ }
693
+
694
+ await initWasmPlayer(bytes, filename, bc, saveBytes, isPreview, recordWalkthrough, runWalkthrough);
695
+ }
696
+
697
+ // ── Start screen helpers ──────────────────────────────────────────────────────
698
+
699
+ function _esc(str) {
700
+ return String(str)
701
+ .replace(/&/g, '&amp;').replace(/</g, '&lt;')
702
+ .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
703
+ }
704
+
705
+ // ── Save/load manager (#qv-saves) ─────────────────────────────────────────────
706
+ // One dialog, two modes: "boot" (the lightweight Continue/New-Game prompt,
707
+ // shown before a game starts if saves already exist) and "manage" (the
708
+ // persistent in-game Save/Load manager, opened via the Save button).
709
+
710
+ let savesDialogWired = false;
711
+ let bootChoiceResolve = null;
712
+
713
+ // Waits for the browser to actually paint the current frame. WasmPlayer's
714
+ // WASM runtime is single-threaded and the engine's SaveAsync does its work
715
+ // synchronously (no genuine await inside it) — so a DOM update made right
716
+ // before calling into it sits queued but unpainted for the entire blocking
717
+ // call, since the one JS/UI thread has no chance to render until that call
718
+ // returns. Awaiting two animation frames forces a real yield back to the
719
+ // browser first, so a "Saving…" label actually reaches the screen before the
720
+ // blocking work starts, instead of only flashing briefly at the very end.
721
+ function nextPaint() {
722
+ return new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
723
+ }
724
+
725
+ // Disables a button and (if given) swaps its label for the duration of an
726
+ // async op, so slower saves (a big transcript, IndexedDB contention, low-end
727
+ // devices) read as "working" rather than an unresponsive click — there was
728
+ // previously no feedback at all between clicking Save and the list
729
+ // refreshing. busyText is omitted for icon-only buttons (e.g. delete), whose
730
+ // content is an <svg>, not text — overwriting textContent would destroy it.
731
+ async function withBusyButton(button, busyText, fn) {
732
+ const originalText = button.textContent;
733
+ const wasDisabled = button.disabled;
734
+ button.disabled = true;
735
+ if (busyText) button.textContent = busyText;
736
+ await nextPaint();
737
+ try {
738
+ return await fn();
739
+ } finally {
740
+ button.disabled = wasDisabled;
741
+ if (busyText) button.textContent = originalText;
742
+ }
743
+ }
744
+
745
+ function showSavesError(message) {
746
+ const el = document.getElementById('qv-saves-error');
747
+ if (!el) return;
748
+ el.textContent = message;
749
+ el.style.display = 'block';
750
+ }
751
+
752
+ function hideSavesError() {
753
+ const el = document.getElementById('qv-saves-error');
754
+ if (el) el.style.display = 'none';
755
+ }
756
+
757
+ function renderSavesList(saves, mode) {
758
+ const list = document.getElementById('qv-saves-list');
759
+ if (!list) return;
760
+ if (!saves.length) {
761
+ list.innerHTML = '<li class="text-sm text-surface-500">No saved games yet.</li>';
762
+ return;
763
+ }
764
+ // s.name already carries a human-readable date/time when the user didn't
765
+ // type a custom one (see GameSaver.save's default label) — don't also
766
+ // render s.timestamp separately, or the same moment shows up twice in
767
+ // two different formats.
768
+ list.innerHTML = saves.map(s => {
769
+ const deleteBtn = mode === 'manage'
770
+ ? `<button type="button" class="btn-icon preset-tonal-error" data-delete-slot="${s.slotIndex}" aria-label="Delete">`
771
+ + `<svg class="qv-icon" aria-hidden="true"><use href="#trash-2"></use></svg></button>`
772
+ : '';
773
+ return `<li class="flex items-center justify-between gap-2">`
774
+ + `<button type="button" class="anchor text-left flex-1" data-slot="${s.slotIndex}">${_esc(s.name)}</button>`
775
+ + deleteBtn
776
+ + `</li>`;
777
+ }).join('');
778
+ }
779
+
780
+ async function downloadSaveToFile() {
781
+ const bytes = await WebPlayer.uiSaveGame($("#divOutput").html());
782
+ const blob = new Blob([bytes], { type: 'application/xml' });
783
+ const url = URL.createObjectURL(blob);
784
+ const a = document.createElement('a');
785
+ a.href = url;
786
+ a.download = WebPlayer.gameId.replace(/\.[^.]+$/, '') + '.quest-save';
787
+ a.click();
788
+ URL.revokeObjectURL(url);
789
+ clearUnsavedProgress();
790
+ }
791
+
792
+ // A .quest-save only carries state, not resources — it must be paired with
793
+ // the currently-loaded game's original bytes to load safely (see plan).
794
+ // Identity check: prefer the game's own embedded IFID (<gameid> in the save
795
+ // XML / Bridge.GetGameIfid() for the running game) over the loading
796
+ // filename — filename is often generic/shared (every textadventures.co.uk
797
+ // game's original attribute is literally "game.aslx" no matter which game
798
+ // it is), so it can tell neither "same game, different session" nor
799
+ // "different game entirely" apart reliably. IFID is stable regardless of
800
+ // how/where the game was loaded from, so it also makes a save downloaded
801
+ // from WebPlayer for a textadventures.co.uk game load correctly here. Only
802
+ // falls back to the filename if either side lacks an ifid (rare for modern
803
+ // games). Legacy .asl/.cas games skip the check altogether: V4Game.GameID is
804
+ // hardcoded null (no ifid concept) *and* their save data is raw restore-data
805
+ // text, not XML, so it carries no "original"/gameid to fall back to either —
806
+ // there's simply nothing reliable to cross-check. The engine's own
807
+ // save-format validation (V4Game's "QUEST300"/"QUEST200.1" header check) is
808
+ // the safety net there instead, same tradeoff WebPlayer's equivalent check
809
+ // already makes.
810
+ async function loadSaveFromFile(file) {
811
+ const bytes = new Uint8Array(await file.arrayBuffer());
812
+
813
+ if (/\.(asl|cas)$/i.test(originalGameFilename)) {
814
+ hideSavesError();
815
+ await restartGame(bytes);
816
+ return;
817
+ }
818
+
819
+ let originalAttr = null;
820
+ let uploadedIfid = null;
821
+ try {
822
+ const text = new TextDecoder('utf-8').decode(bytes);
823
+ const xml = new DOMParser().parseFromString(text, 'application/xml');
824
+ originalAttr = xml.documentElement?.getAttribute('original') ?? null;
825
+ uploadedIfid = xml.querySelector('game > gameid')?.textContent?.trim() || null;
826
+ } catch { /* falls through to the mismatch error below */ }
827
+
828
+ const currentIfid = Bridge.GetGameIfid();
829
+ const currentIdentity = currentIfid || computeGameId(originalGameFilename);
830
+ const uploadedIdentity = uploadedIfid || (originalAttr && computeGameId(originalAttr));
831
+
832
+ if (!uploadedIdentity || currentIdentity.toLowerCase() !== uploadedIdentity.toLowerCase()) {
833
+ showSavesError('This save is for a different game — open that game first, then try again.');
834
+ return;
835
+ }
836
+ hideSavesError();
837
+ await restartGame(bytes);
838
+ }
839
+
840
+ function ensureSavesDialogWired() {
841
+ if (savesDialogWired) return;
842
+ savesDialogWired = true;
843
+
844
+ const dlg = document.getElementById('qv-saves');
845
+ if (!dlg) return;
846
+
847
+ // Non-cancellable while a boot-time choice is pending (matches WebPlayer's
848
+ // Slots dialog); freely closable otherwise.
849
+ dlg.addEventListener('cancel', (e) => {
850
+ if (bootChoiceResolve) e.preventDefault();
851
+ });
852
+
853
+ document.getElementById('qv-saves-start-new').addEventListener('click', (e) => {
854
+ if (bootChoiceResolve) {
855
+ const resolve = bootChoiceResolve;
856
+ bootChoiceResolve = null;
857
+ dlg.close();
858
+ resolve({ type: 'new' });
859
+ return;
860
+ }
861
+ // Manage mode: restarting mid-session, matches WebPlayer's Slots
862
+ // "Start from the beginning" button (no confirm() there either).
863
+ // withBusyButton's disable+busy-label+forced-paint makes a slow
864
+ // restart (a large game, a low-end device) read as "working" rather
865
+ // than unresponsive — restartGame itself also now guards against
866
+ // overlapping calls (see restartInProgress's doc comment), but
867
+ // without this there was no visible feedback at all inviting
868
+ // exactly the impatient re-click that guard exists for.
869
+ withBusyButton(e.currentTarget, 'Restarting…', () => restartGame(null));
870
+ });
871
+
872
+ document.getElementById('qv-saves-list').addEventListener('click', async (e) => {
873
+ const loadBtn = e.target.closest('[data-slot]');
874
+ if (loadBtn) {
875
+ const slotIndex = Number(loadBtn.dataset.slot);
876
+ if (bootChoiceResolve) {
877
+ const resolve = bootChoiceResolve;
878
+ bootChoiceResolve = null;
879
+ dlg.close();
880
+ resolve({ type: 'load', slotIndex });
881
+ } else {
882
+ const bytes = await GameSaver.load(slotIndex, WebPlayer.gameId);
883
+ await restartGame(bytes);
884
+ }
885
+ return;
886
+ }
887
+ const delBtn = e.target.closest('[data-delete-slot]');
888
+ if (delBtn) {
889
+ const name = delBtn.closest('li')?.querySelector('[data-slot]')?.textContent ?? 'this save';
890
+ if (!confirm(`Delete "${name}"? This can't be undone.`)) return;
891
+ await withBusyButton(delBtn, '', async () => {
892
+ await GameSaver.deleteSlot(Number(delBtn.dataset.deleteSlot), WebPlayer.gameId);
893
+ });
894
+ renderSavesList(await GameSaver.listSaves(WebPlayer.gameId), 'manage');
895
+ }
896
+ });
897
+
898
+ document.getElementById('qv-saves-save-new').addEventListener('click', async (e) => {
899
+ const input = document.getElementById('qv-saves-name-input');
900
+ await withBusyButton(e.currentTarget, 'Saving…', async () => {
901
+ await GameSaver.save(input.value.trim() || undefined);
902
+ });
903
+ input.value = '';
904
+ renderSavesList(await GameSaver.listSaves(WebPlayer.gameId), 'manage');
905
+ });
906
+
907
+ document.getElementById('qv-saves-download').addEventListener('click', (e) =>
908
+ withBusyButton(e.currentTarget, 'Saving…', downloadSaveToFile));
909
+
910
+ const uploadBtn = document.getElementById('qv-saves-upload-btn');
911
+ const fileInput = document.getElementById('qv-saves-file-input');
912
+ uploadBtn.addEventListener('click', () => fileInput.click());
913
+ fileInput.addEventListener('change', async () => {
914
+ const file = fileInput.files?.[0];
915
+ fileInput.value = '';
916
+ if (file) await loadSaveFromFile(file);
917
+ });
918
+
919
+ document.getElementById('qv-saves-close').addEventListener('click', () => dlg.close());
920
+ }
921
+
922
+ // mode: 'boot' resolves {type:'new'} or {type:'load', slotIndex} once the
923
+ // user picks; 'manage' just opens the persistent manager (callers act via
924
+ // the wired-up click handlers above, nothing to await).
925
+ async function openSavesDialog(mode, gameId = WebPlayer.gameId) {
926
+ ensureSavesDialogWired();
927
+ const dlg = document.getElementById('qv-saves');
928
+ hideSavesError();
929
+ dlg.dataset.mode = mode;
930
+ renderSavesList(await GameSaver.listSaves(gameId), mode);
931
+
932
+ if (mode === 'boot') {
933
+ return new Promise(resolve => {
934
+ bootChoiceResolve = resolve;
935
+ dlg.showModal();
936
+ });
937
+ }
938
+
939
+ dlg.showModal();
940
+ }
941
+
942
+ // ── Debugger (#questVivaDebugger) ─────────────────────────────────────────────
943
+ // Only ever opened in editor-preview sessions (see WebPlayer.setCanDebug's
944
+ // call site in initWasmPlayer/restartGame) — element browser, per-tab
945
+ // attribute inspector with a "hack your own game" override, and a walkthrough
946
+ // runner. Mirrors WebPlayer's Debugger/Attributes/Walkthrough.razor, which
947
+ // drive IGameDebug directly as Blazor components; here the same data comes
948
+ // over the bridge as JSON (Bridge.Get*Json — see WasmPlayerBridge.cs) for
949
+ // plain-DOM rendering instead.
950
+
951
+ let debuggerWired = false;
952
+ let debuggerActiveTab = 'Walkthrough';
953
+ let debuggerSelectedItem = null;
954
+ // Name of the walkthrough currently running, or null — the source of truth
955
+ // for the Run/Cancel/status UI, *not* the DOM elements themselves. Closing
956
+ // and reopening the dialog (or switching tabs/objects) rebuilds
957
+ // #qv-debugger-detail from scratch, which used to silently lose whatever
958
+ // Run/Cancel state only lived in the old (now-replaced) DOM nodes — a
959
+ // walkthrough kept running with no way to see its status or cancel it once
960
+ // the dialog was reopened. Every render of the Walkthrough detail panel
961
+ // checks this instead, so it comes back correctly regardless of how many
962
+ // times the panel gets rebuilt while a walkthrough is running.
963
+ let runningWalkthroughName = null;
964
+ // Which attribute row (if any) has its override panel open — a single
965
+ // fixed panel below the table, not one input per row (an earlier version
966
+ // tried cramming input+button+hint into a 4th table column and it didn't
967
+ // fit at any reasonable dialog width).
968
+ let debuggerSelectedAttr = null;
969
+ // Sort/filter state for the attribute table — reset whenever a different
970
+ // object/tab is selected (renderDebuggerList's click handler / selectDebuggerTab),
971
+ // but preserved across same-object re-renders (Apply, row selection).
972
+ let debuggerAttrSort = { column: 'attribute', direction: 'asc' };
973
+ let debuggerAttrSearch = '';
974
+ // The current object's raw {attrName: DebugDataItem} data, cached so
975
+ // re-sorting/re-filtering (every keystroke in the search box, every header
976
+ // click) doesn't need a fresh Bridge round-trip each time — only rebuilt
977
+ // when the object actually changes or an override is applied.
978
+ let debuggerAttrData = null;
979
+
980
+ // ── Move/resize/splitter/column-resize state ────────────────────────────────
981
+ // All in px, all session-only (in-memory, not persisted across a page
982
+ // reload) — a dev tool's window geometry isn't worth the complexity of
983
+ // persisting across reloads, but it should survive closing/reopening the
984
+ // dialog and game restarts within the same session, so these live at module
985
+ // scope rather than being recomputed/reset on every render.
986
+
987
+ // Default size scales with the viewport (roughly three-quarters of it)
988
+ // rather than a fixed px value, so it actually uses the room available on a
989
+ // typical editor-preview window instead of looking small in the middle of
990
+ // it — capped at DEBUGGER_MAX_*_DEFAULT so it doesn't balloon absurdly large
991
+ // on an oversized monitor, and floored at DEBUGGER_MIN_* (below) so it never
992
+ // starts out smaller than the resize handle's own minimum.
993
+ const DEBUGGER_DEFAULT_SIZE_FRACTION = 0.75;
994
+ const DEBUGGER_MAX_DEFAULT_WIDTH = 1100;
995
+ const DEBUGGER_MAX_DEFAULT_HEIGHT = 820;
996
+ const DEBUGGER_MIN_WIDTH = 480;
997
+ const DEBUGGER_MIN_HEIGHT = 360;
998
+ const DEBUGGER_MIN_LIST_WIDTH = 100;
999
+ const DEBUGGER_MIN_DETAIL_WIDTH = 200;
1000
+ const DEBUGGER_MIN_COLUMN_WIDTH = 60;
1001
+ // Source (the unsized, "whatever's left" column — see renderDebuggerAttributesDetail)
1002
+ // has no floor of its own otherwise: table-layout:fixed hands it literally
1003
+ // whatever pixels remain after Attribute/Value, which on a narrow dialog can
1004
+ // be smaller than common Source values like "defaultobject" need to render
1005
+ // on one line. overflow-wrap:break-word then wraps that single word
1006
+ // character-by-character, inflating the *whole row* (row height tracks its
1007
+ // tallest cell) — worse the narrower the leftover gets, all the way down to
1008
+ // a one-row table filling hundreds of pixels at the extreme. Below, this
1009
+ // becomes a min-width on the table itself so the table can never be
1010
+ // squeezed narrower than Attribute+Value+this — .qv-debugger-scroll's
1011
+ // overflow-x:auto (chrome.css) then takes over with a horizontal scrollbar
1012
+ // instead, which is a far smaller UX cost than every row ballooning.
1013
+ const DEBUGGER_MIN_SOURCE_WIDTH = 100;
1014
+
1015
+ // null until the first time the dialog is ever opened — see applyDebuggerRect.
1016
+ let debuggerRect = null;
1017
+ let debuggerListWidth = 192; // matches the old w-48 (12rem) Tailwind default
1018
+ // Narrower starting point on a phone-width viewport (chrome.css's
1019
+ // max-width:767px breakpoint stacks the list above the table instead of
1020
+ // beside it, but even the full dialog width rarely clears 160+260=420px) —
1021
+ // still just a default the user can widen via the column-resize handles
1022
+ // (wireDebuggerColumnResize), and still small enough to require scrolling
1023
+ // for a long Value, but sized so a typical short one doesn't need it.
1024
+ let debuggerColWidths = window.innerWidth < 767
1025
+ ? { attribute: 100, value: 140 }
1026
+ : { attribute: 160, value: 260 }; // 'source' just takes whatever's left
1027
+
1028
+ // Generic pointer-drag helper — used by the title bar, resize handle,
1029
+ // splitter, and column-resize handles below. onMove receives the raw
1030
+ // pointermove event; the caller computes whatever delta it needs from
1031
+ // clientX/clientY captured at drag start. document.body.style.cursor is a
1032
+ // plain inline style (works regardless of the .qv-chrome CSS scoping); the
1033
+ // user-select:none class goes on the dialog itself, not <body> — see
1034
+ // :scope.qv-debugger-drag-active's doc comment in chrome.css for why.
1035
+ function startDebuggerDrag(startEvent, cursor, onMove, onEnd) {
1036
+ startEvent.preventDefault();
1037
+ const dlg = document.getElementById('questVivaDebugger');
1038
+ dlg.classList.add('qv-debugger-drag-active');
1039
+ document.body.style.cursor = cursor;
1040
+
1041
+ const move = (e) => onMove(e);
1042
+ const end = (e) => {
1043
+ document.removeEventListener('pointermove', move);
1044
+ document.removeEventListener('pointerup', end);
1045
+ dlg.classList.remove('qv-debugger-drag-active');
1046
+ document.body.style.cursor = '';
1047
+ if (onEnd) onEnd(e);
1048
+ };
1049
+
1050
+ document.addEventListener('pointermove', move);
1051
+ document.addEventListener('pointerup', end);
1052
+ }
1053
+
1054
+ function clamp(value, min, max) {
1055
+ return Math.min(Math.max(value, min), Math.max(min, max));
1056
+ }
1057
+
1058
+ // Applied right after every showModal() (see wireDebuggerButton/restartGame's
1059
+ // call sites), before the browser gets a chance to paint — so the dialog
1060
+ // never visibly flashes at its old browser-default centered position first.
1061
+ // Computes a centered default the very first time it's called; every
1062
+ // subsequent call (reopening the dialog, or after the user drags/resizes)
1063
+ // just re-applies whatever debuggerRect currently holds.
1064
+ function applyDebuggerRect() {
1065
+ const dlg = document.getElementById('questVivaDebugger');
1066
+ if (!dlg) return;
1067
+
1068
+ // Available space after the same 40px (20px/side) margin the default
1069
+ // sizing below already budgets for. On a narrow phone viewport this can
1070
+ // be smaller than DEBUGGER_MIN_WIDTH/HEIGHT — clamp()'s min always wins
1071
+ // over a smaller max, so without this the dialog would still be forced
1072
+ // to the 480x360 floor, end up wider/taller than the viewport, and (via
1073
+ // the centering below) get a negative left/top that pushes it off to one
1074
+ // side instead of actually centering it.
1075
+ const maxAvailableWidth = window.innerWidth - 40;
1076
+ const maxAvailableHeight = window.innerHeight - 40;
1077
+
1078
+ if (!debuggerRect) {
1079
+ const width = maxAvailableWidth < DEBUGGER_MIN_WIDTH
1080
+ ? maxAvailableWidth
1081
+ : clamp(Math.round(window.innerWidth * DEBUGGER_DEFAULT_SIZE_FRACTION), DEBUGGER_MIN_WIDTH, Math.min(DEBUGGER_MAX_DEFAULT_WIDTH, maxAvailableWidth));
1082
+ const height = maxAvailableHeight < DEBUGGER_MIN_HEIGHT
1083
+ ? maxAvailableHeight
1084
+ : clamp(Math.round(window.innerHeight * DEBUGGER_DEFAULT_SIZE_FRACTION), DEBUGGER_MIN_HEIGHT, Math.min(DEBUGGER_MAX_DEFAULT_HEIGHT, maxAvailableHeight));
1085
+ debuggerRect = {
1086
+ left: Math.round((window.innerWidth - width) / 2),
1087
+ top: Math.round((window.innerHeight - height) / 2),
1088
+ width,
1089
+ height,
1090
+ };
1091
+ } else {
1092
+ // Re-clamp whatever geometry the user last left it at (dragged,
1093
+ // resized, or just the computed default above) to the *current*
1094
+ // viewport. debuggerRect is session-only state that otherwise only
1095
+ // changes from explicit drags (wireDebuggerMoveResize/wireDebuggerSplitter),
1096
+ // so reopening after a resize/orientation change would otherwise
1097
+ // keep reapplying a stale rect sized for the old viewport and could
1098
+ // end up partly or fully off-screen.
1099
+ const width = Math.min(debuggerRect.width, maxAvailableWidth);
1100
+ const height = Math.min(debuggerRect.height, maxAvailableHeight);
1101
+ debuggerRect = {
1102
+ width,
1103
+ height,
1104
+ left: clamp(debuggerRect.left, 0, Math.max(0, window.innerWidth - width)),
1105
+ top: clamp(debuggerRect.top, 0, Math.max(0, window.innerHeight - height)),
1106
+ };
1107
+ }
1108
+
1109
+ dlg.style.left = `${debuggerRect.left}px`;
1110
+ dlg.style.top = `${debuggerRect.top}px`;
1111
+ dlg.style.width = `${debuggerRect.width}px`;
1112
+ dlg.style.height = `${debuggerRect.height}px`;
1113
+ }
1114
+
1115
+ function wireDebuggerMoveResize() {
1116
+ const dlg = document.getElementById('questVivaDebugger');
1117
+ const titlebar = document.getElementById('qv-debugger-titlebar');
1118
+ const resizeHandle = document.getElementById('qv-debugger-resize-handle');
1119
+
1120
+ titlebar.addEventListener('pointerdown', (e) => {
1121
+ if (e.target.closest('#qv-debugger-close')) return;
1122
+ const startX = e.clientX;
1123
+ const startY = e.clientY;
1124
+ const { left: startLeft, top: startTop, width, height } = debuggerRect;
1125
+
1126
+ startDebuggerDrag(e, 'move', (moveEvent) => {
1127
+ const left = clamp(startLeft + (moveEvent.clientX - startX), 0, window.innerWidth - width);
1128
+ const top = clamp(startTop + (moveEvent.clientY - startY), 0, window.innerHeight - height);
1129
+ debuggerRect = { ...debuggerRect, left, top };
1130
+ dlg.style.left = `${left}px`;
1131
+ dlg.style.top = `${top}px`;
1132
+ });
1133
+ });
1134
+
1135
+ resizeHandle.addEventListener('pointerdown', (e) => {
1136
+ const startX = e.clientX;
1137
+ const startY = e.clientY;
1138
+ const { left, top, width: startWidth, height: startHeight } = debuggerRect;
1139
+
1140
+ startDebuggerDrag(e, 'nwse-resize', (moveEvent) => {
1141
+ const width = clamp(startWidth + (moveEvent.clientX - startX), DEBUGGER_MIN_WIDTH, window.innerWidth - left);
1142
+ const height = clamp(startHeight + (moveEvent.clientY - startY), DEBUGGER_MIN_HEIGHT, window.innerHeight - top);
1143
+ debuggerRect = { ...debuggerRect, width, height };
1144
+ dlg.style.width = `${width}px`;
1145
+ dlg.style.height = `${height}px`;
1146
+ });
1147
+ });
1148
+ }
1149
+
1150
+ function wireDebuggerSplitter() {
1151
+ const splitter = document.getElementById('qv-debugger-splitter');
1152
+ const list = document.getElementById('qv-debugger-list');
1153
+ const panes = document.getElementById('qv-debugger-panes');
1154
+
1155
+ splitter.addEventListener('pointerdown', (e) => {
1156
+ const startX = e.clientX;
1157
+ const startWidth = list.getBoundingClientRect().width;
1158
+ splitter.classList.add('qv-debugger-dragging');
1159
+
1160
+ startDebuggerDrag(e, 'col-resize', (moveEvent) => {
1161
+ const containerWidth = panes.getBoundingClientRect().width;
1162
+ const maxWidth = containerWidth - DEBUGGER_MIN_DETAIL_WIDTH - splitter.getBoundingClientRect().width;
1163
+ debuggerListWidth = clamp(startWidth + (moveEvent.clientX - startX), DEBUGGER_MIN_LIST_WIDTH, maxWidth);
1164
+ list.style.width = `${debuggerListWidth}px`;
1165
+ }, () => splitter.classList.remove('qv-debugger-dragging'));
1166
+ });
1167
+ }
1168
+
1169
+ // Attribute-table column resizing — only the first two columns (Attribute,
1170
+ // Value) get a drag handle; Source just absorbs whatever width is left over
1171
+ // (see the <colgroup> built in renderDebuggerAttributesDetail), matching how
1172
+ // #qv-debugger-splitter only needs to move one boundary for a two-pane
1173
+ // layout. Wired once in ensureDebuggerWired via delegation, since the
1174
+ // handles themselves are rebuilt on every renderDebuggerAttributesDetail
1175
+ // call (a fresh object/tab, or after Apply).
1176
+ function wireDebuggerColumnResize(startEvent) {
1177
+ const handle = startEvent.target.closest('[data-resize-col]');
1178
+ if (!handle) return false;
1179
+
1180
+ const key = handle.dataset.resizeCol;
1181
+ const table = handle.closest('table');
1182
+ const col = table.querySelector(`col[data-col="${key}"]`);
1183
+ if (!col) return true;
1184
+
1185
+ const startX = startEvent.clientX;
1186
+ const startWidth = debuggerColWidths[key];
1187
+ handle.classList.add('qv-debugger-dragging');
1188
+
1189
+ startDebuggerDrag(startEvent, 'col-resize', (moveEvent) => {
1190
+ const width = Math.max(DEBUGGER_MIN_COLUMN_WIDTH, startWidth + (moveEvent.clientX - startX));
1191
+ debuggerColWidths = { ...debuggerColWidths, [key]: width };
1192
+ col.style.width = `${width}px`;
1193
+ // Keep the table's own min-width (set in renderDebuggerAttributesDetail)
1194
+ // in sync — otherwise widening Attribute/Value here just shrinks
1195
+ // Source's leftover share instead of actually growing the table,
1196
+ // reintroducing the cramped-Source wrapping this min-width exists
1197
+ // to prevent (see DEBUGGER_MIN_SOURCE_WIDTH's doc comment).
1198
+ table.style.minWidth = `${debuggerColWidths.attribute + debuggerColWidths.value + DEBUGGER_MIN_SOURCE_WIDTH}px`;
1199
+ }, () => handle.classList.remove('qv-debugger-dragging'));
1200
+
1201
+ return true;
1202
+ }
1203
+
1204
+ // DebugDataItem.Value is a human-readable *display* string (Fields.cs's
1205
+ // DefaultFormatter just calls ToString() — a string has no quotes, a bool
1206
+ // reads "True"/"False", an object reference reads as "Object: kitchen").
1207
+ // EditValue (same object, a sibling field) is the same underlying value
1208
+ // pre-formatted as valid script syntax instead — quoted string, lowercase
1209
+ // true/false, bare object name — ready to feed straight into Apply. Only
1210
+ // shown at all when item.CanOverride is true (see Fields.cs's
1211
+ // CanOverrideValue) — lists/dicts/scripts have no simple literal syntax to
1212
+ // write back, so those get a short note instead of a dead-end textbox (see
1213
+ // renderDebuggerOverridePanel).
1214
+ const DEBUGGER_OVERRIDE_HINT = 'Edit and Apply to change this value for the rest of the session';
1215
+
1216
+ function renderDebuggerTabs(types) {
1217
+ const tabs = document.getElementById('qv-debugger-tabs');
1218
+ const allTabs = ['Walkthrough', ...types];
1219
+ tabs.innerHTML = allTabs.map(tab =>
1220
+ `<button type="button" class="btn btn-sm ${tab === debuggerActiveTab ? 'preset-filled-primary-500' : 'preset-tonal-surface'}" data-tab="${_esc(tab)}">${_esc(tab)}</button>`
1221
+ ).join('');
1222
+ }
1223
+
1224
+ // Returns the rendered items — refreshDebuggerAfterTurn uses this to notice
1225
+ // when a turn has made the currently-selected item (an object that got
1226
+ // destroyed, a timer that finished, ...) disappear from its own list.
1227
+ function renderDebuggerList() {
1228
+ const list = document.getElementById('qv-debugger-list');
1229
+ const items = debuggerActiveTab === 'Walkthrough'
1230
+ ? JSON.parse(Bridge.GetWalkthroughNamesJson())
1231
+ : JSON.parse(Bridge.GetDebugObjectsJson(debuggerActiveTab));
1232
+
1233
+ if (!items.length) {
1234
+ list.innerHTML = '<li class="text-sm text-surface-500 px-2 py-1">Nothing here.</li>';
1235
+ return items;
1236
+ }
1237
+
1238
+ // A plain selectable list, not hyperlinks — .qv-debugger-list-item is a
1239
+ // block row with its own hover/selected background (shares
1240
+ // .qv-debugger-row-selected with the attribute table below).
1241
+ list.innerHTML = items.map(item => {
1242
+ const selected = item === debuggerSelectedItem;
1243
+ return `<li><button type="button" class="qv-debugger-list-item${selected ? ' qv-debugger-row-selected' : ''}" data-item="${_esc(item)}" aria-selected="${selected}">${_esc(item)}</button></li>`;
1244
+ }).join('');
1245
+ return items;
1246
+ }
1247
+
1248
+ function renderDebuggerWalkthroughDetail(name) {
1249
+ const detail = document.getElementById('qv-debugger-detail');
1250
+ const steps = JSON.parse(Bridge.GetWalkthroughStepsJson(name));
1251
+ const running = name === runningWalkthroughName;
1252
+ detail.innerHTML = '<div class="qv-debugger-scroll">'
1253
+ + '<ol class="list-decimal list-inside space-y-1">'
1254
+ + steps.map(step => `<li>${_esc(step)}</li>`).join('')
1255
+ + '</ol>'
1256
+ + '</div>'
1257
+ + '<div class="qv-debugger-footer flex gap-2 items-center">'
1258
+ + `<button type="button" class="btn preset-filled-primary-500" data-run-walkthrough="${_esc(name)}"${running ? ' disabled' : ''}>Run</button>`
1259
+ + `<button type="button" class="btn preset-tonal-surface${running ? '' : ' hidden'}" data-cancel-walkthrough>Cancel</button>`
1260
+ + `<span class="text-sm" data-walkthrough-status>${running ? 'Running…' : ''}</span>`
1261
+ + '</div>';
1262
+ }
1263
+
1264
+ const DEBUGGER_ATTR_COLUMNS = [
1265
+ { key: 'attribute', label: 'Attribute' },
1266
+ { key: 'value', label: 'Value' },
1267
+ { key: 'source', label: 'Source' },
1268
+ ];
1269
+
1270
+ function debuggerAttrSortIndicator(column) {
1271
+ if (debuggerAttrSort.column !== column) return '';
1272
+ return debuggerAttrSort.direction === 'asc' ? ' ▲' : ' ▼';
1273
+ }
1274
+
1275
+ // Applies debuggerAttrSearch (matches against the attribute name or its
1276
+ // display value) and debuggerAttrSort to debuggerAttrData's keys.
1277
+ function sortedFilteredDebuggerAttrs() {
1278
+ const query = debuggerAttrSearch.trim().toLowerCase();
1279
+ let attrs = Object.keys(debuggerAttrData);
1280
+ if (query) {
1281
+ attrs = attrs.filter(attr =>
1282
+ attr.toLowerCase().includes(query) || debuggerAttrData[attr].Value.toLowerCase().includes(query));
1283
+ }
1284
+
1285
+ const { column, direction } = debuggerAttrSort;
1286
+ const sortKey = attr => column === 'attribute' ? attr
1287
+ : column === 'value' ? debuggerAttrData[attr].Value
1288
+ : (debuggerAttrData[attr].Source ?? '');
1289
+ attrs.sort((a, b) => sortKey(a).localeCompare(sortKey(b), undefined, { sensitivity: 'base' }));
1290
+ if (direction === 'desc') attrs.reverse();
1291
+ return attrs;
1292
+ }
1293
+
1294
+ // Rebuilds just the <tbody> (and the header sort indicators) — deliberately
1295
+ // not the whole panel, so re-sorting/typing in the search box doesn't touch
1296
+ // .qv-debugger-scroll (would reset its scroll position) or the search
1297
+ // <input> itself (would drop keyboard focus mid-keystroke).
1298
+ function renderDebuggerAttrRows() {
1299
+ const tbody = document.getElementById('qv-debugger-attr-tbody');
1300
+ if (!tbody) return;
1301
+
1302
+ // Only the label <span> gets its text replaced — a resize handle
1303
+ // (.qv-debugger-col-resize) is a sibling inside the same <th>, and
1304
+ // setting th.textContent directly would wipe that handle out on every
1305
+ // sort/search re-render.
1306
+ document.querySelectorAll('#qv-debugger-detail [data-sort-col]').forEach(th => {
1307
+ const col = th.dataset.sortCol;
1308
+ const label = th.querySelector('.qv-debugger-sort-label');
1309
+ if (label) label.textContent = DEBUGGER_ATTR_COLUMNS.find(c => c.key === col).label + debuggerAttrSortIndicator(col);
1310
+ });
1311
+
1312
+ const attrs = sortedFilteredDebuggerAttrs();
1313
+ if (!attrs.length) {
1314
+ tbody.innerHTML = '<tr><td colspan="3" class="text-surface-500">No matching attributes.</td></tr>';
1315
+ return;
1316
+ }
1317
+
1318
+ tbody.innerHTML = attrs.map(attr => {
1319
+ const item = debuggerAttrData[attr];
1320
+ const classes = [item.IsInherited ? 'qv-debugger-row-inherited' : '', attr === debuggerSelectedAttr ? 'qv-debugger-row-selected' : ''];
1321
+ return `<tr class="${classes.join(' ')}" data-attr-row="${_esc(attr)}">`
1322
+ + `<td>${_esc(attr)}</td>`
1323
+ + `<td>${_esc(item.Value)}</td>`
1324
+ + `<td>${_esc(item.Source ?? '')}</td>`
1325
+ + '</tr>';
1326
+ }).join('');
1327
+ }
1328
+
1329
+ // The table (which can run to a couple dozen rows for an inherited-heavy
1330
+ // object like the default player) scrolls in its own inner region
1331
+ // (.qv-debugger-scroll); the override panel is a separate, non-scrolling
1332
+ // footer so selecting a row near the top of a long table doesn't require
1333
+ // scrolling past everything else to reach the Apply button. Sorting/search
1334
+ // only ever rebuild the <tbody> (see renderDebuggerAttrRows) — this function
1335
+ // is the one that talks to the bridge and rebuilds the whole panel shell
1336
+ // (search box, sortable headers, override panel), for a genuine object
1337
+ // switch or after Apply changes the underlying data.
1338
+ function renderDebuggerAttributesDetail(tab, obj) {
1339
+ const detail = document.getElementById('qv-debugger-detail');
1340
+ debuggerAttrData = JSON.parse(Bridge.GetDebugDataJson(tab, obj)).Data || {};
1341
+ const attrs = Object.keys(debuggerAttrData);
1342
+
1343
+ if (!attrs.length) {
1344
+ detail.innerHTML = '<p class="text-surface-500">No attributes.</p>';
1345
+ return;
1346
+ }
1347
+
1348
+ if (!attrs.includes(debuggerSelectedAttr)) debuggerSelectedAttr = null;
1349
+
1350
+ // Only Attribute/Value get an explicit <col> width + resize handle —
1351
+ // Source (the last column) just takes whatever width table-layout:fixed
1352
+ // leaves over, the same "only one boundary to drag" simplification
1353
+ // wireDebuggerSplitter uses for the two-pane list/detail split.
1354
+ detail.innerHTML = `<input type="text" class="qv-debugger-input mb-2" id="qv-debugger-attr-search" placeholder="Search attributes…" autocomplete="off" value="${_esc(debuggerAttrSearch)}">`
1355
+ + '<div class="qv-debugger-scroll">'
1356
+ + `<table class="table qv-debugger-table" style="min-width:${debuggerColWidths.attribute + debuggerColWidths.value + DEBUGGER_MIN_SOURCE_WIDTH}px">`
1357
+ + `<colgroup><col data-col="attribute" style="width:${debuggerColWidths.attribute}px">`
1358
+ + `<col data-col="value" style="width:${debuggerColWidths.value}px"><col data-col="source"></colgroup>`
1359
+ + '<thead><tr>'
1360
+ + DEBUGGER_ATTR_COLUMNS.map(c => '<th data-sort-col="' + c.key + '">'
1361
+ + `<span class="qv-debugger-sort-label">${_esc(c.label)}${debuggerAttrSortIndicator(c.key)}</span>`
1362
+ + (c.key === 'source' ? '' : `<span class="qv-debugger-col-resize" data-resize-col="${c.key}"></span>`)
1363
+ + '</th>').join('')
1364
+ + '</tr></thead><tbody id="qv-debugger-attr-tbody"></tbody></table>'
1365
+ + '</div>'
1366
+ + '<div id="qv-debugger-override" class="qv-debugger-footer"></div>';
1367
+
1368
+ renderDebuggerAttrRows();
1369
+ document.getElementById('qv-debugger-attr-search').addEventListener('input', (e) => {
1370
+ debuggerAttrSearch = e.target.value;
1371
+ renderDebuggerAttrRows();
1372
+ });
1373
+
1374
+ if (debuggerSelectedAttr) renderDebuggerOverridePanel(debuggerSelectedAttr, debuggerAttrData[debuggerSelectedAttr]);
1375
+ }
1376
+
1377
+ // renderDebuggerAttributesDetail rebuilds the whole #qv-debugger-detail
1378
+ // subtree (innerHTML), which resets .qv-debugger-scroll's scroll position to
1379
+ // 0 — fine for a genuine switch to a different object/tab (starting back at
1380
+ // the top makes sense there), but jarring for a same-object re-render:
1381
+ // selecting a row further down a long table, or re-rendering after Apply,
1382
+ // used to visibly snap the table back to the top. Callers that are
1383
+ // re-rendering the *same* object wrap the call in this so the scroll
1384
+ // position survives the rebuild.
1385
+ function withPreservedDebuggerScroll(renderFn) {
1386
+ const before = document.querySelector('#qv-debugger-detail .qv-debugger-scroll');
1387
+ const previousScrollTop = before ? before.scrollTop : 0;
1388
+ renderFn();
1389
+ const after = document.querySelector('#qv-debugger-detail .qv-debugger-scroll');
1390
+ if (after) after.scrollTop = previousScrollTop;
1391
+ }
1392
+
1393
+ // The single "click a row above to edit it" panel — populated for whichever
1394
+ // attribute is currently selected, instead of one input per row (see
1395
+ // debuggerSelectedAttr's doc comment). item.CanOverride is false for value
1396
+ // kinds with no simple literal syntax to write back (lists, dictionaries,
1397
+ // scripts, ...) — an override textbox for those would just be a dead end, so
1398
+ // a short note is shown instead of one (see Fields.cs's CanOverrideValue).
1399
+ function renderDebuggerOverridePanel(attr, item) {
1400
+ const panel = document.getElementById('qv-debugger-override');
1401
+ if (!panel) return;
1402
+
1403
+ if (!item.CanOverride) {
1404
+ panel.innerHTML = `<div class="text-sm font-semibold mb-1">${_esc(attr)}</div>`
1405
+ + '<div class="text-xs text-surface-500">This value isn\'t a simple type the debugger can override directly.</div>';
1406
+ return;
1407
+ }
1408
+
1409
+ panel.innerHTML = `<div class="text-sm font-semibold mb-2">Override <code>${_esc(attr)}</code></div>`
1410
+ + '<div class="flex gap-2 items-center">'
1411
+ + `<input class="qv-debugger-input flex-1" type="text" value="${_esc(item.EditValue ?? item.Value)}" id="qv-debugger-override-input">`
1412
+ + '<button type="button" class="btn preset-tonal-primary" id="qv-debugger-override-apply">Apply</button>'
1413
+ + '</div>'
1414
+ + `<div class="text-xs text-surface-500 mt-1">${_esc(DEBUGGER_OVERRIDE_HINT)}</div>`
1415
+ + '<div class="text-xs preset-tonal-error hidden mt-1" id="qv-debugger-override-error"></div>';
1416
+ }
1417
+
1418
+ function renderDebuggerDetail() {
1419
+ const detail = document.getElementById('qv-debugger-detail');
1420
+ if (!debuggerSelectedItem) {
1421
+ detail.innerHTML = '<p class="text-surface-500">Select an item to view details.</p>';
1422
+ return;
1423
+ }
1424
+
1425
+ if (debuggerActiveTab === 'Walkthrough') {
1426
+ renderDebuggerWalkthroughDetail(debuggerSelectedItem);
1427
+ } else {
1428
+ renderDebuggerAttributesDetail(debuggerActiveTab, debuggerSelectedItem);
1429
+ }
1430
+ }
1431
+
1432
+ // Called after every turn (WebPlayer.sendCommand/uiSendEvent below) now that
1433
+ // the dialog is non-modal and can be left open while playing (see
1434
+ // wireDebuggerButton's doc comment) — without this, it only ever reflected
1435
+ // whatever the game's state was at the moment an object/tab was last
1436
+ // clicked, which used to be the *only* moment it could possibly go stale
1437
+ // (nothing else could run a turn while a modal dialog had the page inert).
1438
+ function refreshDebuggerAfterTurn() {
1439
+ const dlg = document.getElementById('questVivaDebugger');
1440
+ if (!dlg || !dlg.open) return;
1441
+
1442
+ // Re-list first, not just the selected item's own attributes — a turn
1443
+ // can create/destroy objects, open new exits, add/remove timers, etc.
1444
+ renderDebuggerTabs(JSON.parse(Bridge.GetDebuggerObjectTypesJson()));
1445
+ const items = renderDebuggerList();
1446
+ // The very thing being inspected can itself be the casualty of a turn
1447
+ // (the object got destroyed, moved out of scope, or a timer fired and
1448
+ // removed itself) — fall back to the placeholder instead of asking
1449
+ // Bridge for debug data on something that may no longer exist.
1450
+ if (debuggerSelectedItem && !items.includes(debuggerSelectedItem)) {
1451
+ debuggerSelectedItem = null;
1452
+ }
1453
+ withPreservedDebuggerScroll(renderDebuggerDetail);
1454
+ }
1455
+
1456
+ function selectDebuggerTab(tab) {
1457
+ debuggerActiveTab = tab;
1458
+ // Same reasoning as wireDebuggerButton's reopen handling: switching back
1459
+ // to the Walkthrough tab while one is running should land on it, not a
1460
+ // blank "Select an item to view details."
1461
+ debuggerSelectedItem = tab === 'Walkthrough' ? runningWalkthroughName : null;
1462
+ debuggerSelectedAttr = null;
1463
+ debuggerAttrSort = { column: 'attribute', direction: 'asc' };
1464
+ debuggerAttrSearch = '';
1465
+ renderDebuggerTabs(JSON.parse(Bridge.GetDebuggerObjectTypesJson()));
1466
+ renderDebuggerList();
1467
+ renderDebuggerDetail();
1468
+ }
1469
+
1470
+ async function applyDebugAttribute(attr, value) {
1471
+ const errorEl = document.getElementById('qv-debugger-override-error');
1472
+ const error = await Bridge.SetDebugAttribute(debuggerSelectedItem, attr, value);
1473
+ if (error) {
1474
+ if (errorEl) {
1475
+ errorEl.textContent = error;
1476
+ errorEl.classList.remove('hidden');
1477
+ }
1478
+ return;
1479
+ }
1480
+ // Re-render so Value/Source reflect the change (and any knock-on effects
1481
+ // the assignment had on other attributes of the same object) — the
1482
+ // override panel stays open on the same attribute (debuggerSelectedAttr
1483
+ // is unchanged) so applying again is a tight loop.
1484
+ withPreservedDebuggerScroll(() => renderDebuggerAttributesDetail(debuggerActiveTab, debuggerSelectedItem));
1485
+ }
1486
+
1487
+ // Re-queries the DOM fresh rather than capturing element references once at
1488
+ // the start of a run — the detail panel can be rebuilt from scratch one or
1489
+ // more times while a walkthrough is running (closing/reopening the dialog,
1490
+ // see wireDebuggerButton's doc comment), which would otherwise leave a
1491
+ // stale/detached reference that no longer matches anything visible.
1492
+ // [data-walkthrough-status]/[data-cancel-walkthrough] aren't name-scoped
1493
+ // (only one detail panel exists at a time), so they're only touched when the
1494
+ // panel currently on screen is actually still showing this walkthrough —
1495
+ // otherwise the status of a *different* walkthrough the user has since
1496
+ // selected would get clobbered.
1497
+ function updateWalkthroughRunUi(name, { running, status }) {
1498
+ const runBtn = document.querySelector(`[data-run-walkthrough="${CSS.escape(name)}"]`);
1499
+ if (runBtn) runBtn.disabled = running;
1500
+
1501
+ if (debuggerActiveTab !== 'Walkthrough' || debuggerSelectedItem !== name) return;
1502
+ const cancelBtn = document.querySelector('[data-cancel-walkthrough]');
1503
+ const statusEl = document.querySelector('[data-walkthrough-status]');
1504
+ if (cancelBtn) cancelBtn.classList.toggle('hidden', !running);
1505
+ if (statusEl) statusEl.textContent = status;
1506
+ }
1507
+
1508
+ async function runSelectedWalkthrough(name) {
1509
+ runningWalkthroughName = name;
1510
+ updateWalkthroughRunUi(name, { running: true, status: 'Running…' });
1511
+ try {
1512
+ const error = await Bridge.RunWalkthrough(name);
1513
+ updateWalkthroughRunUi(name, { running: false, status: error ? `Error: ${error}` : 'Done' });
1514
+ } finally {
1515
+ runningWalkthroughName = null;
1516
+ }
1517
+ }
1518
+
1519
+ function ensureDebuggerWired() {
1520
+ if (debuggerWired) return;
1521
+ debuggerWired = true;
1522
+
1523
+ const dlg = document.getElementById('questVivaDebugger');
1524
+ if (!dlg) return;
1525
+
1526
+ document.getElementById('qv-debugger-close').addEventListener('click', () => dlg.close());
1527
+
1528
+ // A *modal* dialog gets Escape-to-close for free (the browser fires a
1529
+ // native 'cancel' event); a non-modal one — which this now always is,
1530
+ // see wireDebuggerButton's doc comment — doesn't. Scoped to the dialog
1531
+ // itself (not a document-level listener) so it only fires while focus is
1532
+ // actually inside it, matching the native behavior it's standing in for
1533
+ // and leaving Escape free to do whatever it already does elsewhere
1534
+ // (e.g. _waitMode's body-level handler in playercore.js) the rest of the
1535
+ // time.
1536
+ dlg.addEventListener('keydown', (e) => {
1537
+ if (e.key === 'Escape') dlg.close();
1538
+ });
1539
+
1540
+ // Only needs setting once — #qv-debugger-list itself is never rebuilt
1541
+ // (only its innerHTML, by renderDebuggerList), so this inline width
1542
+ // survives every re-render and even a game restart (the dialog is on
1543
+ // swapInPlayerUi's preserve-list). Subsequent changes come from dragging
1544
+ // the splitter (wireDebuggerSplitter).
1545
+ document.getElementById('qv-debugger-list').style.width = `${debuggerListWidth}px`;
1546
+
1547
+ wireDebuggerMoveResize();
1548
+ wireDebuggerSplitter();
1549
+ document.getElementById('qv-debugger-detail').addEventListener('pointerdown', wireDebuggerColumnResize);
1550
+
1551
+ // Keep the dialog on-screen through a live resize/orientation change
1552
+ // (e.g. rotating a phone) too, not just the next reopen — applyDebuggerRect
1553
+ // re-clamps debuggerRect to whatever the viewport is now. Only while the
1554
+ // dialog is actually open; otherwise this would silently reset a resized
1555
+ // dialog's geometry every time the window resizes for an unrelated reason.
1556
+ window.addEventListener('resize', () => {
1557
+ if (dlg.open) applyDebuggerRect();
1558
+ });
1559
+
1560
+ document.getElementById('qv-debugger-tabs').addEventListener('click', (e) => {
1561
+ const btn = e.target.closest('[data-tab]');
1562
+ if (btn) selectDebuggerTab(btn.dataset.tab);
1563
+ });
1564
+
1565
+ document.getElementById('qv-debugger-list').addEventListener('click', (e) => {
1566
+ const btn = e.target.closest('[data-item]');
1567
+ if (!btn) return;
1568
+ debuggerSelectedItem = btn.dataset.item;
1569
+ debuggerSelectedAttr = null;
1570
+ // Fresh sort/search state for whichever object was just selected —
1571
+ // a leftover filter/sort from the previous object would otherwise
1572
+ // silently carry over and could hide attributes the user expects
1573
+ // to see (e.g. a search term that happens to match nothing here).
1574
+ debuggerAttrSort = { column: 'attribute', direction: 'asc' };
1575
+ debuggerAttrSearch = '';
1576
+ renderDebuggerList();
1577
+ renderDebuggerDetail();
1578
+ });
1579
+
1580
+ document.getElementById('qv-debugger-detail').addEventListener('click', async (e) => {
1581
+ // A completed column-resize drag (pointerdown+move+pointerup on
1582
+ // [data-resize-col], handled separately above) still fires a
1583
+ // trailing click on whatever's underneath — swallow it here so it
1584
+ // doesn't also toggle that column's sort direction.
1585
+ if (e.target.closest('[data-resize-col]')) return;
1586
+
1587
+ const sortCol = e.target.closest('[data-sort-col]');
1588
+ if (sortCol) {
1589
+ const col = sortCol.dataset.sortCol;
1590
+ debuggerAttrSort = debuggerAttrSort.column === col
1591
+ ? { column: col, direction: debuggerAttrSort.direction === 'asc' ? 'desc' : 'asc' }
1592
+ : { column: col, direction: 'asc' };
1593
+ renderDebuggerAttrRows();
1594
+ return;
1595
+ }
1596
+
1597
+ const attrRow = e.target.closest('[data-attr-row]');
1598
+ if (attrRow) {
1599
+ debuggerSelectedAttr = attrRow.dataset.attrRow;
1600
+ renderDebuggerAttrRows();
1601
+ renderDebuggerOverridePanel(debuggerSelectedAttr, debuggerAttrData[debuggerSelectedAttr]);
1602
+ return;
1603
+ }
1604
+
1605
+ if (e.target.closest('#qv-debugger-override-apply')) {
1606
+ const input = document.getElementById('qv-debugger-override-input');
1607
+ await applyDebugAttribute(debuggerSelectedAttr, input ? input.value : '');
1608
+ return;
1609
+ }
1610
+
1611
+ const runBtn = e.target.closest('[data-run-walkthrough]');
1612
+ if (runBtn) {
1613
+ await runSelectedWalkthrough(runBtn.dataset.runWalkthrough);
1614
+ return;
1615
+ }
1616
+
1617
+ if (e.target.closest('[data-cancel-walkthrough]')) {
1618
+ Bridge.CancelWalkthrough();
1619
+ }
1620
+ });
1621
+ }
1622
+
1623
+ // Called after every WebPlayer.initUI() — #cmdDebug is part of playercore.htm,
1624
+ // which is fully replaced on every boot/restart (see swapInPlayerUi), so its
1625
+ // showModal() listener (wired in the shared playercore.js) is fresh each time
1626
+ // and this "populate on open" listener needs re-attaching alongside it.
1627
+ function wireDebuggerButton() {
1628
+ const cmdDebug = document.getElementById('cmdDebug');
1629
+ if (!cmdDebug) return;
1630
+ cmdDebug.addEventListener('click', () => {
1631
+ // playercore.js's own click listener (registered first — see this
1632
+ // function's doc comment — and shared with WebPlayer, whose separate
1633
+ // Blazor Debugger.razor still wants the native modal behavior it
1634
+ // gives) has already opened this as a *modal* dialog by the time
1635
+ // this listener runs. Reopen it non-modally instead of touching that
1636
+ // shared file: unlike WebPlayer's dialog, this one is resizable and
1637
+ // movable (wireDebuggerMoveResize) rather than a fixed centered
1638
+ // overlay, so keeping it modal only got in the way of the thing a
1639
+ // dev tool window is actually for — leaving it open while still
1640
+ // playing (refreshDebuggerAfterTurn keeps it in sync as turns
1641
+ // happen). close()+show() in the same synchronous click handler,
1642
+ // before the browser gets a chance to paint the modal state — same
1643
+ // reasoning as applyDebuggerRect's doc comment — so there's no
1644
+ // visible flash of the modal backdrop.
1645
+ const dlg = document.getElementById('questVivaDebugger');
1646
+ dlg.close();
1647
+ dlg.show();
1648
+ ensureDebuggerWired();
1649
+ applyDebuggerRect();
1650
+ debuggerActiveTab = 'Walkthrough';
1651
+ // If a walkthrough is running (started on a previous open of this
1652
+ // dialog, which fully rebuilds #qv-debugger-detail on every open —
1653
+ // see runningWalkthroughName's doc comment), jump straight to it so
1654
+ // its Running…/Cancel state is immediately visible again, rather
1655
+ // than resetting to a blank "Select an item to view details."
1656
+ debuggerSelectedItem = runningWalkthroughName;
1657
+ debuggerSelectedAttr = null;
1658
+ renderDebuggerTabs(JSON.parse(Bridge.GetDebuggerObjectTypesJson()));
1659
+ renderDebuggerList();
1660
+ renderDebuggerDetail();
1661
+ });
1662
+ }
1663
+
1664
+ // Editor-preview sessions hide the Save button entirely (see
1665
+ // setCanSave(!isPreview) above) — and "Start from the beginning"/Load only
1666
+ // ever lived inside the Save/Load dialog that button opens — so a preview
1667
+ // session had no way to restart the game at all. Adds a plain "Restart"
1668
+ // button next to Debug instead, calling restartGame(null) directly (same
1669
+ // as "Start from the beginning", no confirmation there either).
1670
+ //
1671
+ // #cmdDebug (and this button, once created) is part of playercore.htm,
1672
+ // fully replaced on every boot/restart (see swapInPlayerUi) — so unlike
1673
+ // wireDebuggerButton, which just re-attaches a listener to whatever
1674
+ // #cmdDebug currently exists, this recreates the button itself from scratch
1675
+ // every time, since the old one (if any) was just destroyed along with the
1676
+ // rest of the previous playercore.htm content.
1677
+ function wireDebuggerRestartButton(isPreview) {
1678
+ const cmdDebug = document.getElementById('cmdDebug');
1679
+ if (!cmdDebug || !isPreview) return;
1680
+
1681
+ const cmdRestart = document.createElement('button');
1682
+ cmdRestart.id = 'cmdRestart';
1683
+ cmdRestart.type = 'button';
1684
+ cmdRestart.textContent = 'Restart';
1685
+ cmdRestart.addEventListener('click', (e) => {
1686
+ // Unlike #qv-saves-start-new (inside #qv-saves, which survives
1687
+ // swapInPlayerUi untouched — see restartGameCore), this button is
1688
+ // itself destroyed almost immediately by swapInPlayerUi and only
1689
+ // recreated near the end of restartGameCore, so there's no "restore
1690
+ // it afterward" state worth preserving the way withBusyButton does
1691
+ // elsewhere — just disable it synchronously so a double-click fired
1692
+ // in the same tick (before the DOM swap actually runs) doesn't
1693
+ // start a second restart. restartGame's restartInProgress guard is
1694
+ // the real protection against overlapping restarts either way.
1695
+ e.currentTarget.disabled = true;
1696
+ restartGame(null);
1697
+ });
1698
+ cmdDebug.insertAdjacentElement('afterend', cmdRestart);
1699
+ // Matches the jQuery UI ".ui-button" look cmdDebug/cmdSave already have
1700
+ // (applied to them by initPlayerUI's "$('#gameBorder button').button()"
1701
+ // — which already ran by the time this is called, so it never touches
1702
+ // this button; do it explicitly here instead).
1703
+ $(cmdRestart).button();
1704
+ }
1705
+
1706
+ // Nothing here can ever work over file:// — the runtime fetches its own
1707
+ // resources (playercore.htm, the dotnet WASM runtime) via relative URLs,
1708
+ // and browsers refuse those fetches from a file: origin (each file: URL is
1709
+ // treated as a unique, opaque origin with no ability to fetch even its own
1710
+ // sibling files). Caught up front, before any load is attempted, so the
1711
+ // user gets an accurate explanation instead of the generic "not a valid
1712
+ // game file" message that fetch failures would otherwise produce.
1713
+ function showFileProtocolError() {
1714
+ document.documentElement.classList.remove('qv-booting');
1715
+ const pickers = document.getElementById('qv-pickers');
1716
+ const msg = document.getElementById('qv-loading-msg');
1717
+ const errorEl = document.getElementById('qv-error');
1718
+ if (msg) msg.style.display = 'none';
1719
+ if (pickers) pickers.style.display = 'none';
1720
+ if (!errorEl) return;
1721
+ errorEl.innerHTML = '<strong>This can\'t run from a local file.</strong> '
1722
+ + 'You\'ve opened index.html directly from disk (a file:// address). Browsers block the web features this '
1723
+ + 'player needs &mdash; fetching its own files and running WebAssembly &mdash; when a page is loaded that way, '
1724
+ + 'so no game will load no matter which one you pick. '
1725
+ + 'Serve this folder over http(s) instead: for example, run <code>npx serve</code> in this folder and open '
1726
+ + 'the http://localhost address it prints, or upload the files to any web host.';
1727
+ errorEl.style.display = 'block';
1728
+ }
1729
+
1730
+ // The AppShell tab that was going to hand over game bytes (see the
1731
+ // `source=local` boot branch below) turned out not to be there to answer —
1732
+ // closed, navigated away, or superseded by a newer Start click in that same
1733
+ // tab (see PlayCatalog.svelte's handleBrowserStart, which closes its previous
1734
+ // channel before opening a new one). Without this, that's a silent infinite
1735
+ // loading spinner with no way out; this at least gets the user back to a
1736
+ // working picker in the same tab.
1737
+ function showLocalHandoffTimeoutError() {
1738
+ document.documentElement.classList.remove('qv-booting');
1739
+ const pickers = document.getElementById('qv-pickers');
1740
+ const msg = document.getElementById('qv-loading-msg');
1741
+ const errorEl = document.getElementById('qv-error');
1742
+ if (msg) msg.style.display = 'none';
1743
+ if (pickers) pickers.style.display = 'block';
1744
+ if (!errorEl) return;
1745
+ errorEl.innerHTML = '<strong>Couldn\'t reconnect to Quest Viva.</strong> '
1746
+ + 'This tab was waiting for a game from the Play tab it was opened from, but that tab has since been closed, '
1747
+ + 'navigated away, or used to start a different game. Choose the file again below, or go back to Quest Viva '
1748
+ + 'and click Start again.';
1749
+ errorEl.style.display = 'block';
1750
+ wireStartScreen();
1751
+ }
1752
+
1753
+ function showLoading() {
1754
+ const pickers = document.getElementById('qv-pickers');
1755
+ const msg = document.getElementById('qv-loading-msg');
1756
+ if (pickers) pickers.style.display = 'none';
1757
+ if (msg) msg.style.display = 'flex';
1758
+ }
1759
+
1760
+ // Maps an HTTP status code to a short, specific reason. Only used when the
1761
+ // fetch actually reached a server and got a response — a blocked/failed
1762
+ // fetch (CORS, DNS, offline) never gets this far and has no status at all.
1763
+ function _describeHttpStatus(status) {
1764
+ if (status === 404) return 'the file wasn\'t found there (404 Not Found)';
1765
+ if (status === 401 || status === 403) return `access to it was denied (${status})`;
1766
+ if (status >= 500) return `the server hosting it reported an error (HTTP ${status})`;
1767
+ if (status >= 400) return `the request was rejected (HTTP ${status})`;
1768
+ return `the server responded with HTTP ${status}`;
1769
+ }
1770
+
1771
+ function showError(downloadUrl, isLocalFile, error) {
1772
+ const pickers = document.getElementById('qv-pickers');
1773
+ const msg = document.getElementById('qv-loading-msg');
1774
+ const errorEl = document.getElementById('qv-error');
1775
+ if (msg) msg.style.display = 'none';
1776
+ // Explicit 'block' (not '') so this wins over the html.qv-booting CSS that
1777
+ // hides #qv-pickers by default when a game was specified on the URL — an
1778
+ // inline style always beats an external stylesheet rule, cleared or not.
1779
+ if (pickers) pickers.style.display = 'block';
1780
+ if (!errorEl) return;
1781
+ let html;
1782
+ if (isLocalFile) {
1783
+ html = '<strong>Couldn\'t open that file.</strong> '
1784
+ + 'It doesn\'t look like a Quest game file (.quest, .aslx, .asl or .cas). Choose a different file below.';
1785
+ } else if (Number.isInteger(error?.status)) {
1786
+ // We got a real HTTP response, so we know exactly why it failed —
1787
+ // no need to guess at CORS. downloadUrl may still be unknown here
1788
+ // (e.g. the TextAdventures API lookup itself 404'd before we ever
1789
+ // learned the game's source URL), so the link is optional.
1790
+ html = '<strong>Couldn\'t load the game.</strong> '
1791
+ + `When we asked for it, ${_describeHttpStatus(error.status)}. `
1792
+ + (downloadUrl
1793
+ ? '<a class="anchor" href="' + _esc(downloadUrl) + '" target="_blank" rel="noopener">'
1794
+ + 'Open the link</a> to double-check the URL, or load a saved copy with the file picker below.'
1795
+ : 'Double-check the address, or load a saved copy of the game file with the file picker below.');
1796
+ } else if (downloadUrl) {
1797
+ // fetch() itself failed before any response came back. The browser
1798
+ // gives no way to tell apart a CORS block, DNS failure, or being
1799
+ // offline in this case, so we can only name the likely suspects.
1800
+ html = '<strong>Couldn\'t load the game from that URL.</strong> '
1801
+ + 'This is usually because the site hosting it isn\'t configured to allow other sites to fetch the file directly '
1802
+ + '(a CORS restriction), but it could also be a network problem or a bad address '
1803
+ + '&mdash; this is a limitation of the hosting site or your connection, not something wrong with your download. '
1804
+ + '<a class="anchor" href="' + _esc(downloadUrl) + '" target="_blank" rel="noopener">'
1805
+ + 'Open the file in a new tab</a>, save it to your computer, then load it with the file picker below.';
1806
+ } else {
1807
+ html = '<strong>Couldn\'t load the game.</strong> '
1808
+ + 'Try opening a saved copy of the game file instead, using the file picker below.';
1809
+ }
1810
+ errorEl.innerHTML = html;
1811
+ // 'block', not '' — errorEl carries the .hidden class, so clearing the
1812
+ // inline style would fall back to that (display:none) instead of showing.
1813
+ errorEl.style.display = 'block';
1814
+ wireStartScreen();
1815
+ }
1816
+
1817
+ // Keeps the address bar in sync with the game that's actually loaded (or being
1818
+ // attempted), so a refresh reproduces it. `name`/`value` set the active source
1819
+ // param; both `id` and `url` are cleared first since only one can be current.
1820
+ function setLocationParam(name, value) {
1821
+ const params = new URLSearchParams(window.location.search);
1822
+ params.delete('id');
1823
+ params.delete('url');
1824
+ if (name) params.set(name, value);
1825
+ const query = params.toString();
1826
+ const newUrl = window.location.pathname + (query ? `?${query}` : '') + window.location.hash;
1827
+ history.replaceState(null, '', newUrl);
1828
+ }
1829
+
1830
+ let _startScreenWired = false;
1831
+ function wireStartScreen() {
1832
+ if (_startScreenWired) return;
1833
+ _startScreenWired = true;
1834
+
1835
+ const fileBtn = document.getElementById('qv-file-btn');
1836
+ const fileInput = document.getElementById('qv-file-input');
1837
+ const urlInput = document.getElementById('qv-url-input');
1838
+ const urlBtn = document.getElementById('qv-url-btn');
1839
+ if (!fileBtn) return;
1840
+
1841
+ fileBtn.addEventListener('click', () => fileInput.click());
1842
+ fileInput.addEventListener('change', () => {
1843
+ const file = fileInput.files?.[0];
1844
+ if (!file) return;
1845
+ setLocationParam(null);
1846
+ showLoading();
1847
+ const reader = new FileReader();
1848
+ reader.onload = () => startGame(new Uint8Array(reader.result), file.name)
1849
+ .catch(() => showError(null, true));
1850
+ reader.readAsArrayBuffer(file);
1851
+ });
1852
+
1853
+ async function doLoadUrl() {
1854
+ const url = urlInput.value.trim();
1855
+ if (!url) return;
1856
+ const errorEl = document.getElementById('qv-error');
1857
+ if (errorEl) errorEl.style.display = 'none';
1858
+ showLoading();
1859
+ try {
1860
+ const { bytes, filename } = await fetchGameBytes(url);
1861
+ await startGame(bytes, filename);
1862
+ setLocationParam('url', url);
1863
+ } catch (err) {
1864
+ showError(url, false, err);
1865
+ }
1866
+ }
1867
+ urlBtn.addEventListener('click', doLoadUrl);
1868
+ urlInput.addEventListener('keydown', e => { if (e.key === 'Enter') doLoadUrl(); });
1869
+ }
1870
+
1871
+ async function fetchGameBytes(url) {
1872
+ const response = await fetch(url);
1873
+ if (!response.ok) {
1874
+ const err = new Error(`HTTP ${response.status}`);
1875
+ err.status = response.status;
1876
+ throw err;
1877
+ }
1878
+ const bytes = new Uint8Array(await response.arrayBuffer());
1879
+ let filename = (response.url || url).split('/').pop()?.split('?')[0] || 'game.aslx';
1880
+ // dev-server.mjs's CORS-avoidance proxy rewrites the Text Adventures API's
1881
+ // sourceGameUrl to /game-resource/<url-encoded-real-url>, so the "last
1882
+ // segment" above is that encoded string, not a real filename, in local
1883
+ // dev only. Detect and decode so the derived filename (used both for
1884
+ // GameLauncher's extension-based dispatch and the save-file "original"
1885
+ // cross-check) matches what production — no proxy — actually produces.
1886
+ try {
1887
+ const decoded = decodeURIComponent(filename);
1888
+ if (decoded !== filename && decoded.includes('/')) {
1889
+ filename = decoded.split('/').pop()?.split('?')[0] || filename;
1890
+ }
1891
+ } catch { /* not a valid encoded URL, keep filename as-is */ }
1892
+ return { bytes, filename };
1893
+ }
1894
+
1895
+ // ── Boot ─────────────────────────────────────────────────────────────────────
1896
+
1897
+ (function () {
1898
+ if (window.location.protocol === 'file:') {
1899
+ document.addEventListener('DOMContentLoaded', showFileProtocolError);
1900
+ return;
1901
+ }
1902
+
1903
+ // Single-file export (see scripts/export-embedded.mjs): the game bytes are
1904
+ // inlined as base64 by a <script> tag before this one, so there's nothing
1905
+ // to fetch at all — decode and hand straight to the same startGame() every
1906
+ // other boot source converges on. Checked first since, unlike the sources
1907
+ // below, an embedded export never carries any of their query params.
1908
+ if (window.QuestVivaEmbeddedGame) {
1909
+ const bytes = Uint8Array.from(atob(window.QuestVivaEmbeddedGame), c => c.charCodeAt(0));
1910
+ const filename = window.QuestVivaEmbeddedGameFilename || 'game.quest';
1911
+ document.addEventListener('DOMContentLoaded', async () => {
1912
+ showLoading();
1913
+ await startGame(bytes, filename);
1914
+ });
1915
+ return;
1916
+ }
1917
+
1918
+ const params = new URLSearchParams(window.location.search);
1919
+
1920
+ if (params.get('source') === 'editor') {
1921
+ const bc = new BroadcastChannel('quest-preview');
1922
+ bc.postMessage({ type: 'ready' });
1923
+ bc.onmessage = async ({ data }) => {
1924
+ if (data.type === 'game') {
1925
+ bc.onmessage = null;
1926
+ await startGame(data.bytes, data.filename, bc, null, true, data.recordWalkthrough ?? null, data.runWalkthrough ?? null);
1927
+ }
1928
+ };
1929
+ return;
1930
+ }
1931
+
1932
+ // AppShell's Play tab (see PlayCatalog.svelte) — the user already picked
1933
+ // a file and clicked Start (browser build) or the window just got opened
1934
+ // straight from the file picker (Electron, see ipc/player.ts), so the
1935
+ // game bytes are sitting in that tab's memory. Same handoff as the editor
1936
+ // preview above, including resource-request support: in the browser
1937
+ // build a raw picked File has nothing to answer those with (so they just
1938
+ // go unanswered — fine for a self-contained .quest package, which is all
1939
+ // the plain file-input path in wireStartScreen() below ever supported
1940
+ // either), but Electron's local-play.ts backs the picked file with a
1941
+ // real ElectronFileAdapter and answers them from disk, exactly like
1942
+ // editor-store.ts's previewInWasmPlayer does for the live editor. A
1943
+ // distinct channel name keeps this from cross-talking with a real
1944
+ // editor-preview tab open at the same time.
1945
+ if (params.get('source') === 'local') {
1946
+ const bc = new BroadcastChannel('quest-play-local');
1947
+ bc.postMessage({ type: 'ready' });
1948
+ // Covers the case where nothing ever answers — see
1949
+ // showLocalHandoffTimeoutError. 8s comfortably covers a normal
1950
+ // same-tick reply; DOMContentLoaded hasn't necessarily fired yet
1951
+ // when this timer is *set*, but it always has by the time it fires.
1952
+ const timeoutId = window.setTimeout(() => {
1953
+ bc.onmessage = null;
1954
+ bc.close();
1955
+ showLocalHandoffTimeoutError();
1956
+ }, 8000);
1957
+ bc.onmessage = async ({ data }) => {
1958
+ if (data.type === 'game') {
1959
+ window.clearTimeout(timeoutId);
1960
+ // Not closed (unlike the timeout branch above) — startGame
1961
+ // reassigns bc.onmessage itself to keep answering
1962
+ // 'resource-response' messages for the rest of the session.
1963
+ bc.onmessage = null;
1964
+ await startGame(data.bytes, data.filename, bc);
1965
+ }
1966
+ };
1967
+ return;
1968
+ }
1969
+
1970
+ const id = params.get('id');
1971
+ // A URL-supplied game always wins over the configured default, so authors
1972
+ // testing/sharing a specific ?url= link aren't stuck on their own game.
1973
+ const gameUrl = params.get('url') || window.QuestVivaConfig?.defaultGameUrl;
1974
+
1975
+ if (id) {
1976
+ // Start API fetch immediately; wire DOM once it's ready.
1977
+ let resolvedSourceUrl = null;
1978
+ const gamePromise = (async () => {
1979
+ const apiRoot = window.QuestVivaConfig?.textAdventuresApiRoot
1980
+ ?? 'https://textadventures.co.uk/api/';
1981
+ const apiResponse = await fetch(`${apiRoot}game/${id}?${clientInfoParams()}`);
1982
+ if (!apiResponse.ok) {
1983
+ const err = new Error(`API: HTTP ${apiResponse.status}`);
1984
+ err.status = apiResponse.status;
1985
+ throw err;
1986
+ }
1987
+ const { sourceGameUrl, resourceRoot: resRoot } = await apiResponse.json();
1988
+ resolvedSourceUrl = sourceGameUrl;
1989
+ resourceRoot = resRoot || null;
1990
+ const { bytes, filename } = await fetchGameBytes(sourceGameUrl);
1991
+ return { bytes, filename };
1992
+ })();
1993
+
1994
+ document.addEventListener('DOMContentLoaded', async () => {
1995
+ showLoading();
1996
+ try {
1997
+ const { bytes, filename } = await gamePromise;
1998
+ await startGame(bytes, filename, null, id);
1999
+ } catch (err) {
2000
+ showError(resolvedSourceUrl, false, err);
2001
+ }
2002
+ });
2003
+ return;
2004
+ }
2005
+
2006
+ if (gameUrl) {
2007
+ // Start fetch immediately; wire DOM once it's ready.
2008
+ const gamePromise = fetchGameBytes(gameUrl);
2009
+
2010
+ document.addEventListener('DOMContentLoaded', async () => {
2011
+ showLoading();
2012
+ try {
2013
+ const { bytes, filename } = await gamePromise;
2014
+ await startGame(bytes, filename);
2015
+ } catch (err) {
2016
+ showError(gameUrl, false, err);
2017
+ }
2018
+ });
2019
+ return;
2020
+ }
2021
+
2022
+ // No game specified — show start screen and wire up controls.
2023
+ document.addEventListener('DOMContentLoaded', wireStartScreen);
2024
+ })();