@wildshard/engine 0.1.15 → 0.1.18

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 (262) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/index.html +157 -11
  3. package/lint/engine-sides.json +23 -0
  4. package/lint/host-callback-syntax.mjs +2 -1
  5. package/lint/host-callbacks.mjs +3 -3
  6. package/lint/host-files.mjs +5 -4
  7. package/lint/host-register.json +496 -0
  8. package/lint/no-base64.mjs +3 -1
  9. package/lint/ratchet.json +2 -2
  10. package/lint/shard-imports.d.mts +1 -0
  11. package/lint/shard-imports.mjs +60 -13
  12. package/lint/shard-source.d.mts +9 -0
  13. package/lint/shard-source.mjs +91 -0
  14. package/lint/shardfile-boundaries.mjs +10 -8
  15. package/lint/sim-closure.mjs +6 -3
  16. package/lint/wildshard-plugin.d.ts +4 -0
  17. package/lint/wildshard-plugin.js +44 -27
  18. package/package.json +24 -6
  19. package/scripts/app-build/buildIdentity.d.mts +3 -1
  20. package/scripts/app-build/buildIdentity.mjs +25 -5
  21. package/scripts/app-build/builtAt.d.mts +4 -0
  22. package/scripts/app-build/builtAt.mjs +21 -0
  23. package/scripts/app-build/outputProducts.d.mts +3 -0
  24. package/scripts/app-build/outputProducts.mjs +31 -0
  25. package/scripts/app-build/serviceWorker.ts +16 -2
  26. package/scripts/app-build/versionFiles.ts +2 -1
  27. package/scripts/app-build-pipeline.mjs +7 -1
  28. package/scripts/audio-download-proof.mjs +843 -0
  29. package/scripts/build-app.mjs +4 -0
  30. package/scripts/build-mirror.d.mts +2 -0
  31. package/scripts/build-mirror.mjs +5 -4
  32. package/scripts/built-product.mjs +3 -3
  33. package/scripts/cell-mem/metrics-preload.mjs +65 -0
  34. package/scripts/cell-mem-bench.mjs +130 -0
  35. package/scripts/check-chunks.mjs +2 -1
  36. package/scripts/check-devserver.mjs +1 -1
  37. package/scripts/chromium-keychain-check.mjs +4 -2
  38. package/scripts/chromium-keychain.mjs +3 -1
  39. package/scripts/cook.mjs +7 -3
  40. package/scripts/devices.d.mts +4 -0
  41. package/scripts/devices.mjs +39 -0
  42. package/scripts/devserver-client.d.mts +7 -0
  43. package/scripts/devserver-client.mjs +85 -0
  44. package/scripts/doctor-proof.mjs +1 -1
  45. package/scripts/e2e-faults.mjs +159 -0
  46. package/scripts/engine-ci-budget.ts +7 -1
  47. package/scripts/format-lock.mjs +20 -11
  48. package/scripts/generate-title-launch.mjs +3 -2
  49. package/scripts/grid-crossing-walk-proof.mjs +30 -11
  50. package/scripts/heavy-lane.py +25 -1
  51. package/scripts/host-ruler/register-migrate.mjs +242 -0
  52. package/scripts/host-ruler/register.d.mts +36 -0
  53. package/scripts/host-ruler/register.mjs +116 -0
  54. package/scripts/host-ruler/roots.d.mts +29 -0
  55. package/scripts/host-ruler/roots.mjs +333 -0
  56. package/scripts/host-ruler/server-roots.d.mts +23 -0
  57. package/scripts/host-ruler/server-roots.mjs +272 -0
  58. package/scripts/main-watch.d.mts +1 -1
  59. package/scripts/main-watch.mjs +10 -6
  60. package/scripts/map-hash.mjs +3 -6
  61. package/scripts/memory-proof.mjs +158 -0
  62. package/scripts/mmo-bots.mjs +2 -2
  63. package/scripts/offline-proof-rules.d.mts +5 -2
  64. package/scripts/offline-proof-rules.mjs +43 -6
  65. package/scripts/offline-proof.mjs +15 -6
  66. package/scripts/online-rig.mjs +4 -4
  67. package/scripts/page-release/flow.d.mts +1 -0
  68. package/scripts/page-release/flow.mjs +6 -2
  69. package/scripts/page-release.mjs +5 -1
  70. package/scripts/physics-route.json +0 -71
  71. package/scripts/pins-catalogue.ts +103 -0
  72. package/scripts/pins-reuse.mjs +3 -1
  73. package/scripts/pins.ts +22 -14
  74. package/scripts/preview-grid.ts +203 -0
  75. package/scripts/road-preload-proof.mjs +167 -0
  76. package/scripts/server-release/publish.mjs +2 -2
  77. package/scripts/server-release/served-slug.d.mts +2 -0
  78. package/scripts/server-release/served-slug.mjs +10 -0
  79. package/scripts/server-release/sign.d.mts +1 -0
  80. package/scripts/server-release/sign.mjs +3 -7
  81. package/scripts/shard-components.mjs +0 -2
  82. package/scripts/shard-outputs.d.mts +8 -0
  83. package/scripts/shard-outputs.mjs +45 -11
  84. package/scripts/side-parity.d.mts +2 -1
  85. package/scripts/side-parity.mjs +25 -4
  86. package/scripts/test-amber.d.mts +1 -0
  87. package/scripts/test-amber.mjs +10 -0
  88. package/scripts/test-products.json +3 -3
  89. package/scripts/tier-textures-proof.mjs +101 -0
  90. package/scripts/tier-textures.mjs +60 -0
  91. package/scripts/tracked-public.d.mts +1 -0
  92. package/scripts/tracked-public.mjs +17 -0
  93. package/scripts/tsconfig.json +1 -0
  94. package/scripts/vps/wildshard-config +79 -23
  95. package/scripts/worker-client-play.mjs +1 -0
  96. package/scripts/worker-client-proof.mjs +1 -1
  97. package/scripts/worker-client-slug.mjs +44 -0
  98. package/src/cli/engine.mjs +8 -0
  99. package/src/client/app/bootRoute.ts +4 -1
  100. package/src/client/app/dropModal.ts +15 -2
  101. package/src/client/app/entry.ts +96 -13
  102. package/src/client/app/slugPath.ts +5 -0
  103. package/src/client/engine/audio/Audio.ts +20 -2
  104. package/src/client/engine/boot/bakedTextures.ts +3 -2
  105. package/src/client/engine/boot/bootTrace.ts +6 -1
  106. package/src/client/engine/boot/bytes.ts +4 -3
  107. package/src/client/engine/boot/clearDownloads.ts +1 -1
  108. package/src/client/engine/boot/contentRead.ts +4 -0
  109. package/src/client/engine/boot/dropNotice.ts +20 -6
  110. package/src/client/engine/boot/gpuFiles.ts +25 -2
  111. package/src/client/engine/boot/lastEnd.ts +8 -2
  112. package/src/client/engine/boot/parsedPages.ts +127 -58
  113. package/src/client/engine/boot/shardPrefetch.ts +7 -1
  114. package/src/client/engine/boot/sw.ts +19 -0
  115. package/src/client/engine/build.d.ts +2 -0
  116. package/src/client/engine/core/Game.ts +29 -3
  117. package/src/client/engine/core/GpuRecovery.ts +7 -0
  118. package/src/client/engine/core/Volumetrics.ts +5 -0
  119. package/src/client/engine/core/assets.ts +27 -20
  120. package/src/client/engine/core/bootstrap.ts +5 -3
  121. package/src/client/engine/core/ktx2.ts +84 -11
  122. package/src/client/engine/debug/probe.ts +18 -1
  123. package/src/client/engine/explore/Compare.ts +2 -2
  124. package/src/client/engine/explore/TouchFly.ts +3 -5
  125. package/src/client/engine/fx/LightPool.ts +41 -1
  126. package/src/client/engine/input/dom.ts +12 -0
  127. package/src/client/engine/net/predictor.ts +6 -2
  128. package/src/client/engine/player/Player.ts +10 -2
  129. package/src/client/engine/player/TouchControls.ts +12 -4
  130. package/src/client/engine/pwa/sw.js +59 -11
  131. package/src/client/engine/render/drawCheck.ts +96 -0
  132. package/src/client/engine/render/precompile.ts +20 -14
  133. package/src/client/engine/saves/staleBuildNote.ts +46 -0
  134. package/src/client/engine/telemetry/browserErrors.ts +161 -21
  135. package/src/client/engine/telemetry/deviceSnapshot.ts +155 -0
  136. package/src/client/engine/telemetry/screenOutbox.ts +61 -0
  137. package/src/client/engine/telemetry/staleBuildReport.ts +12 -0
  138. package/src/client/engine/ui/DeathFade.ts +99 -11
  139. package/src/client/engine/ui/ErrorModal.ts +13 -6
  140. package/src/client/engine/ui/Feedback.ts +2 -1
  141. package/src/client/engine/ui/Loading.ts +10 -6
  142. package/src/client/engine/ui/Map.ts +2 -1
  143. package/src/client/engine/ui/WeaponStrip.ts +2 -1
  144. package/src/client/engine/ui/backGuard.ts +104 -0
  145. package/src/client/engine/ui/hudAdapters.ts +30 -4
  146. package/src/client/engine/ui/loading.css +17 -0
  147. package/src/client/engine/ui/namePrompt.ts +6 -5
  148. package/src/client/engine/ui/styles/combat.css +12 -0
  149. package/src/client/engine/ui/styles/namePrompt.css +4 -2
  150. package/src/client/game/boot/audio.generated.ts +0 -396
  151. package/src/client/game/boot/bytes.generated.ts +42 -71
  152. package/src/client/game/boot/versions.generated.ts +0 -13
  153. package/src/client/game/compendium/keepsakes.ts +16 -6
  154. package/src/client/game/grapple/tool.ts +10 -7
  155. package/src/client/game/grid/area.ts +38 -0
  156. package/src/client/game/grid/cellLoading.ts +23 -12
  157. package/src/client/game/grid/cellScreens.ts +39 -74
  158. package/src/client/game/grid/live.ts +28 -2
  159. package/src/client/game/grid/liveSession.ts +54 -10
  160. package/src/client/game/grid/menu.ts +4 -0
  161. package/src/client/game/grid/nearPlaceholderPlan.ts +8 -0
  162. package/src/client/game/grid/nearPlaceholderView.ts +9 -3
  163. package/src/client/game/grid/neighbourPanels.ts +10 -1
  164. package/src/client/game/grid/oneWayIn.ts +92 -27
  165. package/src/client/game/grid/pageEntry.ts +19 -0
  166. package/src/client/game/grid/pageShell.ts +1 -1
  167. package/src/client/game/grid/placedCards.ts +55 -0
  168. package/src/client/game/grid/placedCells.ts +131 -0
  169. package/src/client/game/grid/plotAudio.ts +114 -0
  170. package/src/client/game/grid/products.ts +55 -5
  171. package/src/client/game/grid/regionalRuntime.ts +6 -0
  172. package/src/client/game/grid/regionalWorld.ts +15 -2
  173. package/src/client/game/grid/roadCull.ts +44 -14
  174. package/src/client/game/grid/roadLookPlatform.ts +2 -2
  175. package/src/client/game/grid/roadTileBacking.ts +13 -3
  176. package/src/client/game/grid/session.ts +47 -22
  177. package/src/client/game/grid/shardfileFar.ts +9 -3
  178. package/src/client/game/grid/spawnGround.ts +68 -0
  179. package/src/client/game/grid/voidLook.ts +29 -23
  180. package/src/client/game/loot/runtime.ts +3 -1
  181. package/src/client/game/mainMenu.ts +14 -6
  182. package/src/client/game/riding/hud.ts +6 -4
  183. package/src/client/game/session/finish.ts +22 -4
  184. package/src/client/game/session/play.ts +8 -2
  185. package/src/client/game/session/session.ts +4 -1
  186. package/src/client/game/shard/titleList.ts +6 -2
  187. package/src/client/game/shardfile/clientWorker.ts +43 -13
  188. package/src/client/game/shardfile/serverRoute.ts +10 -22
  189. package/src/client/game/slugPage.css +11 -0
  190. package/src/client/game/slugPage.ts +84 -0
  191. package/src/client/game/systems/viewmodel/heldView.ts +6 -3
  192. package/src/client/game/titleDeck.ts +56 -32
  193. package/src/client/host/online/doctor.ts +7 -6
  194. package/src/client/host/online/linkScreens.ts +16 -0
  195. package/src/client/host/online/release.ts +51 -5
  196. package/src/client/host/online/shell.ts +62 -27
  197. package/src/client/host/standalone/shell.ts +7 -3
  198. package/src/cook/game/audioReport.ts +57 -0
  199. package/src/cook/game/entryTotals.ts +26 -6
  200. package/src/cook/game/installedRuntimeReads.ts +3 -0
  201. package/src/cook/game/shardCook.ts +38 -8
  202. package/src/cook/game/tierTextures.ts +276 -0
  203. package/src/e2e/smoke/game.ts +19 -14
  204. package/src/e2e/smoke/page-globals.d.ts +9 -8
  205. package/src/e2e/smoke/template2.spec.ts +8 -7
  206. package/src/server/engine/sim/respawn.ts +6 -1
  207. package/src/server/engine/sim.ts +3 -0
  208. package/src/server/game/grid/simulation.ts +35 -0
  209. package/src/server/game/loot/harvest.ts +2 -0
  210. package/src/server/game/loot/keepsakeProgression.ts +40 -0
  211. package/src/server/game/loot/playerOwned.ts +5 -1
  212. package/src/server/game/plugin/simulation.ts +4 -0
  213. package/src/server/game/population/nativeBake.ts +2 -1
  214. package/src/server/game/quest/chapterRecords.ts +2 -0
  215. package/src/server/game/quest/serverChapters.ts +4 -0
  216. package/src/server/game/quest/serverDoors.ts +11 -5
  217. package/src/server/game/roomRespawn.ts +4 -0
  218. package/src/server/game/shardfile/installedSides.ts +18 -0
  219. package/src/server/game/shardfile/nativeAssemblyHosts.ts +19 -10
  220. package/src/server/game/shardfile/nativeAssemblyInput.ts +1 -4
  221. package/src/server/host/bake/headlessWorker.ts +5 -1
  222. package/src/server/host/dedicated/cellHost.ts +98 -29
  223. package/src/server/host/dedicated/cellProtocol.ts +11 -1
  224. package/src/server/host/dedicated/cellWorker.ts +9 -3
  225. package/src/server/host/dedicated/crossing.ts +6 -2
  226. package/src/server/host/dedicated/dedicatedRoom.ts +21 -8
  227. package/src/server/host/dedicated/gridCells.ts +52 -9
  228. package/src/server/host/dedicated/main.ts +31 -12
  229. package/src/server/host/dedicated/placementFile.ts +56 -0
  230. package/src/server/host/dedicated/releaseFile.ts +17 -10
  231. package/src/server/host/dedicated/roadRoom.ts +21 -5
  232. package/src/server/host/dedicated/socketTransport.ts +2 -1
  233. package/src/server/host/dedicated/workerTable.ts +13 -1
  234. package/src/server/host/dedicated/world.ts +111 -10
  235. package/src/server/host/headlessRuntime.ts +10 -5
  236. package/src/server/host/installers.ts +62 -0
  237. package/src/server/host/openWorld.ts +59 -0
  238. package/src/server/host/ropeDecks.ts +2 -0
  239. package/src/server/host/standalone/cellWorld.ts +25 -19
  240. package/src/server/host/standalone/fallFloor.ts +2 -2
  241. package/src/server/host/standalone/gridServer.ts +7 -4
  242. package/src/server/host/standalone/roadWorld.ts +41 -4
  243. package/src/shared/engine/audio/bootAudio.ts +33 -0
  244. package/src/shared/engine/level/spec.ts +3 -3
  245. package/src/shared/engine/net/acts.ts +3 -0
  246. package/src/shared/engine/net/deviceWord.ts +138 -0
  247. package/src/shared/engine/net/socketFrames.ts +7 -4
  248. package/src/shared/engine/physics/query.ts +27 -0
  249. package/src/shared/engine/physics/terrain.ts +19 -28
  250. package/src/shared/engine/saves/saves.lock.json +15 -0
  251. package/src/shared/engine/sim/actRoutes.ts +2 -0
  252. package/src/shared/game/compendium/keepsakeProgression.ts +24 -0
  253. package/src/shared/game/grid/catalogue.ts +12 -5
  254. package/src/shared/game/grid/catalogueSlot.ts +18 -0
  255. package/src/shared/game/grid/farProxy.ts +6 -5
  256. package/src/shared/game/grid/pageMode.ts +1 -1
  257. package/src/shared/game/grid/placementRows.ts +33 -0
  258. package/src/shared/game/grid/roadLayout.ts +26 -3
  259. package/src/shared/game/grid/singleplayer.json +0 -13
  260. package/src/shared/game/grid/voidFloor.ts +122 -0
  261. package/src/shared/game/strings.ts +15 -0
  262. package/src/shared/host/standalone/netInput.ts +2 -1
@@ -1,7 +1,10 @@
1
1
  import { Scope } from '../../../shared/engine/app/scope';
2
2
  import { harnessPins, installedIdentity } from '../../../shared/engine/app/identity';
3
+ import { pageScope } from '../../../shared/engine/app/resources';
4
+ import { jsonSlot, type Json } from '../saves/slots';
3
5
  /** Optional, error-only Sentry channel. The existing /api/errors report remains the primary local inbox. */
4
6
  import type { captureException, ErrorEvent, getClient, httpContextIntegration, init, withScope } from '@sentry/browser';
7
+ import type { StaleBuildNote } from '../saves/staleBuildNote';
5
8
 
6
9
  declare const __BUILD_ID__: string;
7
10
  /** vite.config.ts: package.json's version (scripts/changelog.mjs); absent under Node */
@@ -15,8 +18,28 @@ export interface BrowserErrorTags {
15
18
  readonly fatal: boolean;
16
19
  /** Small, explicit diagnostics supplied by the caller; never browser storage or request headers. */
17
20
  readonly diagnostic?: Record<string, unknown>;
21
+ /** SENTRY-TRIAGE S13: the error screen this report opened. Set only by the call that opens it, so each screen is one event. */
22
+ readonly screen?: ErrorScreen;
18
23
  }
19
24
 
25
+ /**
26
+ * SENTRY-TRIAGE S13 (Jake, 2026-11-13: "Every time an error modal opens, are we writing something to Sentry that we can pull down and
27
+ * audit?"): every screen a player sees that means something went wrong, as its Sentry `screen` tag. Query: `screen:title-drop`.
28
+ * error-modal the fatal modal (src/client/engine/ui/ErrorModal.ts showFatal: a fault, the boot failed, Developer's every error)
29
+ * stuck-step the same modal opened by the stuck-step watchdog (showError with S4's stall, src/client/app/entry.ts)
30
+ * glitch-chip "A glitch was reported" (ErrorModal.ts showChip, once a session)
31
+ * load-failure the shard's load-failure page (src/client/engine/ui/errorScreen.ts showLoadFailure, src/client/game/session/session.ts)
32
+ * title-drop the drop modal, "Unexpectedly back at the title" (src/client/app/dropModal.ts showDropModal)
33
+ * link-lost the online stop card "Couldn't reconnect" (src/client/host/online/linkScreens.ts)
34
+ * link-refused the online stop card "The world turned this connection away" (the same file)
35
+ * stale-build the stale-build screen (index.html data-stale-build, STALE-BUILD SB6), reported by the next build that boots
36
+ * (telemetry/staleBuildReport.ts) since that page stops before Sentry can load
37
+ * Not screens of a fault, so never reported: the player's own reload, back or exit (QA 11-12 row 35), "Playing somewhere else",
38
+ * "The world is full", the reconnect banner (counted in `net` telemetry), title refusal lines and the Connection doctor.
39
+ */
40
+ export const ERROR_SCREENS = ['error-modal', 'stuck-step', 'glitch-chip', 'load-failure', 'title-drop', 'link-lost', 'link-refused', 'stale-build'] as const;
41
+ export type ErrorScreen = typeof ERROR_SCREENS[number];
42
+
20
43
  // A DSN is a public browser endpoint, not an auth token. Only real production pages report.
21
44
  const productionDsn = 'https://ccaf25bcd6baa389433fb9efe0117c9b@o4512161165410304.ingest.us.sentry.io/4512161184088064';
22
45
  const dsn = String(import.meta.env['VITE_SENTRY_DSN'] ?? (import.meta.env.PROD ? productionDsn : '')).trim();
@@ -34,6 +57,9 @@ export function browserErrorDist(build: string): string | undefined {
34
57
  return build !== '' && build.length <= 64 ? build : undefined;
35
58
  }
36
59
  let sdk: Promise<BrowserSdk | null> | null = null;
60
+ /** S13: deliveries waiting on an event that beforeSend refused (noise, a page that stopped reporting): that event is done, not owed */
61
+ const refusedListeners = new Set<(id: string) => void>();
62
+ const refused = (id: string | undefined): null => { for (const listener of refusedListeners) listener(id ?? ''); return null; };
37
63
 
38
64
  /** External error delivery is opt-in by exact app origin and never by a test runner. */
39
65
  export function browserErrorDeliveryAllowed(environment: { readonly origin: string; readonly automated: boolean; readonly harness: boolean },
@@ -68,6 +94,21 @@ export function browserErrorNoise(event: ErrorEvent, page: { readonly environmen
68
94
  return null;
69
95
  }
70
96
 
97
+ /**
98
+ * Known, designed refusals of an old browser: the player was told what to do, so they are warnings, never fatal (SENTRY-TRIAGE,
99
+ * WILDSHARD-GAME-8F). J171 keeps signature code out of the page, so a browser with no WebCrypto Ed25519 can't join the online world.
100
+ */
101
+ const UNSUPPORTED_BROWSER = ['This browser is too old for the online world'] as const;
102
+
103
+ /** The Sentry level an error reports at: `warning` for a designed old-browser refusal, else `fatal` or `error`. Pure, so it is tested. */
104
+ export function browserErrorLevel(error: unknown, fatal: boolean): 'warning' | 'error' | 'fatal' {
105
+ const message = error instanceof Error ? error.message
106
+ : typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string' ? error.message : String(error);
107
+ // includes, not startsWith: a title drop reports it as `<what>: <reason>` (src/client/app/entry.ts showDrop).
108
+ if (UNSUPPORTED_BROWSER.some((phrase) => message.includes(phrase))) return 'warning';
109
+ return fatal ? 'fatal' : 'error';
110
+ }
111
+
71
112
  function productionPage(): boolean {
72
113
  if (typeof location === 'undefined' || typeof navigator === 'undefined') return false;
73
114
  return browserErrorDeliveryAllowed({origin: location.origin, automated: navigator.webdriver, harness: harnessPins() !== undefined},
@@ -76,7 +117,7 @@ function productionPage(): boolean {
76
117
 
77
118
  function loadSdk(): Promise<BrowserSdk | null> {
78
119
  if (!productionPage()) return Promise.resolve(null);
79
- sdk ??= import('@sentry/browser').then((sentry) => {
120
+ sdk ??= import('@sentry/browser').then(async (sentry) => {
80
121
  const environment = browserErrorEnvironment(location.origin, installedIdentity()?.errorReportEnvironments ?? {});
81
122
  const version = typeof __ENGINE_RELEASE__ === 'object' ? __ENGINE_RELEASE__.version : undefined;
82
123
  sentry.init({
@@ -96,8 +137,8 @@ function loadSdk(): Promise<BrowserSdk | null> {
96
137
  maxBreadcrumbs: 0,
97
138
  normalizeDepth: 6, // context -> checkpoint array -> checkpoint -> facts
98
139
  beforeSend(event) {
99
- if (!productionPage()) return null;
100
- if (browserErrorNoise(event, { environment, userAgent: navigator.userAgent }) !== null) return null;
140
+ if (!productionPage()) return refused(event.event_id);
141
+ if (browserErrorNoise(event, { environment, userAgent: navigator.userAgent }) !== null) return refused(event.event_id);
101
142
  if (event.request) {
102
143
  event.request.url = `${location.origin}${location.pathname}`;
103
144
  // The user agent names the browser, OS and device; no referrer or other header leaves the page.
@@ -107,23 +148,26 @@ function loadSdk(): Promise<BrowserSdk | null> {
107
148
  return event;
108
149
  },
109
150
  });
151
+ // DEVICE-TELEMETRY DT2: the device's snapshot as the `device` context and `device.*` tags, loaded with the SDK (never on the title)
152
+ try { const { applySentryDevice, deviceSnapshot } = await import('./deviceSnapshot'); applySentryDevice(sentry, await deviceSnapshot(), dsn); }
153
+ catch { /* a report goes without it */ }
110
154
  return sentry;
111
- }).catch(() => null);
155
+ // S13: a failed chunk load (a stale page, the network) must not silence every later report on this page; the next one tries again
156
+ }).catch(() => { sdk = null; return null; });
112
157
  return sdk;
113
158
  }
114
159
 
160
+ function tagsOf(tags: BrowserErrorTags): Record<string, string> {
161
+ return { system: tags.system, build: tags.build, shard: tags.shard, boot_stage: tags.bootStage, ...(tags.screen === undefined ? {} : { screen: tags.screen }) };
162
+ }
163
+
115
164
  async function send(error: unknown, tags: BrowserErrorTags): Promise<void> {
116
165
  const sentry = await loadSdk();
117
166
  if (sentry === null) return;
118
167
  try {
119
168
  sentry.withScope((scope) => {
120
- scope.setTags({
121
- system: tags.system,
122
- build: tags.build,
123
- shard: tags.shard,
124
- boot_stage: tags.bootStage,
125
- });
126
- scope.setLevel(tags.fatal ? 'fatal' : 'error');
169
+ scope.setTags(tagsOf(tags));
170
+ scope.setLevel(browserErrorLevel(error, tags.fatal));
127
171
  if (tags.diagnostic) scope.setContext('boot_diagnostic', tags.diagnostic);
128
172
  sentry.captureException(asError(error));
129
173
  });
@@ -140,34 +184,130 @@ function asError(error: unknown): Error {
140
184
  return new Error(String(error));
141
185
  }
142
186
 
143
- /** Fire and forget: an absent DSN adds no request or SDK initialization to a player's boot. */
187
+ /**
188
+ * Fire and forget: an absent DSN adds no request or SDK initialization to a player's boot. A report that opens an error screen
189
+ * (`tags.screen`) is durable instead (S13): it is written to the device's screen outbox first, in the screen's own turn, and leaves
190
+ * the outbox only once Sentry acknowledges it, so a page that reloads, goes to the title or dies right after still delivers it
191
+ * (the next page sends it with the same event id, so Sentry keeps one).
192
+ */
144
193
  export function captureBrowserError(error: unknown, tags: BrowserErrorTags): void {
145
194
  if (!dsn || !productionPage()) return;
195
+ if (tags.screen !== undefined) { reportScreen(error, tags); return; }
146
196
  void send(error, tags);
147
197
  }
148
198
 
149
- /** Durable diagnostics require a transport acknowledgement, not just captureException's event ID. */
150
- export async function deliverBrowserError(error: Error, tags: BrowserErrorTags): Promise<boolean> {
199
+ /** Durable diagnostics require a transport acknowledgement, not just captureException's event ID. `eventId`: a fixed id (S13). */
200
+ export async function deliverBrowserError(error: Error, tags: BrowserErrorTags, eventId?: string): Promise<boolean> {
151
201
  if (!dsn || !productionPage()) return true;
152
202
  const sentry = await loadSdk();
153
203
  const client = sentry?.getClient();
154
204
  if (!sentry || !client) { sdk = null; return false; }
155
205
  return new Promise((resolve) => {
156
206
  const delivery = new Scope('error.delivery');
157
- let eventId = '';
207
+ let sentId = '';
158
208
  let unsubscribe = (): void => undefined;
159
- delivery.timeout(5000, () => { delivery.dispose(); unsubscribe(); resolve(false); });
160
- const finish = (ok: boolean): void => { delivery.dispose(); unsubscribe(); resolve(ok); };
209
+ let stopRefused = (): void => undefined;
210
+ delivery.timeout(5000, () => { delivery.dispose(); unsubscribe(); stopRefused(); resolve(false); });
211
+ const finish = (ok: boolean): void => { delivery.dispose(); unsubscribe(); stopRefused(); resolve(ok); };
212
+ const onRefused = (id: string): void => { if (id !== '' && (id === sentId || id === eventId)) finish(true); };
213
+ refusedListeners.add(onRefused);
214
+ stopRefused = (): void => { refusedListeners.delete(onRefused); };
161
215
  unsubscribe = client.on('afterSendEvent', (event, response) => {
162
- if (event.event_id === eventId) finish(response.statusCode !== undefined && response.statusCode >= 200 && response.statusCode < 300);
216
+ if (event.event_id === sentId) finish(response.statusCode !== undefined && response.statusCode >= 200 && response.statusCode < 300);
163
217
  });
164
218
  try {
165
219
  sentry.withScope((scope) => {
166
- scope.setTags({ system: tags.system, build: tags.build, shard: tags.shard, boot_stage: tags.bootStage });
167
- scope.setLevel('error');
220
+ scope.setTags(tagsOf(tags));
221
+ scope.setLevel(browserErrorLevel(error, tags.screen !== undefined && tags.fatal));
168
222
  if (tags.diagnostic) scope.setContext('boot_diagnostic', tags.diagnostic);
169
- eventId = sentry.captureException(error);
223
+ sentId = sentry.captureException(error, eventId === undefined ? undefined : { event_id: eventId });
170
224
  });
171
225
  } catch { finish(false); }
172
226
  });
173
227
  }
228
+
229
+ /**
230
+ * STALE-BUILD SB6: the stale-build screen (index.html `data-stale-build`) runs before Sentry can load, so the next build that
231
+ * boots reports it, once, as screen `stale-build` through the screen outbox (durable until Sentry acknowledges it). The build
232
+ * tag is the stale build's, not this page's.
233
+ */
234
+ export function staleBuildReport(note: StaleBuildNote): { error: Error; tags: BrowserErrorTags } {
235
+ const days = Math.floor((note.seen - note.at) / 86_400_000);
236
+ const error = new Error(`A stale build was stopped at the title and sent to update (${String(days)} days old)`);
237
+ return { error, tags: { system: 'stale-build', build: note.build, shard: '', bootStage: 'title', fatal: false, screen: 'stale-build',
238
+ diagnostic: { builtAt: new Date(note.at).toISOString(), seen: new Date(note.seen).toISOString(), server: note.server, tries: note.tries } } };
239
+ }
240
+
241
+ // ── S13: the screen outbox (its reader and sender, src/client/engine/telemetry/screenOutbox.ts, load only when something is owed) ──
242
+ /** one screen report waiting for Sentry's acknowledgement */
243
+ export interface ScreenReport {
244
+ /** the Sentry event id (32 hex), fixed when the screen opens so a resend is the same event */
245
+ readonly id: string;
246
+ readonly at: number;
247
+ readonly message: string;
248
+ readonly stack: string;
249
+ readonly tags: BrowserErrorTags & { readonly screen: ErrorScreen };
250
+ }
251
+ /** where the outbox lives: the device's `screen.reports` slot on a page, a variable in a test */
252
+ export interface ScreenStore { read: () => Json; write: (value: Json) => void }
253
+ export const OUTBOX_MAX = 8;
254
+
255
+ let idCount = 0;
256
+ /** A fresh event id. getRandomValues works on a plain-http page, where crypto.randomUUID throws (QA 11-13 row 5). */
257
+ export function screenEventId(random: (bytes: Uint8Array<ArrayBuffer>) => Uint8Array = (bytes) => crypto.getRandomValues(bytes)): string {
258
+ try { return [...random(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, '0')).join(''); }
259
+ catch { idCount++; return `${Date.now().toString(16)}${idCount.toString(16)}`.padStart(32, '0').slice(-32); }
260
+ }
261
+
262
+ /** the page's outbox: literal jsonSlot calls (test/saves-lock.test.ts reads the key from them) */
263
+ const pageStore: ScreenStore = {
264
+ read: () => jsonSlot('screen.reports', 'device').peek(),
265
+ write: (value) => { if (!jsonSlot('screen.reports', 'device').write(value)) throw new Error('screen outbox not saved'); },
266
+ };
267
+ const sending = new Set<string>();
268
+ let flushWired = false;
269
+ /** a report as the outbox stores it: JSON, so a diagnostic's undefined fields drop as they would on the wire */
270
+ function stored(report: ScreenReport): Json {
271
+ const text = JSON.stringify(report);
272
+ return JSON.parse(text) as Json;
273
+ }
274
+ async function sendOnce(error: Error, tags: BrowserErrorTags, id: string): Promise<void> {
275
+ sending.add(id);
276
+ try { await deliverBrowserError(error, tags, id); } catch { /* telemetry never throws */ } finally { sending.delete(id); }
277
+ }
278
+
279
+ /** S13: the report of a screen that just opened, on the device before anything awaits, then sent. */
280
+ function reportScreen(error: unknown, tags: BrowserErrorTags): void {
281
+ if (tags.screen === undefined) return;
282
+ const e = asError(error);
283
+ // the diagnostic rides along up to 16 KB of JSON; a larger one is cut to a note, so eight stored reports stay small beside the saves
284
+ const diagnostic = tags.diagnostic === undefined ? undefined : JSON.stringify(tags.diagnostic).length <= 16_384 ? tags.diagnostic : { truncated: true };
285
+ const report: ScreenReport = { id: screenEventId(), at: Date.now(), message: e.message.slice(0, 2000), stack: (e.stack ?? '').slice(0, 6000),
286
+ tags: { ...tags, screen: tags.screen, ...(diagnostic === undefined ? {} : { diagnostic }) } };
287
+ let kept = true;
288
+ try {
289
+ const raw = pageStore.read();
290
+ pageStore.write([...(Array.isArray(raw) ? raw : []), stored(report)].slice(-OUTBOX_MAX));
291
+ } catch { kept = false; }
292
+ // storage refused: this page still sends it, once
293
+ if (kept) flushScreenReports(); else void sendOnce(e, report.tags, report.id);
294
+ }
295
+
296
+ /** S13: whether this build can deliver a screen report at all (a DSN is built in), so a build or test without one arms no flush timer */
297
+ export function screenReportsEnabled(): boolean { return dsn !== ''; }
298
+
299
+ /** Send what this page or an earlier one still owes (every document, off the boot's hot path), and again when the network is back. */
300
+ export function flushScreenReports(): void {
301
+ if (!dsn || !productionPage()) return;
302
+ if (!flushWired && typeof window !== 'undefined') {
303
+ flushWired = true;
304
+ pageScope.listen(window, 'online', () => { flushScreenReports(); });
305
+ }
306
+ // offline: the `online` listener sends it; a chunk import now would only fail
307
+ if (typeof navigator !== 'undefined' && !navigator.onLine) return;
308
+ let raw: Json = null;
309
+ try { raw = pageStore.read(); } catch { return; }
310
+ if (!Array.isArray(raw) || raw.length === 0) return;
311
+ void import('./screenOutbox').then(({ ScreenOutbox, flushScreenOutbox }) => flushScreenOutbox(new ScreenOutbox(pageStore), deliverBrowserError, sending))
312
+ .catch(() => undefined);
313
+ }
@@ -0,0 +1,155 @@
1
+ // DEVICE-TELEMETRY DT1 (meta docs/plans/DEVICE-TELEMETRY-PLAN.md): one snapshot of the device this page runs on, gathered once per page,
2
+ // for the door's `client.device` line (shell.ts sends it on each socket) and Sentry's `device` context (browserErrors.ts).
3
+ // Every field is optional and every read is failure-safe: a browser without an API gives fewer fields, never a throw.
4
+ // Privacy line: device characteristics only, the ones any page can read. No IP address, no new persistent identifier, no fingerprint
5
+ // hash, and nothing that reads files, contacts, sensors, the camera, the microphone or location.
6
+ import { Scope } from '../../../shared/engine/app/scope';
7
+ import { cleanDevice, deviceTags, type DeviceSnapshot } from '../../../shared/engine/net/deviceWord';
8
+
9
+ declare const __BUILD_ID__: string | undefined;
10
+
11
+ /** What the snapshot reads; the page's globals by default, fakes in a test. */
12
+ export interface DeviceSources {
13
+ readonly navigator?: unknown;
14
+ readonly screen?: unknown;
15
+ readonly devicePixelRatio?: unknown;
16
+ readonly matchMedia?: (query: string) => { readonly matches: boolean };
17
+ readonly timeZone?: () => string | undefined;
18
+ readonly build?: string;
19
+ }
20
+
21
+ /** What the game's own WebGL context says (never a new context). */
22
+ export type DeviceGpu = Pick<DeviceSnapshot, 'gpu' | 'gpuVendor' | 'maxTexture' | 'astc' | 'etc2' | 'bptc'>;
23
+
24
+ const HIGH_ENTROPY = ['model', 'platform', 'platformVersion', 'architecture', 'bitness', 'fullVersionList', 'formFactors', 'wow64'];
25
+ /** Client Hints can hang on a browser that never answers; the snapshot waits at most this long for them. */
26
+ const HINTS_WAIT_MS = 1500;
27
+
28
+ type Rec = Record<string, unknown>;
29
+ /** A property read that never throws (a getter may). */
30
+ const read = (from: unknown, key: string): unknown => {
31
+ if (typeof from !== 'object' && typeof from !== 'function') return undefined;
32
+ if (from === null) return undefined;
33
+ try { return (from as Rec)[key]; } catch { return undefined; }
34
+ };
35
+ const said = (value: unknown): string => typeof value === 'string' || typeof value === 'number' ? String(value) : '';
36
+ const brandList = (value: unknown): string[] | undefined => Array.isArray(value)
37
+ ? value.map(entry => `${said(read(entry, 'brand'))} ${said(read(entry, 'version'))}`.trim()).filter(Boolean) : undefined;
38
+
39
+ async function hints(nav: unknown): Promise<Rec> {
40
+ const data = read(nav, 'userAgentData');
41
+ const out: Rec = { brands: brandList(read(data, 'brands')), mobile: read(data, 'mobile'), platform: read(data, 'platform') };
42
+ const ask = read(data, 'getHighEntropyValues');
43
+ if (typeof ask !== 'function') return out;
44
+ const scope = new Scope('device.hints');
45
+ try {
46
+ const asked = Promise.resolve((ask as (hints: string[]) => unknown).call(data, HIGH_ENTROPY));
47
+ const values = await Promise.race([asked, new Promise(resolve => { scope.timeout(HINTS_WAIT_MS, () => { resolve(null); }); })]);
48
+ if (values === null || typeof values !== 'object') return out;
49
+ for (const key of ['model', 'platform', 'platformVersion', 'architecture', 'bitness', 'wow64', 'formFactors']) {
50
+ const value = read(values, key);
51
+ if (value !== undefined && value !== '') out[key] = value;
52
+ }
53
+ out['fullVersionList'] = brandList(read(values, 'fullVersionList'));
54
+ } catch { /* a refused hint leaves the low-entropy ones */ } finally { scope.dispose(); }
55
+ return out;
56
+ }
57
+
58
+ function media(sources: DeviceSources, query: string): boolean | undefined {
59
+ try { return sources.matchMedia?.(query).matches; } catch { return undefined; }
60
+ }
61
+
62
+ /** The snapshot from `sources`, without the GPU. Never throws. */
63
+ export async function collectDevice(sources: DeviceSources): Promise<DeviceSnapshot> {
64
+ const nav = sources.navigator, screen = sources.screen, out: Rec = { build: sources.build };
65
+ try { Object.assign(out, await hints(nav)); } catch { /* none */ }
66
+ out['ua'] = read(nav, 'userAgent');
67
+ out['screenW'] = read(screen, 'width'); out['screenH'] = read(screen, 'height');
68
+ out['availW'] = read(screen, 'availWidth'); out['availH'] = read(screen, 'availHeight');
69
+ out['orientation'] = read(read(screen, 'orientation'), 'type');
70
+ out['dpr'] = sources.devicePixelRatio;
71
+ out['cores'] = read(nav, 'hardwareConcurrency'); out['memory'] = read(nav, 'deviceMemory'); out['touch'] = read(nav, 'maxTouchPoints');
72
+ out['pointer'] = media(sources, '(pointer: coarse)') === true ? 'coarse' : media(sources, '(pointer: fine)') === true ? 'fine' : media(sources, '(pointer: none)') === true ? 'none' : undefined;
73
+ out['hover'] = media(sources, '(hover: hover)');
74
+ out['language'] = read(nav, 'language');
75
+ const languages = read(nav, 'languages');
76
+ out['languages'] = Array.isArray(languages) ? [...languages as unknown[]] : undefined;
77
+ try { out['timeZone'] = sources.timeZone?.(); } catch { /* none */ }
78
+ const connection = read(nav, 'connection');
79
+ out['net'] = read(connection, 'effectiveType'); out['downlink'] = read(connection, 'downlink'); out['saveData'] = read(connection, 'saveData');
80
+ out['display'] = (['standalone', 'fullscreen', 'minimal-ui', 'browser'] as const).find(mode => media(sources, `(display-mode: ${mode})`) === true);
81
+ return cleanDevice(out);
82
+ }
83
+
84
+ /** What the game's own context says about its GPU: the unmasked names, the largest texture, and the compressed forms it takes. Never throws. */
85
+ export function gpuFacts(gl: Pick<WebGLRenderingContext, 'getExtension' | 'getParameter' | 'RENDERER' | 'VENDOR' | 'MAX_TEXTURE_SIZE'>): DeviceGpu {
86
+ const out: Rec = {};
87
+ try {
88
+ const info: { UNMASKED_RENDERER_WEBGL: number; UNMASKED_VENDOR_WEBGL: number } | null = gl.getExtension('WEBGL_debug_renderer_info');
89
+ out['gpu'] = gl.getParameter(info === null ? gl.RENDERER : info.UNMASKED_RENDERER_WEBGL);
90
+ out['gpuVendor'] = gl.getParameter(info === null ? gl.VENDOR : info.UNMASKED_VENDOR_WEBGL);
91
+ } catch { /* a lost context names nothing */ }
92
+ try { out['maxTexture'] = gl.getParameter(gl.MAX_TEXTURE_SIZE); } catch { /* none */ }
93
+ const has = (name: string): boolean | undefined => { try { return gl.getExtension(name) !== null; } catch { return undefined; } };
94
+ out['astc'] = has('WEBGL_compressed_texture_astc'); out['etc2'] = has('WEBGL_compressed_texture_etc'); out['bptc'] = has('EXT_texture_compression_bptc');
95
+ return cleanDevice(out);
96
+ }
97
+
98
+ /** The noted GPU lives on the window, not in this module: the online shell and the game can be separate bundles of the engine. */
99
+ const GPU_KEY = Symbol.for('wildshard.deviceGpu');
100
+ interface GpuHolder { [GPU_KEY]?: { facts: DeviceGpu | null; waiting: ((facts: DeviceGpu) => void)[] } }
101
+ const holder = (): NonNullable<GpuHolder[typeof GPU_KEY]> => {
102
+ const host = globalThis as GpuHolder;
103
+ host[GPU_KEY] ??= { facts: null, waiting: [] };
104
+ return host[GPU_KEY];
105
+ };
106
+
107
+ /** The renderer's context is up (bootstrap.ts): note what it says, once per page. */
108
+ export function noteDeviceGpu(gl: Parameters<typeof gpuFacts>[0]): void {
109
+ try {
110
+ const held = holder();
111
+ if (held.facts !== null) return;
112
+ held.facts = gpuFacts(gl);
113
+ for (const wake of held.waiting.splice(0)) wake(held.facts);
114
+ } catch { /* telemetry never disrupts the boot */ }
115
+ }
116
+
117
+ /** The GPU noted so far, waiting at most `waitMs` for the renderer. */
118
+ function noted(waitMs: number): Promise<DeviceGpu> {
119
+ const held = holder();
120
+ if (held.facts !== null || waitMs <= 0) return Promise.resolve(held.facts ?? {});
121
+ const scope = new Scope('device.gpu');
122
+ return new Promise<DeviceGpu>(resolve => {
123
+ const wake = (facts: DeviceGpu): void => { scope.dispose(); resolve(facts); };
124
+ scope.timeout(waitMs, () => { held.waiting = held.waiting.filter(entry => entry !== wake); scope.dispose(); resolve({}); });
125
+ held.waiting.push(wake);
126
+ });
127
+ }
128
+
129
+ let page: Promise<DeviceSnapshot> | null = null;
130
+ /** This page's snapshot: gathered once, with the GPU once the renderer has said it (at most `gpuWaitMs`). Never rejects. */
131
+ export async function deviceSnapshot(gpuWaitMs = 0): Promise<DeviceSnapshot> {
132
+ page ??= collectDevice(pageSources()).catch(() => ({}));
133
+ const [device, gpu] = await Promise.all([page, noted(gpuWaitMs)]);
134
+ return { ...device, ...gpu };
135
+ }
136
+
137
+ function pageSources(): DeviceSources {
138
+ const scope = globalThis as unknown as { navigator?: unknown; screen?: unknown; devicePixelRatio?: unknown; matchMedia?: (query: string) => { matches: boolean } };
139
+ const matchMedia = scope.matchMedia;
140
+ return {
141
+ navigator: scope.navigator, screen: scope.screen, devicePixelRatio: scope.devicePixelRatio,
142
+ ...(typeof matchMedia === 'function' ? { matchMedia: (query: string) => matchMedia.call(globalThis, query) } : {}),
143
+ timeZone: () => Intl.DateTimeFormat().resolvedOptions().timeZone,
144
+ ...(typeof __BUILD_ID__ === 'string' ? { build: __BUILD_ID__ } : {}),
145
+ };
146
+ }
147
+
148
+ /** The part of the Sentry SDK the device context needs. */
149
+ export interface SentryDeviceSink { setContext: (name: string, context: Record<string, unknown> | null) => void; setTags: (tags: Record<string, string>) => void }
150
+ /** DT2: Sentry's `device` context holds the whole snapshot, and its searchable tags are set (`device.model:*`). Only with a DSN built
151
+ * in, as every Sentry call; without one nothing is called. Never throws. */
152
+ export function applySentryDevice(sentry: SentryDeviceSink, device: DeviceSnapshot, dsn: string): boolean {
153
+ if (dsn === '') return false;
154
+ try { sentry.setContext('device', { ...device }); sentry.setTags(deviceTags(device)); return true; } catch { return false; }
155
+ }
@@ -0,0 +1,61 @@
1
+ import type { Json } from '../saves/slots';
2
+ import { ERROR_SCREENS, OUTBOX_MAX, type BrowserErrorTags, type ScreenReport, type ScreenStore } from './browserErrors';
3
+ /**
4
+ * SENTRY-TRIAGE S13: the screen outbox's reader and sender, loaded only when a report is owed (outside the title's gzip ceiling).
5
+ * Every error screen's report waits on the device (browserErrors.ts reportScreen) until Sentry acknowledges it; a resend keeps its
6
+ * event id, so Sentry keeps one event.
7
+ */
8
+
9
+ const OUTBOX_AGE_MS = 7 * 24 * 60 * 60_000;
10
+
11
+ /** The outbox over a store. Pure: no SDK and no page. */
12
+ export class ScreenOutbox {
13
+ private readonly store: ScreenStore;
14
+ private readonly now: () => number;
15
+ constructor(store: ScreenStore, now: () => number = Date.now) { this.store = store; this.now = now; }
16
+ /** the reports still owed, oldest first: at most OUTBOX_MAX, none older than a week, nothing malformed */
17
+ pending(): ScreenReport[] {
18
+ let raw: Json = null;
19
+ try { raw = this.store.read(); } catch { return []; }
20
+ if (!Array.isArray(raw)) return [];
21
+ const now = this.now();
22
+ const owed: ScreenReport[] = [];
23
+ for (const item of raw) {
24
+ if (typeof item !== 'object' || item === null || Array.isArray(item)) continue;
25
+ const { id, at, message, stack, tags } = item;
26
+ if (typeof id !== 'string' || typeof at !== 'number' || now - at >= OUTBOX_AGE_MS || typeof message !== 'string' || typeof stack !== 'string') continue;
27
+ if (typeof tags !== 'object' || tags === null || Array.isArray(tags)) continue;
28
+ const screen = ERROR_SCREENS.find((name) => name === tags['screen']);
29
+ if (screen === undefined || typeof tags['system'] !== 'string' || typeof tags['bootStage'] !== 'string') continue;
30
+ // every tag is a string or the fatal flag; the diagnostic is a plain object
31
+ const sound = Object.entries(tags).every(([key, value]) => key === 'diagnostic'
32
+ ? typeof value === 'object' && value !== null && !Array.isArray(value) : typeof value === 'string' || typeof value === 'boolean');
33
+ if (sound) owed.push({ id, at, message, stack, tags: { ...(tags as unknown as BrowserErrorTags), screen } });
34
+ }
35
+ return owed.slice(-OUTBOX_MAX);
36
+ }
37
+ /** keep a report until it is acknowledged; false when storage refused it */
38
+ add(report: ScreenReport): boolean {
39
+ return this.save([...this.pending().filter((p) => p.id !== report.id), report]);
40
+ }
41
+ ack(id: string): void { this.save(this.pending().filter((p) => p.id !== id)); }
42
+ private save(queue: readonly ScreenReport[]): boolean {
43
+ const text = JSON.stringify(queue.slice(-OUTBOX_MAX));
44
+ try { this.store.write(JSON.parse(text) as Json); return true; } catch { return false; }
45
+ }
46
+ }
47
+
48
+ /** Send every owed report; an acknowledged one leaves the outbox. `deliver` resolves true on Sentry's 2xx. */
49
+ export async function flushScreenOutbox(outbox: ScreenOutbox, deliver: (error: Error, tags: BrowserErrorTags, eventId: string) => Promise<boolean>,
50
+ inFlight: Set<string>): Promise<void> {
51
+ for (const report of outbox.pending()) {
52
+ // another flush may have delivered it while this one waited
53
+ if (inFlight.has(report.id) || !outbox.pending().some((p) => p.id === report.id)) continue;
54
+ inFlight.add(report.id);
55
+ try {
56
+ const error = new Error(report.message);
57
+ if (report.stack !== '') error.stack = report.stack;
58
+ if (await deliver(error, report.tags, report.id)) outbox.ack(report.id);
59
+ } catch { /* kept for the next flush */ } finally { inFlight.delete(report.id); }
60
+ }
61
+ }
@@ -0,0 +1,12 @@
1
+ import { takeStaleBuildNote, type StaleBuildNote } from '../saves/staleBuildNote';
2
+ import { captureBrowserError, staleBuildReport } from './browserErrors';
3
+
4
+ /** STALE-BUILD SB6: report an earlier page's stale-build note (browserErrors.ts staleBuildReport), if there is one; the note is gone after this. */
5
+ export function reportStaleBuild(take: () => StaleBuildNote | null = takeStaleBuildNote, capture: typeof captureBrowserError = captureBrowserError): void {
6
+ try {
7
+ const note = take();
8
+ if (note === null) return;
9
+ const { error, tags } = staleBuildReport(note);
10
+ capture(error, tags);
11
+ } catch { /* telemetry never disrupts the boot */ }
12
+ }