@dreamboard-games/cli 0.1.30-alpha.3 → 0.1.30-alpha.30

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 (173) hide show
  1. package/README.md +27 -108
  2. package/dist/agent-verifier/agent-workspace-verifier.mjs +1855 -57
  3. package/dist/agent-verifier/agent-workspace-verifier.mjs.map +1 -1
  4. package/dist/agent-verifier/{chunk-XQXDOBYB.mjs → chunk-4I2WWAPK.mjs} +27 -10
  5. package/dist/agent-verifier/chunk-4I2WWAPK.mjs.map +1 -0
  6. package/dist/agent-verifier/{chunk-O4YCPU7C.mjs → chunk-BWBN2TDJ.mjs} +539 -641
  7. package/dist/agent-verifier/chunk-BWBN2TDJ.mjs.map +1 -0
  8. package/dist/agent-verifier/{chunk-SH5JKYOB.mjs → chunk-FNSHNMDY.mjs} +116 -23
  9. package/dist/agent-verifier/chunk-FNSHNMDY.mjs.map +1 -0
  10. package/dist/agent-verifier/{chunk-TAEQKBJB.mjs → chunk-GWRZRWCF.mjs} +1 -1
  11. package/dist/agent-verifier/chunk-GWRZRWCF.mjs.map +1 -0
  12. package/dist/agent-verifier/chunk-H6XDQJ3N.mjs +11 -0
  13. package/dist/agent-verifier/chunk-HUBV22JQ.mjs +89 -0
  14. package/dist/agent-verifier/chunk-HUBV22JQ.mjs.map +1 -0
  15. package/dist/agent-verifier/{chunk-VS573ERH.mjs → chunk-JZTH3EMV.mjs} +2 -2
  16. package/dist/agent-verifier/{chunk-XGWCY624.mjs → chunk-KDAQ4CZY.mjs} +34 -27
  17. package/dist/agent-verifier/chunk-KDAQ4CZY.mjs.map +1 -0
  18. package/dist/agent-verifier/{chunk-IAYRNVUC.mjs → chunk-LMW66VBH.mjs} +2 -13
  19. package/dist/agent-verifier/{chunk-IAYRNVUC.mjs.map → chunk-LMW66VBH.mjs.map} +1 -1
  20. package/dist/agent-verifier/{chunk-776W3UGV.mjs → chunk-M6YNQZCC.mjs} +4 -13
  21. package/dist/agent-verifier/chunk-M6YNQZCC.mjs.map +1 -0
  22. package/dist/agent-verifier/{chunk-H76MT5UR.mjs → chunk-M7UVBANQ.mjs} +2 -1
  23. package/dist/agent-verifier/chunk-M7UVBANQ.mjs.map +1 -0
  24. package/dist/agent-verifier/{chunk-NAK77WXW.mjs → chunk-MYMVXTZT.mjs} +4 -5
  25. package/dist/agent-verifier/chunk-MYMVXTZT.mjs.map +1 -0
  26. package/dist/agent-verifier/chunk-OJFZVGEL.mjs +492 -0
  27. package/dist/agent-verifier/chunk-OJFZVGEL.mjs.map +1 -0
  28. package/dist/agent-verifier/{chunk-LUZ7KE6H.mjs → chunk-QD4SQNUP.mjs} +4 -8
  29. package/dist/agent-verifier/{chunk-LUZ7KE6H.mjs.map → chunk-QD4SQNUP.mjs.map} +1 -1
  30. package/dist/agent-verifier/{chunk-7WWGFAAU.mjs → chunk-QMOBTQ5G.mjs} +215 -223
  31. package/dist/agent-verifier/chunk-QMOBTQ5G.mjs.map +1 -0
  32. package/dist/agent-verifier/chunk-TTB7AIHZ.mjs +214 -0
  33. package/dist/agent-verifier/chunk-TTB7AIHZ.mjs.map +1 -0
  34. package/dist/agent-verifier/{chunk-F2DIOJJZ.mjs → chunk-XCQQIPCO.mjs} +5 -46
  35. package/dist/agent-verifier/chunk-XCQQIPCO.mjs.map +1 -0
  36. package/dist/agent-verifier/{global-config-Y2NTSK4R.mjs → global-config-SWWR2LP4.mjs} +6 -6
  37. package/dist/agent-verifier/{keychain-backend-SPQWGKZN.mjs → keychain-backend-UF3Z26JM.mjs} +12 -7
  38. package/dist/agent-verifier/keychain-backend-UF3Z26JM.mjs.map +1 -0
  39. package/dist/agent-verifier/{local-files-JFOQQZDL.mjs → local-files-OF4QFISU.mjs} +10 -10
  40. package/dist/agent-verifier/{chunk-UIOLGH4A.mjs → local-typecheck-DHVLM37Z.mjs} +4 -4
  41. package/dist/agent-verifier/local-typecheck-DHVLM37Z.mjs.map +1 -0
  42. package/dist/agent-verifier/{materialize-workspace-ZAVGQQSF.mjs → materialize-workspace-K4WYFG5E.mjs} +23 -22
  43. package/dist/agent-verifier/materialize-workspace-K4WYFG5E.mjs.map +1 -0
  44. package/dist/agent-verifier/{project-state-K576C2TE.mjs → project-state-XKUSCFSV.mjs} +2 -2
  45. package/dist/agent-verifier/{prompt-MJRJMOGQ.mjs → prompt-VKHMCQT6.mjs} +2 -2
  46. package/dist/agent-verifier/{chunk-A64ZZUZV.mjs → reducer-bundle-preflight-GLUJKTWU.mjs} +76 -25
  47. package/dist/agent-verifier/reducer-bundle-preflight-GLUJKTWU.mjs.map +1 -0
  48. package/dist/agent-verifier/{chunk-JGT4P4UD.mjs → reducer-contract-preflight-WVQQPW5F.mjs} +7 -6
  49. package/dist/agent-verifier/reducer-contract-preflight-WVQQPW5F.mjs.map +1 -0
  50. package/dist/agent-verifier/{chunk-E7SSWJXJ.mjs → reducer-native-test-harness-UFMSNNDY.mjs} +463 -686
  51. package/dist/agent-verifier/reducer-native-test-harness-UFMSNNDY.mjs.map +1 -0
  52. package/dist/agent-verifier/static-scaffold-MHVM63HU.mjs +24 -0
  53. package/dist/agent-verifier/workspace-codegen-SPPVHURX.mjs +10 -0
  54. package/dist/agent-verifier/{workspace-dependencies-NOOQBK6I.mjs → workspace-dependencies-5HEEKZFP.mjs} +6 -4
  55. package/dist/authoring-compatibility-internal.js +12 -0
  56. package/dist/chunk-2H7UOFLK.js +11 -0
  57. package/dist/chunk-EQNBQVIW.js +204 -0
  58. package/dist/chunk-EQNBQVIW.js.map +1 -0
  59. package/dist/{chunk-TAQKH67O.js → chunk-I4SZ7FA4.js} +2593 -7278
  60. package/dist/chunk-I4SZ7FA4.js.map +1 -0
  61. package/dist/chunk-RTNKVNQA.js +3735 -0
  62. package/dist/chunk-RTNKVNQA.js.map +1 -0
  63. package/dist/chunk-UI7NWSYA.js +334 -0
  64. package/dist/chunk-UI7NWSYA.js.map +1 -0
  65. package/dist/{global-config-S4ZIPECE.js → global-config-GK2UC2X6.js} +4 -3
  66. package/dist/index.js +3278 -6181
  67. package/dist/index.js.map +1 -1
  68. package/dist/internal.js +36 -10
  69. package/dist/internal.js.map +1 -1
  70. package/dist/{keychain-backend-HDF4TZDL.js → keychain-backend-GO34KGTG.js} +12 -7
  71. package/dist/keychain-backend-GO34KGTG.js.map +1 -0
  72. package/dist/{prompt-NDV3AE5L.js → prompt-GMZABCJC.js} +2 -2
  73. package/package.json +9 -19
  74. package/release/authoring-release-set.json +38 -0
  75. package/skills/dreamboard/SKILL.md +30 -28
  76. package/skills/dreamboard/references/building-your-first-game.md +15 -15
  77. package/skills/dreamboard/references/cli.md +46 -47
  78. package/skills/dreamboard/references/manifest-authoring.md +11 -3
  79. package/skills/dreamboard/references/quickstart.md +16 -13
  80. package/skills/dreamboard/references/testing.md +6 -13
  81. package/dist/agent-verifier/chunk-3UKQVWLV.mjs +0 -1744
  82. package/dist/agent-verifier/chunk-3UKQVWLV.mjs.map +0 -1
  83. package/dist/agent-verifier/chunk-776W3UGV.mjs.map +0 -1
  84. package/dist/agent-verifier/chunk-7WWGFAAU.mjs.map +0 -1
  85. package/dist/agent-verifier/chunk-A64ZZUZV.mjs.map +0 -1
  86. package/dist/agent-verifier/chunk-E7SSWJXJ.mjs.map +0 -1
  87. package/dist/agent-verifier/chunk-F2DIOJJZ.mjs.map +0 -1
  88. package/dist/agent-verifier/chunk-G42BGGG2.mjs +0 -70
  89. package/dist/agent-verifier/chunk-G42BGGG2.mjs.map +0 -1
  90. package/dist/agent-verifier/chunk-H76MT5UR.mjs.map +0 -1
  91. package/dist/agent-verifier/chunk-HGMUAL33.mjs +0 -39
  92. package/dist/agent-verifier/chunk-HGMUAL33.mjs.map +0 -1
  93. package/dist/agent-verifier/chunk-JGT4P4UD.mjs.map +0 -1
  94. package/dist/agent-verifier/chunk-NAK77WXW.mjs.map +0 -1
  95. package/dist/agent-verifier/chunk-O4YCPU7C.mjs.map +0 -1
  96. package/dist/agent-verifier/chunk-S34FRJHS.mjs +0 -222
  97. package/dist/agent-verifier/chunk-S34FRJHS.mjs.map +0 -1
  98. package/dist/agent-verifier/chunk-SH5JKYOB.mjs.map +0 -1
  99. package/dist/agent-verifier/chunk-SKI2ESE5.mjs +0 -44
  100. package/dist/agent-verifier/chunk-TAEQKBJB.mjs.map +0 -1
  101. package/dist/agent-verifier/chunk-UIOLGH4A.mjs.map +0 -1
  102. package/dist/agent-verifier/chunk-UIZNWRM6.mjs +0 -2432
  103. package/dist/agent-verifier/chunk-UIZNWRM6.mjs.map +0 -1
  104. package/dist/agent-verifier/chunk-W3N3QJ4V.mjs +0 -624
  105. package/dist/agent-verifier/chunk-W3N3QJ4V.mjs.map +0 -1
  106. package/dist/agent-verifier/chunk-XGWCY624.mjs.map +0 -1
  107. package/dist/agent-verifier/chunk-XQXDOBYB.mjs.map +0 -1
  108. package/dist/agent-verifier/compile-TEQVA46V.mjs +0 -312
  109. package/dist/agent-verifier/compile-TEQVA46V.mjs.map +0 -1
  110. package/dist/agent-verifier/keychain-backend-SPQWGKZN.mjs.map +0 -1
  111. package/dist/agent-verifier/local-typecheck-XVGWI75X.mjs +0 -10
  112. package/dist/agent-verifier/materialize-workspace-ZAVGQQSF.mjs.map +0 -1
  113. package/dist/agent-verifier/reducer-bundle-preflight-LXNJUBKL.mjs +0 -20
  114. package/dist/agent-verifier/reducer-contract-preflight-TUMQ43JV.mjs +0 -11
  115. package/dist/agent-verifier/reducer-native-test-harness-CHX5MBL5.mjs +0 -50
  116. package/dist/agent-verifier/static-scaffold-R7SVDRQI.mjs +0 -27
  117. package/dist/agent-verifier/sync-THAI546U.mjs +0 -588
  118. package/dist/agent-verifier/sync-THAI546U.mjs.map +0 -1
  119. package/dist/agent-verifier/test-AFAQFKOB.mjs +0 -353
  120. package/dist/agent-verifier/test-AFAQFKOB.mjs.map +0 -1
  121. package/dist/agent-verifier/workspace-codegen-2ZMQRIKJ.mjs +0 -10
  122. package/dist/agent-verifier/workspace-dependencies-NOOQBK6I.mjs.map +0 -1
  123. package/dist/chunk-N7XPNNUI.js +0 -432
  124. package/dist/chunk-N7XPNNUI.js.map +0 -1
  125. package/dist/chunk-SEGVTWSK.js +0 -44
  126. package/dist/chunk-SEGVTWSK.js.map +0 -1
  127. package/dist/chunk-TAQKH67O.js.map +0 -1
  128. package/dist/dev-host/components/drawer.tsx +0 -132
  129. package/dist/dev-host/components/input.tsx +0 -21
  130. package/dist/dev-host/dev-api-proxy-plugin.ts +0 -328
  131. package/dist/dev-host/dev-author-dom-warnings.ts +0 -100
  132. package/dist/dev-host/dev-diagnostics.ts +0 -62
  133. package/dist/dev-host/dev-fallback-stylesheet.ts +0 -53
  134. package/dist/dev-host/dev-hmr-guard-plugin.ts +0 -47
  135. package/dist/dev-host/dev-host-controller.ts +0 -674
  136. package/dist/dev-host/dev-host-player-query.ts +0 -17
  137. package/dist/dev-host/dev-host-session-transport.ts +0 -52
  138. package/dist/dev-host/dev-host-storage.ts +0 -56
  139. package/dist/dev-host/dev-log-relay-plugin.ts +0 -510
  140. package/dist/dev-host/dev-runtime-config.ts +0 -14
  141. package/dist/dev-host/dev-runtime-platform.ts +0 -335
  142. package/dist/dev-host/dev-virtual-modules-plugin.ts +0 -64
  143. package/dist/dev-host/host-main.css +0 -224
  144. package/dist/dev-host/host-main.tsx +0 -948
  145. package/dist/dev-host/index.html +0 -56
  146. package/dist/dev-host/lib/utils.ts +0 -6
  147. package/dist/dev-host/plugin-main.ts +0 -61
  148. package/dist/dev-host/plugin.html +0 -24
  149. package/dist/dev-host/shared-styles.css +0 -144
  150. package/dist/dev-host/start-dev-server.ts +0 -140
  151. package/dist/dev-host/virtual-modules.d.ts +0 -27
  152. package/dist/global-config-S4ZIPECE.js.map +0 -1
  153. package/dist/keychain-backend-HDF4TZDL.js.map +0 -1
  154. package/skills/dreamboard/scripts/events-extract.mjs +0 -218
  155. /package/dist/agent-verifier/{chunk-SKI2ESE5.mjs.map → chunk-H6XDQJ3N.mjs.map} +0 -0
  156. /package/dist/agent-verifier/{chunk-VS573ERH.mjs.map → chunk-JZTH3EMV.mjs.map} +0 -0
  157. /package/dist/agent-verifier/{global-config-Y2NTSK4R.mjs.map → global-config-SWWR2LP4.mjs.map} +0 -0
  158. /package/dist/agent-verifier/{local-files-JFOQQZDL.mjs.map → local-files-OF4QFISU.mjs.map} +0 -0
  159. /package/dist/agent-verifier/{local-typecheck-XVGWI75X.mjs.map → project-state-XKUSCFSV.mjs.map} +0 -0
  160. /package/dist/agent-verifier/{prompt-MJRJMOGQ.mjs.map → prompt-VKHMCQT6.mjs.map} +0 -0
  161. /package/dist/agent-verifier/{project-state-K576C2TE.mjs.map → static-scaffold-MHVM63HU.mjs.map} +0 -0
  162. /package/dist/agent-verifier/{reducer-bundle-preflight-LXNJUBKL.mjs.map → workspace-codegen-SPPVHURX.mjs.map} +0 -0
  163. /package/dist/agent-verifier/{reducer-contract-preflight-TUMQ43JV.mjs.map → workspace-dependencies-5HEEKZFP.mjs.map} +0 -0
  164. /package/dist/{agent-verifier/reducer-native-test-harness-CHX5MBL5.mjs.map → authoring-compatibility-internal.js.map} +0 -0
  165. /package/dist/{agent-verifier/static-scaffold-R7SVDRQI.mjs.map → chunk-2H7UOFLK.js.map} +0 -0
  166. /package/dist/{agent-verifier/workspace-codegen-2ZMQRIKJ.mjs.map → global-config-GK2UC2X6.js.map} +0 -0
  167. /package/dist/{prompt-NDV3AE5L.js.map → prompt-GMZABCJC.js.map} +0 -0
  168. /package/{dist/scaffold → scaffold}/assets/static/app/tsconfig.framework.json +0 -0
  169. /package/{dist/scaffold → scaffold}/assets/static/app/tsconfig.json +0 -0
  170. /package/{dist/scaffold → scaffold}/assets/static/ui/index.tsx +0 -0
  171. /package/{dist/scaffold → scaffold}/assets/static/ui/style.css +0 -0
  172. /package/{dist/scaffold → scaffold}/assets/static/ui/tsconfig.framework.json +0 -0
  173. /package/{dist/scaffold → scaffold}/assets/static/ui/tsconfig.json +0 -0
@@ -0,0 +1,3735 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ CLIENT_PROBLEM_TYPES,
4
+ REDUCER_TESTING_TYPES_WRAPPER_CONTENT,
5
+ SERVER_PROBLEM_TYPES,
6
+ buildReducerTestingContractContent,
7
+ client,
8
+ createGameplayCapability,
9
+ createProjectSessionFromReducerSnapshot,
10
+ createRepoLocalPackageResolutionPlugin,
11
+ external_exports,
12
+ findProjectRoot,
13
+ getJob,
14
+ getProjectCompiledResult,
15
+ getSessionSnapshot,
16
+ hashContent,
17
+ listProjectCompiledResults,
18
+ loadManifest,
19
+ loadProjectConfig,
20
+ readWorkspaceTextFileIfExists,
21
+ resolveCliRepoRoot,
22
+ resolveWorkspacePath,
23
+ workspacePathExists,
24
+ writeWorkspaceJsonFile,
25
+ writeWorkspaceTextFile,
26
+ zProblemDetails
27
+ } from "./chunk-I4SZ7FA4.js";
28
+ import {
29
+ clearCredentials,
30
+ getStoredSession,
31
+ loadGlobalConfig,
32
+ setCredentials,
33
+ withCredentialLock
34
+ } from "./chunk-UI7NWSYA.js";
35
+ import {
36
+ DEFAULT_API_BASE_URL,
37
+ DEFAULT_WEB_BASE_URL,
38
+ ENVIRONMENT_CONFIGS,
39
+ PROJECT_DIR_NAME,
40
+ ensureDir,
41
+ exists
42
+ } from "./chunk-EQNBQVIW.js";
43
+
44
+ // src/build-target.ts
45
+ var injectedBuildChannel = true ? "published" : void 0;
46
+ var BUILD_CHANNEL = injectedBuildChannel === "published" ? "published" : "development";
47
+ var IS_PUBLISHED_BUILD = BUILD_CHANNEL === "published";
48
+ var PUBLISHED_ENVIRONMENT = "prod";
49
+
50
+ // src/auth/clerk-oauth.ts
51
+ import crypto from "crypto";
52
+ function createPkcePair() {
53
+ const verifier = base64Url(crypto.randomBytes(32));
54
+ const challenge = base64Url(
55
+ crypto.createHash("sha256").update(verifier).digest()
56
+ );
57
+ return { verifier, challenge };
58
+ }
59
+ function buildClerkAuthorizationUrl(input) {
60
+ const { issuer, clientId, scope } = assertConfigured(input.config);
61
+ const url = new URL("/oauth/authorize", issuer);
62
+ url.searchParams.set("response_type", "code");
63
+ url.searchParams.set("client_id", clientId);
64
+ url.searchParams.set("redirect_uri", input.redirectUri);
65
+ url.searchParams.set("state", input.state);
66
+ url.searchParams.set("code_challenge", input.codeChallenge);
67
+ url.searchParams.set("code_challenge_method", "S256");
68
+ url.searchParams.set("scope", scope ?? "openid profile email offline_access");
69
+ return url;
70
+ }
71
+ async function exchangeClerkOAuthCode(input) {
72
+ const { clientId, tokenUrl } = assertConfigured(input.config);
73
+ const body = new URLSearchParams({
74
+ grant_type: "authorization_code",
75
+ client_id: clientId,
76
+ code: input.code,
77
+ redirect_uri: input.redirectUri,
78
+ code_verifier: input.codeVerifier
79
+ });
80
+ return requestClerkToken(tokenUrl, body);
81
+ }
82
+ async function refreshClerkOAuthToken(input) {
83
+ const { clientId, tokenUrl } = assertConfigured(input.config);
84
+ const body = new URLSearchParams({
85
+ grant_type: "refresh_token",
86
+ client_id: clientId,
87
+ refresh_token: input.refreshToken
88
+ });
89
+ return requestClerkToken(tokenUrl, body);
90
+ }
91
+ function assertConfigured(config) {
92
+ const issuer = config.issuer?.trim().replace(/\/$/, "");
93
+ const clientId = config.clientId?.trim();
94
+ if (!issuer || !clientId) {
95
+ throw new Error(
96
+ [
97
+ "Clerk OAuth CLI is not configured for this environment.",
98
+ "The CLI expects first-party environments to be configured in its built-in registry.",
99
+ "If this environment has no registered public Clerk OAuth client, create one and release a CLI with its client id.",
100
+ "For emergency overrides, set the environment-specific DREAMBOARD_<ENV>_CLERK_OAUTH_* variables or DREAMBOARD_CLERK_OAUTH_*.",
101
+ "For local harness auth, use `pnpm auth:local` or the auto-bootstrapped local harness flows instead."
102
+ ].join(" ")
103
+ );
104
+ }
105
+ return {
106
+ issuer,
107
+ clientId,
108
+ tokenUrl: config.tokenUrl?.trim() || new URL("/oauth/token", issuer).toString(),
109
+ scope: config.scope?.trim() || void 0
110
+ };
111
+ }
112
+ async function requestClerkToken(tokenUrl, body) {
113
+ const response = await fetch(tokenUrl, {
114
+ method: "POST",
115
+ headers: {
116
+ "Content-Type": "application/x-www-form-urlencoded",
117
+ Accept: "application/json"
118
+ },
119
+ body
120
+ });
121
+ if (!response.ok) {
122
+ const detail = await response.text();
123
+ throw new Error(
124
+ `Clerk OAuth token request failed (${response.status}): ${detail}`
125
+ );
126
+ }
127
+ const payload = await response.json();
128
+ if (typeof payload.access_token !== "string") {
129
+ throw new Error("Clerk OAuth token response did not include access_token.");
130
+ }
131
+ if (typeof payload.refresh_token !== "string") {
132
+ throw new Error(
133
+ "Clerk OAuth token response did not include refresh_token."
134
+ );
135
+ }
136
+ const expiresAt = typeof payload.expires_in === "number" ? new Date(Date.now() + payload.expires_in * 1e3).toISOString() : void 0;
137
+ return {
138
+ accessToken: payload.access_token,
139
+ refreshToken: payload.refresh_token,
140
+ expiresAt,
141
+ tokenUrl
142
+ };
143
+ }
144
+ function base64Url(bytes) {
145
+ return bytes.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
146
+ }
147
+
148
+ // src/auth/token-exchange.ts
149
+ async function exchangeDreamboardUserToken(input) {
150
+ const fetchImpl = input.fetchImpl ?? globalThis.fetch.bind(globalThis);
151
+ const response = await fetchImpl(
152
+ new URL("/api/auth/token-exchange", input.apiBaseUrl),
153
+ {
154
+ method: "POST",
155
+ headers: {
156
+ Authorization: `Bearer ${input.clerkAccessToken}`,
157
+ "Content-Type": "application/json",
158
+ Accept: "application/json"
159
+ },
160
+ body: JSON.stringify({ audience: input.audience })
161
+ }
162
+ );
163
+ if (!response.ok) {
164
+ throw new Error(
165
+ `Dreamboard token exchange failed (${response.status}). Run \`dreamboard auth login\` to authenticate again.`
166
+ );
167
+ }
168
+ const payload = await response.json();
169
+ if (typeof payload.accessToken !== "string" || payload.accessToken === "") {
170
+ throw new Error("Dreamboard token exchange response omitted accessToken.");
171
+ }
172
+ if (payload.tokenType !== "Bearer") {
173
+ throw new Error(
174
+ "Dreamboard token exchange response had invalid tokenType."
175
+ );
176
+ }
177
+ if (payload.audience !== input.audience) {
178
+ throw new Error("Dreamboard token exchange response had wrong audience.");
179
+ }
180
+ const expiresIn = typeof payload.expiresIn === "number" && Number.isFinite(payload.expiresIn) ? payload.expiresIn : void 0;
181
+ return {
182
+ accessToken: payload.accessToken,
183
+ tokenType: "Bearer",
184
+ audience: input.audience,
185
+ expiresIn,
186
+ expiresAt: expiresIn === void 0 ? void 0 : new Date(Date.now() + expiresIn * 1e3).toISOString()
187
+ };
188
+ }
189
+
190
+ // src/auth/user-token-manager.ts
191
+ var TOKEN_REFRESH_WINDOW_MS = 60 * 1e3;
192
+ function createUserTokenManager(config) {
193
+ return {
194
+ async resolveApiToken() {
195
+ const localOrInjected = resolveNonStoredToken(config, "dreamboard-api");
196
+ if (localOrInjected) return localOrInjected;
197
+ if (!usesStoredSession(config)) return null;
198
+ return withCredentialLock(async (ops) => {
199
+ const stored = await ops.read();
200
+ const apiToken = freshStoredApiToken(stored);
201
+ if (apiToken) return apiToken;
202
+ const clerk = await resolveFreshClerkAccessToken(config, stored);
203
+ const exchanged = await exchangeDreamboardUserToken({
204
+ apiBaseUrl: config.apiBaseUrl,
205
+ clerkAccessToken: clerk.accessToken,
206
+ audience: "dreamboard-api"
207
+ });
208
+ await ops.writeFull({
209
+ ...clerk,
210
+ dreamboardApiToken: exchanged.accessToken,
211
+ dreamboardApiExpiresAt: exchanged.expiresAt
212
+ });
213
+ return {
214
+ token: exchanged.accessToken,
215
+ expiresAt: exchanged.expiresAt,
216
+ audience: "dreamboard-api"
217
+ };
218
+ });
219
+ },
220
+ async resolveGitToken() {
221
+ if (!usesStoredSession(config) && config.authToken) {
222
+ const exchanged = await exchangeDreamboardUserToken({
223
+ apiBaseUrl: config.apiBaseUrl,
224
+ clerkAccessToken: config.authToken,
225
+ audience: "dreamboard-git"
226
+ });
227
+ return {
228
+ token: exchanged.accessToken,
229
+ expiresAt: exchanged.expiresAt,
230
+ audience: "dreamboard-git"
231
+ };
232
+ }
233
+ if (!usesStoredSession(config)) {
234
+ throw new Error(
235
+ "Missing Dreamboard session. Run `dreamboard auth login` to authenticate."
236
+ );
237
+ }
238
+ return withCredentialLock(async (ops) => {
239
+ const stored = await ops.read();
240
+ const clerk = await resolveFreshClerkAccessToken(config, stored);
241
+ const exchanged = await exchangeDreamboardUserToken({
242
+ apiBaseUrl: config.apiBaseUrl,
243
+ clerkAccessToken: clerk.accessToken,
244
+ audience: "dreamboard-git"
245
+ });
246
+ await ops.writeFull(clerk);
247
+ return {
248
+ token: exchanged.accessToken,
249
+ expiresAt: exchanged.expiresAt,
250
+ audience: "dreamboard-git"
251
+ };
252
+ });
253
+ },
254
+ async logout() {
255
+ await clearCredentials("user_token_manager_logout");
256
+ }
257
+ };
258
+ }
259
+ function resolveNonStoredToken(config, audience) {
260
+ if (usesStoredSession(config)) return null;
261
+ if (!config.authToken) return null;
262
+ return {
263
+ token: config.authToken,
264
+ expiresAt: config.tokenExpiresAt,
265
+ audience
266
+ };
267
+ }
268
+ function freshStoredApiToken(stored) {
269
+ if (!stored?.dreamboardApiToken) return null;
270
+ if (isFresh(stored.dreamboardApiExpiresAt, stored.dreamboardApiToken)) {
271
+ return {
272
+ token: stored.dreamboardApiToken,
273
+ expiresAt: stored.dreamboardApiExpiresAt,
274
+ audience: "dreamboard-api"
275
+ };
276
+ }
277
+ return null;
278
+ }
279
+ async function resolveFreshClerkAccessToken(config, stored) {
280
+ const accessToken = stored?.accessToken ?? config.clerkAccessToken;
281
+ const refreshToken = stored?.refreshToken ?? config.refreshToken;
282
+ const tokenExpiresAt = stored?.tokenExpiresAt ?? config.clerkAccessExpiresAt;
283
+ if (!refreshToken) {
284
+ throw new Error(
285
+ "Stored Dreamboard session is missing its refresh token. Run `dreamboard auth login` to authenticate again."
286
+ );
287
+ }
288
+ if (accessToken && isFresh(tokenExpiresAt, accessToken)) {
289
+ return {
290
+ accessToken,
291
+ refreshToken,
292
+ tokenExpiresAt,
293
+ dreamboardApiToken: stored?.dreamboardApiToken,
294
+ dreamboardApiExpiresAt: stored?.dreamboardApiExpiresAt,
295
+ clerkOAuthIssuer: stored?.clerkOAuthIssuer ?? config.clerkOAuthIssuer,
296
+ clerkOAuthClientId: stored?.clerkOAuthClientId ?? config.clerkOAuthClientId,
297
+ clerkOAuthTokenUrl: stored?.clerkOAuthTokenUrl ?? config.clerkOAuthTokenUrl,
298
+ environment: stored?.environment ?? config.environment
299
+ };
300
+ }
301
+ const payload = await refreshClerkOAuthToken({
302
+ config: {
303
+ issuer: stored?.clerkOAuthIssuer ?? config.clerkOAuthIssuer,
304
+ clientId: stored?.clerkOAuthClientId ?? config.clerkOAuthClientId,
305
+ tokenUrl: stored?.clerkOAuthTokenUrl ?? config.clerkOAuthTokenUrl
306
+ },
307
+ refreshToken
308
+ });
309
+ return {
310
+ accessToken: payload.accessToken,
311
+ refreshToken: payload.refreshToken,
312
+ tokenExpiresAt: payload.expiresAt,
313
+ clerkOAuthIssuer: stored?.clerkOAuthIssuer ?? config.clerkOAuthIssuer,
314
+ clerkOAuthClientId: stored?.clerkOAuthClientId ?? config.clerkOAuthClientId,
315
+ clerkOAuthTokenUrl: payload.tokenUrl,
316
+ environment: stored?.environment ?? config.environment
317
+ };
318
+ }
319
+ function isFresh(expiresAt, token) {
320
+ const expiry = expiresAt ? new Date(expiresAt) : getJwtExpiry(token);
321
+ return expiry !== null && Number.isFinite(expiry.getTime()) && expiry.getTime() > Date.now() + TOKEN_REFRESH_WINDOW_MS;
322
+ }
323
+ function getJwtExpiry(accessToken) {
324
+ if (!accessToken) return null;
325
+ const parts = accessToken.split(".");
326
+ if (parts.length !== 3) return null;
327
+ try {
328
+ const payload = JSON.parse(
329
+ Buffer.from(parts[1], "base64url").toString("utf8")
330
+ );
331
+ if (typeof payload.exp !== "number" || !Number.isFinite(payload.exp)) {
332
+ return null;
333
+ }
334
+ return new Date(payload.exp * 1e3);
335
+ } catch {
336
+ return null;
337
+ }
338
+ }
339
+ function usesStoredSession(config) {
340
+ return config.refreshTokenSource === "global";
341
+ }
342
+
343
+ // src/config/local-harness-auth.ts
344
+ import { createHmac, randomUUID } from "crypto";
345
+ var DEFAULT_SUBJECT = "harness-smoke-local@dreamboard.local";
346
+ var DEFAULT_ISSUER = "dreamboard-local-harness";
347
+ var DEFAULT_SECRET = "dreamboard-local-harness-token-secret";
348
+ var LOCAL_AWS_ISSUER = "dreamboard-local-aws-harness";
349
+ var LOCAL_AWS_SECRET = "dreamboard-local-aws-harness-token-secret";
350
+ var DEFAULT_TTL_SECONDS = 8 * 60 * 60;
351
+ var mintedTokens = /* @__PURE__ */ new Map();
352
+ function resolveLocalHarnessAccessToken(config) {
353
+ if (IS_PUBLISHED_BUILD || config.environment !== "local") {
354
+ return void 0;
355
+ }
356
+ const profile = inferLocalHarnessProfile(config);
357
+ if (config.authToken && (profile !== "local-aws" || isExplicitTokenSource(config.authTokenSource))) {
358
+ return void 0;
359
+ }
360
+ const cacheKey = [
361
+ profile,
362
+ process.env.LOCAL_HARNESS_TOKEN_ISSUER ?? "",
363
+ process.env.LOCAL_HARNESS_TOKEN_SECRET ?? "",
364
+ process.env.LOCAL_HARNESS_SUBJECT ?? "",
365
+ process.env.HARNESS_USER_EMAIL ?? "",
366
+ process.env.LOCAL_HARNESS_EMAIL ?? "",
367
+ process.env.LOCAL_HARNESS_TOKEN_TTL_SECONDS ?? ""
368
+ ].join("\0");
369
+ const cached = mintedTokens.get(cacheKey);
370
+ if (cached) return cached;
371
+ const token = mintLocalHarnessToken(profile);
372
+ mintedTokens.set(cacheKey, token);
373
+ return token;
374
+ }
375
+ function isExplicitTokenSource(source) {
376
+ return source === "flag" || source === "env" || source === "agent-env";
377
+ }
378
+ function inferLocalHarnessProfile(config) {
379
+ return isLocalAwsUrl(config.apiBaseUrl) || isLocalAwsUrl(config.webBaseUrl) ? "local-aws" : "local";
380
+ }
381
+ function mintLocalHarnessToken(profile) {
382
+ const subject = envValue(process.env.LOCAL_HARNESS_SUBJECT) ?? envValue(process.env.HARNESS_USER_EMAIL) ?? DEFAULT_SUBJECT;
383
+ const email = envValue(process.env.LOCAL_HARNESS_EMAIL) ?? (subject.includes("@") ? subject : void 0);
384
+ const issuer = envValue(process.env.LOCAL_HARNESS_TOKEN_ISSUER) ?? (profile === "local-aws" ? LOCAL_AWS_ISSUER : DEFAULT_ISSUER);
385
+ const secret = envValue(process.env.LOCAL_HARNESS_TOKEN_SECRET) ?? (profile === "local-aws" ? LOCAL_AWS_SECRET : DEFAULT_SECRET);
386
+ const ttlSeconds = Number(
387
+ envValue(process.env.LOCAL_HARNESS_TOKEN_TTL_SECONDS) ?? String(DEFAULT_TTL_SECONDS)
388
+ );
389
+ if (!Number.isFinite(ttlSeconds) || ttlSeconds <= 0) {
390
+ throw new Error(
391
+ "LOCAL_HARNESS_TOKEN_TTL_SECONDS must be a positive number."
392
+ );
393
+ }
394
+ const now = Math.floor(Date.now() / 1e3);
395
+ const payload = {
396
+ typ: "local_harness_access",
397
+ dreamboard_provider: "local-harness",
398
+ dreamboard_provider_subject: subject,
399
+ ...email ? { email } : {},
400
+ iss: issuer,
401
+ sub: subject,
402
+ iat: now,
403
+ exp: now + Math.floor(ttlSeconds),
404
+ jti: randomUUID()
405
+ };
406
+ const headerPart = base64UrlJson({ alg: "HS256", typ: "JWT" });
407
+ const payloadPart = base64UrlJson(payload);
408
+ const signature = createHmac("sha256", secret).update(`${headerPart}.${payloadPart}`).digest("base64url");
409
+ return `${headerPart}.${payloadPart}.${signature}`;
410
+ }
411
+ function base64UrlJson(value) {
412
+ return Buffer.from(JSON.stringify(value), "utf8").toString("base64url");
413
+ }
414
+ function envValue(raw) {
415
+ return typeof raw === "string" && raw.trim().length > 0 ? raw.trim() : void 0;
416
+ }
417
+ function isLocalAwsUrl(rawUrl) {
418
+ if (!rawUrl) return false;
419
+ try {
420
+ const url = new URL(rawUrl);
421
+ return (url.hostname === "localhost" || url.hostname === "127.0.0.1") && (url.port === "18080" || url.port === "8088");
422
+ } catch {
423
+ return false;
424
+ }
425
+ }
426
+
427
+ // src/config/resolve.ts
428
+ var DEFAULT_REFRESH_WINDOW_MS = 5 * 60 * 1e3;
429
+ var TRANSIENT_READ_RETRY_DELAYS_MS = [100, 300];
430
+ function resolveConfig(globalConfig, flags, project, credentials) {
431
+ if (IS_PUBLISHED_BUILD) {
432
+ assertPublicRuntimeFlags(flags);
433
+ }
434
+ const envEnvironment = IS_PUBLISHED_BUILD ? void 0 : environmentFromProcess();
435
+ const projectEnvironment = IS_PUBLISHED_BUILD ? void 0 : project?.environment;
436
+ const environment = IS_PUBLISHED_BUILD ? PUBLISHED_ENVIRONMENT : flags.env || envEnvironment || projectEnvironment || globalConfig.environment || "staging";
437
+ const envConfig = ENVIRONMENT_CONFIGS[environment];
438
+ const publishedEnvConfig = ENVIRONMENT_CONFIGS[PUBLISHED_ENVIRONMENT];
439
+ const hasExplicitEnvironmentOverride = !IS_PUBLISHED_BUILD && Boolean(flags.env || envEnvironment || projectEnvironment);
440
+ const resolvedApiBaseUrl = IS_PUBLISHED_BUILD ? publishedEnvConfig?.apiBaseUrl ?? DEFAULT_API_BASE_URL : hasExplicitEnvironmentOverride ? projectLocalBaseUrl(project?.apiBaseUrl, environment) || envConfig?.apiBaseUrl || DEFAULT_API_BASE_URL : project?.apiBaseUrl || envConfig?.apiBaseUrl || DEFAULT_API_BASE_URL;
441
+ const apiBaseUrl = valueOrUndefined(process.env.DREAMBOARD_API_BASE_URL) ?? resolvedApiBaseUrl;
442
+ const resolvedWebBaseUrl = IS_PUBLISHED_BUILD ? publishedEnvConfig?.webBaseUrl ?? DEFAULT_WEB_BASE_URL : hasExplicitEnvironmentOverride ? projectLocalBaseUrl(project?.webBaseUrl, environment) || envConfig?.webBaseUrl || DEFAULT_WEB_BASE_URL : project?.webBaseUrl || envConfig?.webBaseUrl || DEFAULT_WEB_BASE_URL;
443
+ const webBaseUrl = valueOrUndefined(process.env.DREAMBOARD_WEB_BASE_URL) ?? resolvedWebBaseUrl;
444
+ const snapshot = buildCredentialSnapshot(flags, credentials, environment);
445
+ const oauthConfig = resolveEnvironmentOAuthConfig(environment, envConfig);
446
+ return {
447
+ environment,
448
+ apiBaseUrl,
449
+ webBaseUrl,
450
+ authToken: snapshot.dreamboardApiToken ?? (snapshot.refreshToken ? void 0 : snapshot.accessToken),
451
+ refreshToken: snapshot.refreshToken,
452
+ tokenExpiresAt: snapshot.dreamboardApiExpiresAt ?? (snapshot.refreshToken ? void 0 : snapshot.tokenExpiresAt),
453
+ clerkAccessToken: snapshot.accessToken,
454
+ clerkAccessExpiresAt: snapshot.tokenExpiresAt,
455
+ dreamboardApiToken: snapshot.dreamboardApiToken,
456
+ dreamboardApiExpiresAt: snapshot.dreamboardApiExpiresAt,
457
+ clerkOAuthIssuer: snapshot.clerkOAuthIssuer ?? oauthConfig.issuer,
458
+ clerkOAuthClientId: snapshot.clerkOAuthClientId ?? oauthConfig.clientId,
459
+ clerkOAuthTokenUrl: snapshot.clerkOAuthTokenUrl ?? oauthConfig.tokenUrl,
460
+ clerkOAuthScope: oauthConfig.scope,
461
+ authTokenSource: snapshot.authTokenSource,
462
+ refreshTokenSource: snapshot.refreshTokenSource
463
+ };
464
+ }
465
+ function resolveEnvironmentOAuthConfig(environment, envConfig) {
466
+ const prefix = environment.toUpperCase();
467
+ return {
468
+ issuer: valueOrUndefined(
469
+ process.env[`DREAMBOARD_${prefix}_CLERK_OAUTH_ISSUER`]
470
+ ) ?? valueOrUndefined(process.env.DREAMBOARD_CLERK_OAUTH_ISSUER) ?? envConfig?.clerkOAuthIssuer,
471
+ clientId: valueOrUndefined(
472
+ process.env[`DREAMBOARD_${prefix}_CLERK_OAUTH_CLIENT_ID`]
473
+ ) ?? valueOrUndefined(process.env.DREAMBOARD_CLERK_OAUTH_CLIENT_ID) ?? envConfig?.clerkOAuthClientId,
474
+ tokenUrl: valueOrUndefined(
475
+ process.env[`DREAMBOARD_${prefix}_CLERK_OAUTH_TOKEN_URL`]
476
+ ) ?? valueOrUndefined(process.env.DREAMBOARD_CLERK_OAUTH_TOKEN_URL) ?? envConfig?.clerkOAuthTokenUrl,
477
+ scope: valueOrUndefined(process.env[`DREAMBOARD_${prefix}_CLERK_OAUTH_SCOPE`]) ?? valueOrUndefined(process.env.DREAMBOARD_CLERK_OAUTH_SCOPE) ?? envConfig?.clerkOAuthScope
478
+ };
479
+ }
480
+ function buildCredentialSnapshot(flags, storedCredentials, environment) {
481
+ const flagToken = valueOrUndefined(flags.token);
482
+ const agentEnvToken = valueOrUndefined(process.env.DREAMBOARD_AGENT_TOKEN);
483
+ const envToken = valueOrUndefined(process.env.DREAMBOARD_TOKEN);
484
+ const environmentScopedStoredCredentials = storedCredentials?.environment && environment && storedCredentials.environment !== environment ? null : storedCredentials ?? null;
485
+ if (IS_PUBLISHED_BUILD) {
486
+ const stored = environmentScopedStoredCredentials;
487
+ if (agentEnvToken) {
488
+ return {
489
+ accessToken: agentEnvToken,
490
+ refreshToken: void 0,
491
+ tokenExpiresAt: void 0,
492
+ authTokenSource: "agent-env",
493
+ refreshTokenSource: "none"
494
+ };
495
+ }
496
+ return {
497
+ accessToken: stored?.accessToken,
498
+ refreshToken: stored?.refreshToken,
499
+ tokenExpiresAt: stored?.tokenExpiresAt,
500
+ dreamboardApiToken: stored?.dreamboardApiToken,
501
+ dreamboardApiExpiresAt: stored?.dreamboardApiExpiresAt,
502
+ clerkOAuthIssuer: stored?.clerkOAuthIssuer,
503
+ clerkOAuthClientId: stored?.clerkOAuthClientId,
504
+ clerkOAuthTokenUrl: stored?.clerkOAuthTokenUrl,
505
+ environment: stored?.environment,
506
+ authTokenSource: stored?.dreamboardApiToken || stored?.accessToken && !stored.refreshToken ? "global" : "none",
507
+ refreshTokenSource: stored?.refreshToken ? "global" : "none"
508
+ };
509
+ }
510
+ const accessToken = flagToken || agentEnvToken || envToken || environmentScopedStoredCredentials?.accessToken;
511
+ const refreshToken = environmentScopedStoredCredentials?.refreshToken;
512
+ const authTokenSource = flagToken ? "flag" : agentEnvToken ? "agent-env" : envToken ? "env" : environmentScopedStoredCredentials?.accessToken ? "global" : "none";
513
+ const refreshTokenSource = environmentScopedStoredCredentials?.refreshToken ? "global" : "none";
514
+ return {
515
+ accessToken,
516
+ refreshToken,
517
+ tokenExpiresAt: environmentScopedStoredCredentials?.tokenExpiresAt,
518
+ dreamboardApiToken: environmentScopedStoredCredentials?.dreamboardApiToken,
519
+ dreamboardApiExpiresAt: environmentScopedStoredCredentials?.dreamboardApiExpiresAt,
520
+ clerkOAuthIssuer: environmentScopedStoredCredentials?.clerkOAuthIssuer,
521
+ clerkOAuthClientId: environmentScopedStoredCredentials?.clerkOAuthClientId,
522
+ clerkOAuthTokenUrl: environmentScopedStoredCredentials?.clerkOAuthTokenUrl,
523
+ environment: environmentScopedStoredCredentials?.environment,
524
+ authTokenSource,
525
+ refreshTokenSource
526
+ };
527
+ }
528
+ function environmentFromProcess() {
529
+ const value = valueOrUndefined(process.env.DREAMBOARD_ENV);
530
+ if (!value) return void 0;
531
+ if (value === "local" || value === "staging" || value === "prod") {
532
+ return value;
533
+ }
534
+ throw new Error(
535
+ `Invalid DREAMBOARD_ENV '${value}'. Valid options: local, staging, prod`
536
+ );
537
+ }
538
+ function projectLocalBaseUrl(rawUrl, environment) {
539
+ if (environment !== "local" || !rawUrl) return void 0;
540
+ try {
541
+ const url = new URL(rawUrl);
542
+ return url.hostname === "localhost" || url.hostname === "127.0.0.1" ? rawUrl : void 0;
543
+ } catch {
544
+ return void 0;
545
+ }
546
+ }
547
+ function assertPublicRuntimeFlags(flags) {
548
+ const argv = process.argv.slice(2);
549
+ if (flags.env || argv.includes("--env")) {
550
+ throw new Error(
551
+ "The published Dreamboard CLI is production-only and does not accept `--env`."
552
+ );
553
+ }
554
+ if (valueOrUndefined(flags.token) || argv.includes("--token")) {
555
+ throw new Error(
556
+ "Direct JWT injection is not supported in the published Dreamboard CLI. Use `dreamboard auth login` so the CLI can store and refresh your session."
557
+ );
558
+ }
559
+ if (process.env.DREAMBOARD_TOKEN) {
560
+ throw new Error(
561
+ "The published Dreamboard CLI ignores direct token environment variables. Use `dreamboard auth login` so the CLI can manage refreshable credentials."
562
+ );
563
+ }
564
+ }
565
+ async function configureClient(config) {
566
+ const localHarnessToken = resolveLocalHarnessAccessToken(config);
567
+ const resolvedToken = localHarnessToken ? { token: localHarnessToken } : await createUserTokenManager(config).resolveApiToken();
568
+ const effectiveAccessToken = resolvedToken?.token;
569
+ client.setConfig({
570
+ baseUrl: config.apiBaseUrl,
571
+ fetch: createRetryingReadFetch(globalThis.fetch.bind(globalThis)),
572
+ headers: effectiveAccessToken ? { Authorization: `Bearer ${effectiveAccessToken}` } : {}
573
+ });
574
+ }
575
+ function createRetryingReadFetch(fetchImpl) {
576
+ return (async (input, init) => {
577
+ const method = resolveFetchMethod(input, init);
578
+ if (method !== "GET" && method !== "HEAD") {
579
+ return fetchImpl(input, init);
580
+ }
581
+ let lastError;
582
+ for (let attempt = 0; attempt <= TRANSIENT_READ_RETRY_DELAYS_MS.length; attempt += 1) {
583
+ try {
584
+ return await fetchImpl(input, init);
585
+ } catch (error) {
586
+ lastError = error;
587
+ if (attempt >= TRANSIENT_READ_RETRY_DELAYS_MS.length || !isTransientFetchError(error)) {
588
+ throw error;
589
+ }
590
+ await sleep(TRANSIENT_READ_RETRY_DELAYS_MS[attempt]);
591
+ }
592
+ }
593
+ throw lastError;
594
+ });
595
+ }
596
+ function resolveFetchMethod(input, init) {
597
+ const method = init?.method ?? (typeof Request !== "undefined" && input instanceof Request ? input.method : void 0);
598
+ return (method ?? "GET").toUpperCase();
599
+ }
600
+ function isTransientFetchError(error) {
601
+ const message = error instanceof Error ? error.message : typeof error === "object" && error !== null && "message" in error ? String(error.message) : String(error);
602
+ const normalized = message.toLowerCase();
603
+ return normalized.includes("fetch failed") || normalized.includes("network") || normalized.includes("timeout") || normalized.includes("econnreset") || normalized.includes("econnrefused") || normalized.includes("socket");
604
+ }
605
+ function sleep(ms) {
606
+ return new Promise((resolve) => setTimeout(resolve, ms));
607
+ }
608
+ async function refreshResolvedAuthSession(config) {
609
+ if (!usesStoredSession2(config)) return null;
610
+ if (config.refreshToken) {
611
+ return refreshClerkOAuthSession(config);
612
+ }
613
+ return null;
614
+ }
615
+ async function refreshClerkOAuthSession(config) {
616
+ if (!config.refreshToken) return null;
617
+ const payload = await refreshClerkOAuthToken({
618
+ config: {
619
+ issuer: config.clerkOAuthIssuer,
620
+ clientId: config.clerkOAuthClientId,
621
+ tokenUrl: config.clerkOAuthTokenUrl
622
+ },
623
+ refreshToken: config.refreshToken
624
+ });
625
+ const credentials = {
626
+ accessToken: payload.accessToken,
627
+ refreshToken: payload.refreshToken,
628
+ tokenExpiresAt: payload.expiresAt,
629
+ clerkOAuthIssuer: config.clerkOAuthIssuer,
630
+ clerkOAuthClientId: config.clerkOAuthClientId,
631
+ clerkOAuthTokenUrl: payload.tokenUrl,
632
+ environment: config.environment
633
+ };
634
+ await setCredentials(credentials);
635
+ return credentials;
636
+ }
637
+ function requireAuth(config) {
638
+ if (!config.authToken && !config.refreshToken && !resolveLocalHarnessAccessToken(config)) {
639
+ throw new Error(
640
+ "Missing Dreamboard session. Run `dreamboard auth login` to authenticate."
641
+ );
642
+ }
643
+ }
644
+ function valueOrUndefined(value) {
645
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
646
+ }
647
+ function getAuthTokenExpiry(accessToken) {
648
+ if (!accessToken) return null;
649
+ const parts = accessToken.split(".");
650
+ if (parts.length !== 3) return null;
651
+ try {
652
+ const payload = JSON.parse(
653
+ Buffer.from(parts[1], "base64url").toString("utf8")
654
+ );
655
+ if (typeof payload.exp !== "number" || !Number.isFinite(payload.exp)) {
656
+ return null;
657
+ }
658
+ return new Date(payload.exp * 1e3);
659
+ } catch {
660
+ return null;
661
+ }
662
+ }
663
+ function usesStoredSession2(config) {
664
+ return config.refreshTokenSource === "global";
665
+ }
666
+ async function loadProjectContextCredentials(requireAuth2, loadCredentials = getStoredSession) {
667
+ return requireAuth2 ? loadCredentials() : void 0;
668
+ }
669
+ async function resolveProjectContext(flags, opts) {
670
+ const projectRoot = await findProjectRoot(process.cwd());
671
+ if (!projectRoot) {
672
+ throw new Error(
673
+ "Not inside a dreamboard project (missing .dreamboard/project.json)."
674
+ );
675
+ }
676
+ const projectConfig = await loadProjectConfig(projectRoot);
677
+ const requireAuthForContext = opts?.requireAuth !== false;
678
+ const [globalConfig, credentials] = await Promise.all([
679
+ loadGlobalConfig(),
680
+ loadProjectContextCredentials(requireAuthForContext)
681
+ ]);
682
+ const config = resolveConfig(globalConfig, flags, projectConfig, credentials);
683
+ if (requireAuthForContext) {
684
+ requireAuth(config);
685
+ await configureClient(config);
686
+ }
687
+ return { projectRoot, projectConfig, config };
688
+ }
689
+
690
+ // src/flags.ts
691
+ var configFlagsSchema = external_exports.object({
692
+ env: external_exports.enum(["local", "staging", "prod"]).optional(),
693
+ token: external_exports.string().optional()
694
+ });
695
+ var ruleInputFlagsSchema = external_exports.object({
696
+ "rule-file": external_exports.string().optional(),
697
+ rule: external_exports.string().optional()
698
+ });
699
+ var playerCountFlagsSchema = external_exports.object({
700
+ players: external_exports.string().optional(),
701
+ "player-count": external_exports.string().optional()
702
+ });
703
+ var newCommandArgsSchema = configFlagsSchema.extend({
704
+ slug: external_exports.string().min(1),
705
+ description: external_exports.string().min(1),
706
+ force: external_exports.boolean().default(false),
707
+ "wait-timeout-ms": external_exports.string().optional(),
708
+ "repository-poll-interval-ms": external_exports.string().optional()
709
+ });
710
+ var cloneCommandArgsSchema = configFlagsSchema.extend({
711
+ slug: external_exports.string().min(1),
712
+ "wait-timeout-ms": external_exports.string().optional(),
713
+ "repository-poll-interval-ms": external_exports.string().optional()
714
+ });
715
+ var queryCommandArgsSchema = configFlagsSchema.extend({
716
+ title: external_exports.string().min(1)
717
+ });
718
+ var pullCommandArgsSchema = configFlagsSchema.extend({
719
+ force: external_exports.boolean().default(false)
720
+ });
721
+ var syncCommandArgsSchema = configFlagsSchema.extend({
722
+ force: external_exports.boolean().default(false),
723
+ yes: external_exports.boolean().default(false)
724
+ });
725
+ var compileCommandArgsSchema = configFlagsSchema.extend({
726
+ debug: external_exports.boolean().default(false),
727
+ "skip-local-check": external_exports.boolean().default(false)
728
+ });
729
+ var statusCommandArgsSchema = configFlagsSchema.extend({
730
+ json: external_exports.boolean().default(false)
731
+ });
732
+ var commitScopedCommandArgsSchema = configFlagsSchema.extend({
733
+ commit: external_exports.string().min(1),
734
+ json: external_exports.boolean().default(false)
735
+ });
736
+ var projectRepositoryCommandArgsSchema = configFlagsSchema.extend({
737
+ project: external_exports.string().min(1),
738
+ wait: external_exports.boolean().default(false),
739
+ "wait-timeout-ms": external_exports.string().optional(),
740
+ "repository-poll-interval-ms": external_exports.string().optional(),
741
+ json: external_exports.boolean().default(false)
742
+ });
743
+ var buildCommandArgsSchema = commitScopedCommandArgsSchema.extend({
744
+ profile: external_exports.enum(["preview", "release"]).optional().default("preview")
745
+ });
746
+ var releasePublishCommandArgsSchema = commitScopedCommandArgsSchema.extend({
747
+ yes: external_exports.boolean().default(false)
748
+ });
749
+ var devCommandArgsSchema = configFlagsSchema.extend({
750
+ seed: external_exports.string().optional(),
751
+ "setup-profile": external_exports.string().optional(),
752
+ players: external_exports.string().optional(),
753
+ "player-count": external_exports.string().optional(),
754
+ debug: external_exports.boolean().default(false),
755
+ resume: external_exports.string().optional(),
756
+ "from-scenario": external_exports.string().optional(),
757
+ "new-session": external_exports.boolean().default(false),
758
+ open: external_exports.boolean().default(false),
759
+ port: external_exports.string().optional(),
760
+ host: external_exports.union([external_exports.string(), external_exports.boolean()]).optional(),
761
+ "allowed-host": external_exports.string().optional()
762
+ });
763
+ var joinCommandArgsSchema = configFlagsSchema.extend({
764
+ session: external_exports.string().min(1).optional(),
765
+ player: external_exports.string().min(1),
766
+ "raw-events": external_exports.boolean().default(false)
767
+ });
768
+ var configCommandArgsSchema = configFlagsSchema.extend({
769
+ action: external_exports.string().optional().default("show"),
770
+ scope: external_exports.enum(["global", "workspace"]).optional().default("global")
771
+ });
772
+ var authCommandArgsSchema = external_exports.object({
773
+ action: external_exports.enum([
774
+ "set",
775
+ "login",
776
+ "logout",
777
+ "env",
778
+ "status",
779
+ "git-credential"
780
+ ]),
781
+ tokenValue: external_exports.string().optional(),
782
+ token: external_exports.string().optional(),
783
+ jwt: external_exports.boolean().optional(),
784
+ env: external_exports.enum(["local", "staging", "prod"]).optional()
785
+ });
786
+ function parseArgs(commandName, schema, args) {
787
+ const parsed = schema.safeParse(args);
788
+ if (parsed.success) {
789
+ return parsed.data;
790
+ }
791
+ const details = parsed.error.issues.map((issue) => {
792
+ const field = issue.path.length > 0 ? issue.path.join(".") : "args";
793
+ return `${field}: ${issue.message}`;
794
+ }).join("; ");
795
+ throw new Error(`Invalid arguments for '${commandName}': ${details}`);
796
+ }
797
+ function parseConfigFlags(args) {
798
+ return parseArgs("config-flags", configFlagsSchema, args);
799
+ }
800
+ function parsePlayerCountFlags(args) {
801
+ return parseArgs("player-count", playerCountFlagsSchema, args);
802
+ }
803
+ function parseNewCommandArgs(args) {
804
+ return parseArgs("new", newCommandArgsSchema, args);
805
+ }
806
+ function parseCloneCommandArgs(args) {
807
+ return parseArgs("clone", cloneCommandArgsSchema, args);
808
+ }
809
+ function parseCommitScopedCommandArgs(commandName, args) {
810
+ return parseArgs(commandName, commitScopedCommandArgsSchema, args);
811
+ }
812
+ function parseProjectRepositoryCommandArgs(commandName, args) {
813
+ return parseArgs(commandName, projectRepositoryCommandArgsSchema, args);
814
+ }
815
+ function parseBuildCommandArgs(args) {
816
+ return parseArgs("build", buildCommandArgsSchema, args);
817
+ }
818
+ function parseReleasePublishCommandArgs(args) {
819
+ return parseArgs("release publish", releasePublishCommandArgsSchema, args);
820
+ }
821
+ function parseDevCommandArgs(args) {
822
+ return parseArgs("dev", devCommandArgsSchema, args);
823
+ }
824
+ function parseAuthCommandArgs(args) {
825
+ return parseArgs("auth", authCommandArgsSchema, args);
826
+ }
827
+
828
+ // src/command-args.ts
829
+ var CONFIG_FLAG_ARGS = {
830
+ env: {
831
+ type: "string",
832
+ description: "Environment: local | staging | prod"
833
+ },
834
+ token: {
835
+ type: "string",
836
+ description: "Auth token (Dreamboard bearer JWT)"
837
+ }
838
+ };
839
+
840
+ // src/utils/problem-types.ts
841
+ var CLI_PROBLEM_TYPES = {
842
+ ...SERVER_PROBLEM_TYPES,
843
+ ...CLIENT_PROBLEM_TYPES
844
+ };
845
+
846
+ // src/utils/errors.ts
847
+ var STALE_CONTRACT_ARTIFACT_CODE = "STALE_CONTRACT_ARTIFACT";
848
+ var STALE_CONTRACT_ARTIFACT_EXIT_CODE = 42;
849
+ function isProblemViolationArray(value) {
850
+ return Array.isArray(value) && value.every(
851
+ (entry) => typeof entry === "object" && entry !== null && typeof entry.message === "string"
852
+ );
853
+ }
854
+ function isProblemDetails(value) {
855
+ return zProblemDetails.safeParse(value).success;
856
+ }
857
+ function coerceViolations(value) {
858
+ if (isProblemViolationArray(value)) {
859
+ return value;
860
+ }
861
+ if (Array.isArray(value) && value.every((entry) => typeof entry === "string")) {
862
+ return value.map((message) => ({ message }));
863
+ }
864
+ return void 0;
865
+ }
866
+ function getRequestId(response) {
867
+ return response?.headers?.get?.("X-Correlation-ID") ?? response?.headers?.get?.("x-correlation-id") ?? void 0;
868
+ }
869
+ function toApiProblem(error, response, fallback) {
870
+ if (isProblemDetails(error)) {
871
+ return {
872
+ ...error,
873
+ status: error.status || response?.status || 0,
874
+ requestId: error.requestId ?? getRequestId(response)
875
+ };
876
+ }
877
+ if (error instanceof Error) {
878
+ return {
879
+ type: CLI_PROBLEM_TYPES.TRANSPORT_ERROR,
880
+ title: response?.statusText || "API error",
881
+ status: response?.status ?? 0,
882
+ detail: error.message || fallback,
883
+ requestId: getRequestId(response)
884
+ };
885
+ }
886
+ if (error && typeof error === "object") {
887
+ const obj = error;
888
+ const detail2 = typeof obj.detail === "string" ? obj.detail : typeof obj.message === "string" ? obj.message : void 0;
889
+ const title = typeof obj.title === "string" ? obj.title : response?.statusText || "API error";
890
+ const violations = coerceViolations(obj.violations) ?? coerceViolations(obj.errors);
891
+ if (detail2) {
892
+ return {
893
+ type: typeof obj.type === "string" ? obj.type : CLI_PROBLEM_TYPES.UNKNOWN_API_ERROR,
894
+ title,
895
+ status: typeof obj.status === "number" ? obj.status : response?.status ?? 0,
896
+ detail: detail2,
897
+ requestId: typeof obj.requestId === "string" ? obj.requestId : getRequestId(response),
898
+ retryable: typeof obj.retryable === "boolean" ? obj.retryable : void 0,
899
+ context: typeof obj.context === "object" && obj.context !== null ? obj.context : void 0,
900
+ violations,
901
+ timestamp: typeof obj.timestamp === "string" ? obj.timestamp : void 0,
902
+ instance: typeof obj.instance === "string" ? obj.instance : void 0
903
+ };
904
+ }
905
+ }
906
+ const detail = typeof error === "string" ? error.trim() || fallback : fallback;
907
+ return {
908
+ type: CLI_PROBLEM_TYPES.UNKNOWN_API_ERROR,
909
+ title: response?.statusText || "API error",
910
+ status: response?.status ?? 0,
911
+ detail,
912
+ requestId: getRequestId(response)
913
+ };
914
+ }
915
+ function formatProblem(problem) {
916
+ const base = problem.detail || problem.title;
917
+ const violations = problem.violations && problem.violations.length > 0 ? ` (${problem.violations.map((entry) => entry.message).join("; ")})` : "";
918
+ const statusSuffix = problem.status && problem.status > 0 ? ` (HTTP ${problem.status})` : "";
919
+ return `${base}${violations}${statusSuffix}`;
920
+ }
921
+ var DreamboardApiError = class extends Error {
922
+ problem;
923
+ status;
924
+ requestId;
925
+ retryable;
926
+ constructor(problem, cause) {
927
+ super(formatProblem(problem), { cause });
928
+ this.name = "DreamboardApiError";
929
+ this.problem = problem;
930
+ this.status = problem.status;
931
+ this.requestId = problem.requestId;
932
+ this.retryable = problem.retryable;
933
+ }
934
+ };
935
+ function toDreamboardApiError(error, response, fallback) {
936
+ return new DreamboardApiError(toApiProblem(error, response, fallback), error);
937
+ }
938
+ function isDreamboardApiError(error) {
939
+ return error instanceof DreamboardApiError;
940
+ }
941
+ function getObjectStringProperty(value, property) {
942
+ return value && typeof value === "object" && typeof value[property] === "string" ? value[property] : void 0;
943
+ }
944
+ function isStaleContractArtifactMessage(message) {
945
+ return message.includes(STALE_CONTRACT_ARTIFACT_CODE) || message.includes("StaleContractArtifactError") || message.toLowerCase().includes("stale contract artifact");
946
+ }
947
+ function isStaleContractArtifactError(error) {
948
+ if (getObjectStringProperty(error, "code") === STALE_CONTRACT_ARTIFACT_CODE) {
949
+ return true;
950
+ }
951
+ if (getObjectStringProperty(error, "name") === "StaleContractArtifactError") {
952
+ return true;
953
+ }
954
+ const message = getObjectStringProperty(error, "message");
955
+ return message ? isStaleContractArtifactMessage(message) : false;
956
+ }
957
+ function getCliErrorExitCode(error) {
958
+ return isStaleContractArtifactError(error) ? STALE_CONTRACT_ARTIFACT_EXIT_CODE : 1;
959
+ }
960
+ function isGameNotFoundProblem(problem) {
961
+ return problem.status === 404 && (problem.detail?.startsWith("Game not found: ") === true || problem.instance?.includes("/source-blobs/upload-sessions") === true);
962
+ }
963
+ function getProblemResolution(problem) {
964
+ if (isGameNotFoundProblem(problem)) {
965
+ return [
966
+ "Verify the project binding with `dreamboard project status --commit <rev>` after pushing the exact commit.",
967
+ "If you meant to use an existing remote project, check that your selected account and environment point at the backend that has that project."
968
+ ].join(" ");
969
+ }
970
+ switch (problem.type) {
971
+ case CLI_PROBLEM_TYPES.UNAUTHORIZED:
972
+ return "Run `dreamboard auth login` to authenticate again.";
973
+ case CLI_PROBLEM_TYPES.FORBIDDEN:
974
+ return "Check that the signed-in account has access to this game, or run `dreamboard auth login` with the correct account.";
975
+ case CLI_PROBLEM_TYPES.TOO_MANY_REQUESTS:
976
+ return "Wait a moment, then retry the command.";
977
+ case CLI_PROBLEM_TYPES.TRANSPORT_ERROR:
978
+ return "Check that the selected Dreamboard server is reachable and try again later.";
979
+ case CLI_PROBLEM_TYPES.VALIDATION_FAILED:
980
+ return "Fix the validation issue above, then retry the command.";
981
+ case CLI_PROBLEM_TYPES.ACTIVE_JOB_CONFLICT:
982
+ return "Wait for the active job to finish, then retry the command.";
983
+ case CLI_PROBLEM_TYPES.GAME_SLUG_CONFLICT:
984
+ return "Choose a different game slug, or use the existing workspace for that slug.";
985
+ case CLI_PROBLEM_TYPES.SOURCE_REVISION_NOT_FOUND:
986
+ return "Push the exact Git commit, then run `dreamboard project status --commit <rev> --wait` before retrying.";
987
+ case CLI_PROBLEM_TYPES.SOURCE_REVISION_DRIFT:
988
+ case CLI_PROBLEM_TYPES.AUTHORING_STATE_DRIFT:
989
+ case CLI_PROBLEM_TYPES.STATE_CONFLICT:
990
+ return "Resolve the Git/source conflict in your worktree, push the intended exact commit, and retry the command against that commit.";
991
+ case CLI_PROBLEM_TYPES.SOURCE_REVISION_BASE_MISSING:
992
+ case CLI_PROBLEM_TYPES.AUTHORING_STATE_BASE_MISSING:
993
+ return "Clone the project repository into a clean workspace or push the intended exact commit before retrying.";
994
+ case CLI_PROBLEM_TYPES.INTERNAL_ERROR:
995
+ return "Retry the command. If it still fails, include the request id when asking for help.";
996
+ default:
997
+ return void 0;
998
+ }
999
+ }
1000
+ function getProblemDetails(problem) {
1001
+ return [
1002
+ `Problem: ${problem.type}`,
1003
+ problem.instance ? `Endpoint: ${problem.instance}` : void 0,
1004
+ problem.requestId ? `Request ID: ${problem.requestId}` : void 0,
1005
+ problem.timestamp ? `Timestamp: ${problem.timestamp}` : void 0
1006
+ ].filter((detail) => Boolean(detail));
1007
+ }
1008
+ function presentCliError(error) {
1009
+ if (isDreamboardApiError(error)) {
1010
+ return {
1011
+ message: formatProblem(error.problem),
1012
+ resolution: getProblemResolution(error.problem),
1013
+ details: getProblemDetails(error.problem)
1014
+ };
1015
+ }
1016
+ if (error instanceof Error) {
1017
+ return {
1018
+ message: error.message,
1019
+ details: []
1020
+ };
1021
+ }
1022
+ if (typeof error === "object" && error !== null) {
1023
+ let serialized;
1024
+ try {
1025
+ serialized = JSON.stringify(error);
1026
+ } catch {
1027
+ serialized = String(error);
1028
+ }
1029
+ return {
1030
+ message: serialized,
1031
+ details: []
1032
+ };
1033
+ }
1034
+ return {
1035
+ message: String(error),
1036
+ details: []
1037
+ };
1038
+ }
1039
+ function formatCliError(error) {
1040
+ const presentation = presentCliError(error);
1041
+ return [
1042
+ presentation.message,
1043
+ presentation.resolution ? `Resolution: ${presentation.resolution}` : void 0,
1044
+ ...presentation.details
1045
+ ].filter((line) => Boolean(line)).join("\n");
1046
+ }
1047
+
1048
+ // src/utils/strings.ts
1049
+ import path from "path";
1050
+ function normalizeSlug(input) {
1051
+ const lowered = input.trim().toLowerCase();
1052
+ const replaced = lowered.replace(/[^a-z0-9]+/g, "-");
1053
+ return replaced.replace(/^-+/, "").replace(/-+$/, "");
1054
+ }
1055
+ function titleFromSlug(slug) {
1056
+ return slug.split("-").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
1057
+ }
1058
+ function parsePositiveInt(value, label) {
1059
+ const parsed = Number.parseInt(value, 10);
1060
+ if (!Number.isFinite(parsed) || parsed <= 0) {
1061
+ throw new Error(`${label} must be a positive integer.`);
1062
+ }
1063
+ return parsed;
1064
+ }
1065
+ function sleep2(ms) {
1066
+ return new Promise((resolve) => setTimeout(resolve, ms));
1067
+ }
1068
+
1069
+ // src/services/api/compiled-results-api.ts
1070
+ var COMPILE_JOB_POLL_INTERVAL_MS = 1e3;
1071
+ var DEFAULT_COMPILE_JOB_WAIT_TIMEOUT_MS = 10 * 60 * 1e3;
1072
+ function firstNonEmpty(...values) {
1073
+ for (const value of values) {
1074
+ if (typeof value === "string" && value.trim().length > 0) {
1075
+ return value.trim();
1076
+ }
1077
+ }
1078
+ return null;
1079
+ }
1080
+ function formatTerminalCompileJobMessage(job) {
1081
+ const detail = firstNonEmpty(job.errorMessage, job.message);
1082
+ const phase = firstNonEmpty(job.phase);
1083
+ const prefix = `Compile ${job.status.toLowerCase()}${phase ? ` [${phase}]` : ""}`;
1084
+ return detail ? `${prefix}: ${detail}` : `${prefix}: job ${job.jobId} ended before a compiled result was created.`;
1085
+ }
1086
+ function compareCreatedAtDesc(left, right) {
1087
+ const leftTime = Date.parse(left.createdAt);
1088
+ const rightTime = Date.parse(right.createdAt);
1089
+ if (Number.isFinite(leftTime) && Number.isFinite(rightTime)) {
1090
+ return rightTime - leftTime;
1091
+ }
1092
+ if (Number.isFinite(rightTime)) {
1093
+ return 1;
1094
+ }
1095
+ if (Number.isFinite(leftTime)) {
1096
+ return -1;
1097
+ }
1098
+ return 0;
1099
+ }
1100
+ async function findFallbackCompiledResultForJob(options) {
1101
+ const { gameId, projectId, job } = options;
1102
+ if (!projectId) {
1103
+ return null;
1104
+ }
1105
+ const results = await listProjectCompiledResults({
1106
+ path: { projectId },
1107
+ query: { limit: 100 }
1108
+ });
1109
+ if (results.error || !results.data) {
1110
+ return null;
1111
+ }
1112
+ if (results.data.results.length === 0) {
1113
+ return null;
1114
+ }
1115
+ const jobCreatedAtMs = Date.parse(job.createdAt);
1116
+ const resultsCreatedAfterJob = Number.isFinite(jobCreatedAtMs) ? results.data.results.filter((result) => {
1117
+ const resultCreatedAtMs = Date.parse(result.createdAt);
1118
+ return !Number.isFinite(resultCreatedAtMs) || resultCreatedAtMs >= jobCreatedAtMs;
1119
+ }) : results.data.results;
1120
+ const candidateResults = resultsCreatedAfterJob.length > 0 ? resultsCreatedAfterJob : results.data.results;
1121
+ return [...candidateResults].sort(compareCreatedAtDesc)[0] ?? null;
1122
+ }
1123
+ async function findCompiledResultsForAuthoringState(options) {
1124
+ void options;
1125
+ return [];
1126
+ }
1127
+ async function getCompiledResultSdk(gameId, compiledResultId) {
1128
+ void gameId;
1129
+ void compiledResultId;
1130
+ throw new Error("Game-scoped compiled result lookup is no longer supported.");
1131
+ }
1132
+ async function getProjectCompiledResultSdk(projectId, compiledResultId) {
1133
+ const { data, error, response } = await getProjectCompiledResult({
1134
+ path: { projectId, compiledResultId }
1135
+ });
1136
+ if (error || !data) {
1137
+ throw toDreamboardApiError(
1138
+ error,
1139
+ response,
1140
+ "Failed to fetch compiled result"
1141
+ );
1142
+ }
1143
+ return data;
1144
+ }
1145
+ async function waitForCompiledResultJobSdk(options) {
1146
+ const { gameId, projectId, jobId, onProgress } = options;
1147
+ let previousTransitionKey = null;
1148
+ const startedAt = Date.now();
1149
+ const timeoutMs = readCompileJobWaitTimeoutMs();
1150
+ while (Date.now() - startedAt < timeoutMs) {
1151
+ const {
1152
+ data: job,
1153
+ error,
1154
+ response
1155
+ } = await getJob({
1156
+ path: { jobId }
1157
+ });
1158
+ if (error || !job) {
1159
+ if (isTransientJobPollError(error, response)) {
1160
+ await sleep2(COMPILE_JOB_POLL_INTERVAL_MS);
1161
+ continue;
1162
+ }
1163
+ throw toDreamboardApiError(error, response, "Failed to get job");
1164
+ }
1165
+ const transitionKey = `${job.status}:${job.phase ?? ""}`;
1166
+ if (transitionKey !== previousTransitionKey) {
1167
+ previousTransitionKey = transitionKey;
1168
+ onProgress?.(job);
1169
+ }
1170
+ if (job.status === "COMPLETED" || job.status === "FAILED") {
1171
+ const compiledResultId = job.createdCompiledResultId ?? job.createdAppScriptId;
1172
+ if (compiledResultId) {
1173
+ if (projectId) {
1174
+ const compiledResult2 = await getProjectCompiledResultSdk(
1175
+ projectId,
1176
+ compiledResultId
1177
+ );
1178
+ return { job, compiledResult: compiledResult2 };
1179
+ }
1180
+ const compiledResult = await getCompiledResultSdk(
1181
+ gameId,
1182
+ compiledResultId
1183
+ );
1184
+ return { job, compiledResult };
1185
+ }
1186
+ const fallbackCompiledResult = await findFallbackCompiledResultForJob({
1187
+ gameId,
1188
+ projectId,
1189
+ job
1190
+ });
1191
+ if (fallbackCompiledResult) {
1192
+ return { job, compiledResult: fallbackCompiledResult };
1193
+ }
1194
+ throw new Error(formatTerminalCompileJobMessage(job));
1195
+ }
1196
+ if (job.status === "CANCELLED" || job.status === "INTERRUPTED") {
1197
+ throw new Error(formatTerminalCompileJobMessage(job));
1198
+ }
1199
+ await sleep2(COMPILE_JOB_POLL_INTERVAL_MS);
1200
+ }
1201
+ throw new Error(`Compile job ${jobId} did not complete in time.`);
1202
+ }
1203
+ function readCompileJobWaitTimeoutMs() {
1204
+ const raw = process.env.DREAMBOARD_COMPILE_WAIT_TIMEOUT_MS;
1205
+ if (!raw) return DEFAULT_COMPILE_JOB_WAIT_TIMEOUT_MS;
1206
+ const parsed = Number(raw);
1207
+ if (!Number.isFinite(parsed) || parsed <= 0) {
1208
+ return DEFAULT_COMPILE_JOB_WAIT_TIMEOUT_MS;
1209
+ }
1210
+ return parsed;
1211
+ }
1212
+ function isTransientJobPollError(error, response) {
1213
+ if (response) return false;
1214
+ if (!error) return false;
1215
+ if (error instanceof Error) {
1216
+ return isTransientJobPollMessage(error.message);
1217
+ }
1218
+ if (typeof error === "object" && error !== null && "message" in error) {
1219
+ return isTransientJobPollMessage(String(error.message));
1220
+ }
1221
+ return isTransientJobPollMessage(String(error));
1222
+ }
1223
+ function isTransientJobPollMessage(message) {
1224
+ const normalized = message.toLowerCase();
1225
+ return normalized.includes("fetch failed") || normalized.includes("network") || normalized.includes("timeout") || normalized.includes("econnreset") || normalized.includes("econnrefused") || normalized.includes("socket");
1226
+ }
1227
+
1228
+ // src/services/testing/reducer-native-test-harness.ts
1229
+ import path3 from "path";
1230
+ import { randomUUID as randomUUID3 } from "crypto";
1231
+ import { createRequire } from "module";
1232
+ import { pathToFileURL as pathToFileURL2 } from "url";
1233
+ import {
1234
+ existsSync,
1235
+ mkdirSync,
1236
+ readFileSync,
1237
+ rmSync,
1238
+ writeFileSync
1239
+ } from "fs";
1240
+ import { readdir } from "fs/promises";
1241
+ import { isDeepStrictEqual } from "util";
1242
+
1243
+ // src/utils/ts-module-loader.ts
1244
+ import { mkdtemp, rm, writeFile } from "fs/promises";
1245
+ import { tmpdir } from "os";
1246
+ import path2 from "path";
1247
+ import { pathToFileURL } from "url";
1248
+ import { build } from "esbuild";
1249
+ var ESBUILD_EXTERNALS = [
1250
+ "playwright",
1251
+ "playwright-core",
1252
+ "chromium-bidi",
1253
+ "electron"
1254
+ ];
1255
+ function resolveSourceCheckoutBuildContext() {
1256
+ try {
1257
+ const repoRoot = resolveCliRepoRoot(import.meta.url);
1258
+ return {
1259
+ nodePaths: [
1260
+ path2.join(repoRoot, "apps", "dreamboard-cli", "node_modules"),
1261
+ path2.join(repoRoot, "node_modules")
1262
+ ],
1263
+ plugins: [createRepoLocalPackageResolutionPlugin({ repoRoot })]
1264
+ };
1265
+ } catch {
1266
+ return {
1267
+ nodePaths: [path2.join(process.cwd(), "node_modules")],
1268
+ plugins: []
1269
+ };
1270
+ }
1271
+ }
1272
+ async function bundleTypeScriptModuleText(entryPath, options = {}) {
1273
+ const sourceCheckoutContext = resolveSourceCheckoutBuildContext();
1274
+ const result = await build({
1275
+ entryPoints: [entryPath],
1276
+ bundle: true,
1277
+ format: "esm",
1278
+ platform: "node",
1279
+ target: "node24",
1280
+ sourcemap: "inline",
1281
+ external: [...ESBUILD_EXTERNALS, ...options.external ?? []],
1282
+ nodePaths: sourceCheckoutContext.nodePaths,
1283
+ plugins: sourceCheckoutContext.plugins,
1284
+ write: false
1285
+ });
1286
+ const output = result.outputFiles?.[0];
1287
+ if (!output) {
1288
+ throw new Error(`Failed to bundle TypeScript module '${entryPath}'.`);
1289
+ }
1290
+ return output.text;
1291
+ }
1292
+ async function importTypeScriptModule(entryPath) {
1293
+ const tempDir = await mkdtemp(path2.join(tmpdir(), "dreamboard-ts-module-"));
1294
+ const outfile = path2.join(
1295
+ tempDir,
1296
+ `${path2.basename(entryPath).replace(/\.[^.]+$/u, "")}.mjs`
1297
+ );
1298
+ try {
1299
+ const bundledText = await bundleTypeScriptModuleText(entryPath);
1300
+ await writeFile(outfile, bundledText);
1301
+ return await import(pathToFileURL(outfile).href);
1302
+ } finally {
1303
+ await rm(tempDir, { recursive: true, force: true });
1304
+ }
1305
+ }
1306
+
1307
+ // src/services/gameplay-authority-submit.ts
1308
+ import { randomUUID as randomUUID2 } from "crypto";
1309
+
1310
+ // ../../node_modules/.pnpm/@dreamboard-games+gameplay-authority-protocol@0.1.0-alpha.0/node_modules/@dreamboard-games/gameplay-authority-protocol/dist/frames.js
1311
+ var GAMEPLAY_AUTHORITY_AUDIENCE = "dreamboard-gameplay-authority";
1312
+ var GAMEPLAY_TUNNEL_AUDIENCE = "dreamboard-gameplay-authority-tunnel";
1313
+ var GameplayPermissionSchema = external_exports.enum([
1314
+ "observe",
1315
+ "submit",
1316
+ "restore-history"
1317
+ ]);
1318
+ var GameplayConnectionContextSchema = external_exports.object({
1319
+ sessionId: external_exports.string().uuid(),
1320
+ playerId: external_exports.string().min(1),
1321
+ permissions: external_exports.array(GameplayPermissionSchema)
1322
+ });
1323
+ var GameplayActorKindSchema = external_exports.enum(["user", "demo", "perf"]);
1324
+ var JsonPatchOperationSchema = external_exports.object({
1325
+ op: external_exports.string().min(1),
1326
+ path: external_exports.string()
1327
+ }).catchall(external_exports.unknown());
1328
+ var ProjectedDeltaSchema = external_exports.object({
1329
+ kind: external_exports.literal("delta"),
1330
+ generation: external_exports.number().int().nonnegative(),
1331
+ baseVersion: external_exports.number().int().nonnegative(),
1332
+ version: external_exports.number().int().nonnegative(),
1333
+ patch: external_exports.array(JsonPatchOperationSchema)
1334
+ });
1335
+ var ProjectedSnapshotSchema = external_exports.object({
1336
+ kind: external_exports.literal("snapshot"),
1337
+ generation: external_exports.number().int().nonnegative(),
1338
+ version: external_exports.number().int().nonnegative(),
1339
+ view: external_exports.unknown()
1340
+ });
1341
+ var BaseGameplayCapabilityClaimsSchema = external_exports.object({
1342
+ typ: external_exports.literal("gameplay-capability"),
1343
+ aud: external_exports.literal(GAMEPLAY_AUTHORITY_AUDIENCE),
1344
+ iss: external_exports.string().min(1),
1345
+ exp: external_exports.number().int().positive(),
1346
+ iat: external_exports.number().int().positive().optional(),
1347
+ jti: external_exports.string().min(1).optional(),
1348
+ sessionId: external_exports.string().uuid(),
1349
+ playerId: external_exports.string().min(1),
1350
+ permissions: external_exports.array(GameplayPermissionSchema)
1351
+ });
1352
+ var UserGameplayCapabilityClaimsSchema = BaseGameplayCapabilityClaimsSchema.extend({
1353
+ actorKind: external_exports.literal("user")
1354
+ });
1355
+ var DemoGameplayCapabilityClaimsSchema = BaseGameplayCapabilityClaimsSchema.extend({
1356
+ actorKind: external_exports.literal("demo")
1357
+ });
1358
+ var PerfGameplayCapabilityClaimsSchema = BaseGameplayCapabilityClaimsSchema.extend({
1359
+ actorKind: external_exports.literal("perf"),
1360
+ perfRunId: external_exports.string().uuid(),
1361
+ laneId: external_exports.string().min(1)
1362
+ });
1363
+ var GameplayCapabilityClaimsSchema = external_exports.discriminatedUnion("actorKind", [
1364
+ UserGameplayCapabilityClaimsSchema,
1365
+ DemoGameplayCapabilityClaimsSchema,
1366
+ PerfGameplayCapabilityClaimsSchema
1367
+ ]);
1368
+ var GameplayTunnelClaimsSchema = external_exports.object({
1369
+ aud: external_exports.literal(GAMEPLAY_TUNNEL_AUDIENCE),
1370
+ iss: external_exports.string().min(1),
1371
+ exp: external_exports.number().int().positive(),
1372
+ iat: external_exports.number().int().positive().optional(),
1373
+ jti: external_exports.string().min(1).optional(),
1374
+ targetInstanceId: external_exports.string().min(1),
1375
+ sessionId: external_exports.string().uuid(),
1376
+ playerId: external_exports.string().min(1),
1377
+ // Permissions are cryptographically bound into the tunnel token so the owner
1378
+ // task trusts the signed claim set rather than the unauthenticated
1379
+ // `tunnel.bind` frame. An ingress task cannot grant a player capabilities the
1380
+ // issued token did not attest.
1381
+ permissions: external_exports.array(GameplayPermissionSchema)
1382
+ });
1383
+ var AuthConnectFrameSchema = external_exports.object({
1384
+ type: external_exports.literal("auth.connect"),
1385
+ capabilityToken: external_exports.string().min(1)
1386
+ });
1387
+ var AuthRefreshFrameSchema = external_exports.object({
1388
+ type: external_exports.literal("auth.refresh"),
1389
+ capabilityToken: external_exports.string().min(1)
1390
+ });
1391
+ var SessionResumeFrameSchema = external_exports.object({
1392
+ type: external_exports.literal("session.resume"),
1393
+ lastSeenGeneration: external_exports.number().int().nonnegative().nullable(),
1394
+ lastSeenVersion: external_exports.number().int().nonnegative().nullable(),
1395
+ unacknowledgedClientActionIds: external_exports.array(external_exports.string().min(1)).max(32)
1396
+ });
1397
+ var CommandSubmitFrameSchema = external_exports.object({
1398
+ type: external_exports.literal("command.submit"),
1399
+ clientActionId: external_exports.string().min(1).max(128),
1400
+ expectedVersion: external_exports.number().int().nonnegative(),
1401
+ actionSetVersion: external_exports.string().min(1),
1402
+ interactionId: external_exports.string().min(1),
1403
+ inputs: external_exports.record(external_exports.string(), external_exports.unknown())
1404
+ });
1405
+ var HistoryRestoreFrameSchema = external_exports.object({
1406
+ type: external_exports.literal("history.restore"),
1407
+ restoreId: external_exports.string().min(1).max(128),
1408
+ targetGeneration: external_exports.number().int().nonnegative(),
1409
+ targetVersion: external_exports.number().int().nonnegative()
1410
+ });
1411
+ var ClientGameplayFrameSchema = external_exports.discriminatedUnion("type", [
1412
+ AuthConnectFrameSchema,
1413
+ AuthRefreshFrameSchema,
1414
+ SessionResumeFrameSchema,
1415
+ CommandSubmitFrameSchema,
1416
+ HistoryRestoreFrameSchema
1417
+ ]);
1418
+ var TunnelBindFrameSchema = external_exports.object({
1419
+ type: external_exports.literal("tunnel.bind"),
1420
+ context: GameplayConnectionContextSchema
1421
+ });
1422
+ var TunnelClientFrameSchema = external_exports.discriminatedUnion("type", [
1423
+ TunnelBindFrameSchema,
1424
+ SessionResumeFrameSchema,
1425
+ CommandSubmitFrameSchema,
1426
+ HistoryRestoreFrameSchema
1427
+ ]);
1428
+ var CommandAcceptedFrameSchema = external_exports.object({
1429
+ type: external_exports.literal("command.accepted"),
1430
+ clientActionId: external_exports.string().min(1),
1431
+ generation: external_exports.number().int().nonnegative(),
1432
+ version: external_exports.number().int().nonnegative(),
1433
+ stateHash: external_exports.string().min(1),
1434
+ update: ProjectedSnapshotSchema
1435
+ });
1436
+ var CommandRejectedFrameSchema = external_exports.object({
1437
+ type: external_exports.literal("command.rejected"),
1438
+ clientActionId: external_exports.string().min(1).optional(),
1439
+ errorCode: external_exports.string().min(1),
1440
+ message: external_exports.string().min(1),
1441
+ currentGeneration: external_exports.number().int().nonnegative().optional(),
1442
+ currentVersion: external_exports.number().int().nonnegative().optional()
1443
+ });
1444
+ var HistoryRestoredFrameSchema = external_exports.object({
1445
+ type: external_exports.literal("history.restored"),
1446
+ restoreId: external_exports.string().min(1),
1447
+ generation: external_exports.number().int().nonnegative(),
1448
+ version: external_exports.number().int().nonnegative(),
1449
+ stateHash: external_exports.string().min(1),
1450
+ update: ProjectedSnapshotSchema
1451
+ });
1452
+ var HistoryRestoreRejectedFrameSchema = external_exports.object({
1453
+ type: external_exports.literal("history.restoreRejected"),
1454
+ restoreId: external_exports.string().min(1).optional(),
1455
+ errorCode: external_exports.string().min(1),
1456
+ message: external_exports.string().min(1),
1457
+ currentGeneration: external_exports.number().int().nonnegative().optional(),
1458
+ currentVersion: external_exports.number().int().nonnegative().optional()
1459
+ });
1460
+ var AuthAcceptedFrameSchema = external_exports.object({
1461
+ type: external_exports.literal("auth.accepted"),
1462
+ expiresAt: external_exports.string().datetime()
1463
+ });
1464
+ var AuthorityRecoveringFrameSchema = external_exports.object({
1465
+ type: external_exports.literal("authority.recovering"),
1466
+ retryAfterMs: external_exports.number().int().positive(),
1467
+ message: external_exports.string().min(1)
1468
+ });
1469
+ var SessionSnapshotFrameSchema = external_exports.object({
1470
+ type: external_exports.literal("session.snapshot"),
1471
+ generation: external_exports.number().int().nonnegative(),
1472
+ version: external_exports.number().int().nonnegative(),
1473
+ stateHash: external_exports.string().min(1),
1474
+ update: ProjectedSnapshotSchema
1475
+ });
1476
+ var SessionDeltaFrameSchema = external_exports.object({
1477
+ type: external_exports.literal("session.delta"),
1478
+ clientActionId: external_exports.string().min(1).optional(),
1479
+ update: ProjectedDeltaSchema
1480
+ });
1481
+ var ServerGameplayFrameSchema = external_exports.discriminatedUnion("type", [
1482
+ AuthAcceptedFrameSchema,
1483
+ AuthorityRecoveringFrameSchema,
1484
+ SessionSnapshotFrameSchema,
1485
+ SessionDeltaFrameSchema,
1486
+ CommandAcceptedFrameSchema,
1487
+ CommandRejectedFrameSchema,
1488
+ HistoryRestoredFrameSchema,
1489
+ HistoryRestoreRejectedFrameSchema
1490
+ ]);
1491
+ var TunnelBoundFrameSchema = external_exports.object({
1492
+ type: external_exports.literal("tunnel.bound"),
1493
+ sessionId: external_exports.string().uuid(),
1494
+ playerId: external_exports.string().min(1)
1495
+ });
1496
+ var TunnelServerFrameSchema = external_exports.discriminatedUnion("type", [
1497
+ TunnelBoundFrameSchema,
1498
+ AuthorityRecoveringFrameSchema,
1499
+ SessionSnapshotFrameSchema,
1500
+ SessionDeltaFrameSchema,
1501
+ CommandAcceptedFrameSchema,
1502
+ CommandRejectedFrameSchema,
1503
+ HistoryRestoredFrameSchema,
1504
+ HistoryRestoreRejectedFrameSchema
1505
+ ]);
1506
+
1507
+ // ../../node_modules/.pnpm/@dreamboard-games+gameplay-authority-client@0.1.0-alpha.1/node_modules/@dreamboard-games/gameplay-authority-client/dist/index.js
1508
+ var DEFAULT_OPEN_TIMEOUT_MS = 5e3;
1509
+ var DEFAULT_REQUEST_TIMEOUT_MS = 1e4;
1510
+ var GameplayAuthorityRecoveringError = class extends Error {
1511
+ retryAfterMs;
1512
+ constructor(message, retryAfterMs) {
1513
+ super(message);
1514
+ this.name = "GameplayAuthorityRecoveringError";
1515
+ this.retryAfterMs = retryAfterMs;
1516
+ }
1517
+ };
1518
+ async function connectGameplayAuthority(input) {
1519
+ const webSocketFactory = input.webSocketFactory ?? browserWebSocketFactory();
1520
+ const openTimeoutMs = input.openTimeoutMs ?? DEFAULT_OPEN_TIMEOUT_MS;
1521
+ const requestTimeoutMs = input.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
1522
+ const socket = new webSocketFactory(input.websocketUrl, input.webSocketInit);
1523
+ try {
1524
+ await waitUntilOpen(socket, openTimeoutMs);
1525
+ socket.send(JSON.stringify({
1526
+ type: "auth.connect",
1527
+ capabilityToken: input.capabilityToken
1528
+ }));
1529
+ await waitForServerFrame(socket, (frame) => frame.type === "auth.accepted", requestTimeoutMs);
1530
+ return new WebSocketGameplayAuthorityClient(socket, requestTimeoutMs);
1531
+ } catch (error) {
1532
+ socket.close();
1533
+ throw error;
1534
+ }
1535
+ }
1536
+ var WebSocketGameplayAuthorityClient = class {
1537
+ socket;
1538
+ requestTimeoutMs;
1539
+ constructor(socket, requestTimeoutMs) {
1540
+ this.socket = socket;
1541
+ this.requestTimeoutMs = requestTimeoutMs;
1542
+ }
1543
+ resume(input = {}) {
1544
+ this.socket.send(JSON.stringify({
1545
+ type: "session.resume",
1546
+ lastSeenGeneration: input.lastSeenGeneration ?? null,
1547
+ lastSeenVersion: input.lastSeenVersion ?? null,
1548
+ unacknowledgedClientActionIds: input.unacknowledgedClientActionIds ?? []
1549
+ }));
1550
+ }
1551
+ async submitCommand(input) {
1552
+ this.socket.send(JSON.stringify({
1553
+ type: "command.submit",
1554
+ clientActionId: input.clientActionId,
1555
+ expectedVersion: input.expectedVersion,
1556
+ actionSetVersion: input.actionSetVersion,
1557
+ interactionId: input.interactionId,
1558
+ inputs: input.inputs
1559
+ }));
1560
+ const frame = await waitForServerFrame(this.socket, (candidate) => candidate.type === "authority.recovering" || candidate.type === "command.accepted" && candidate.clientActionId === input.clientActionId || candidate.type === "command.rejected" && (candidate.clientActionId === void 0 || candidate.clientActionId === input.clientActionId), this.requestTimeoutMs);
1561
+ throwIfRecovering(frame);
1562
+ if (frame.type !== "command.accepted" && frame.type !== "command.rejected") {
1563
+ throw new Error("Unexpected gameplay authority command frame.");
1564
+ }
1565
+ return frame;
1566
+ }
1567
+ async restoreHistory(input) {
1568
+ this.socket.send(JSON.stringify({
1569
+ type: "history.restore",
1570
+ restoreId: input.restoreId,
1571
+ targetGeneration: input.targetGeneration,
1572
+ targetVersion: input.targetVersion
1573
+ }));
1574
+ const frame = await waitForServerFrame(this.socket, (candidate) => candidate.type === "authority.recovering" || candidate.type === "history.restored" && candidate.restoreId === input.restoreId || candidate.type === "history.restoreRejected" && (candidate.restoreId === void 0 || candidate.restoreId === input.restoreId), this.requestTimeoutMs);
1575
+ throwIfRecovering(frame);
1576
+ if (frame.type !== "history.restored" && frame.type !== "history.restoreRejected") {
1577
+ throw new Error("Unexpected gameplay authority history frame.");
1578
+ }
1579
+ return frame;
1580
+ }
1581
+ frames(signal) {
1582
+ return readServerFrames(this.socket, signal);
1583
+ }
1584
+ close() {
1585
+ this.socket.close();
1586
+ }
1587
+ };
1588
+ function throwIfRecovering(frame) {
1589
+ if (frame.type === "authority.recovering") {
1590
+ throw new GameplayAuthorityRecoveringError(frame.message, frame.retryAfterMs);
1591
+ }
1592
+ }
1593
+ function browserWebSocketFactory() {
1594
+ return BrowserGameplayAuthorityWebSocket;
1595
+ }
1596
+ var BrowserGameplayAuthorityWebSocket = class {
1597
+ socket;
1598
+ listeners = /* @__PURE__ */ new Map();
1599
+ constructor(url, init) {
1600
+ if (init?.headers && Object.keys(init.headers).length > 0) {
1601
+ throw new Error("Browser WebSocket does not support custom headers; provide a webSocketFactory for header-aware runtimes.");
1602
+ }
1603
+ this.socket = new WebSocket(url);
1604
+ }
1605
+ send(data) {
1606
+ this.socket.send(data);
1607
+ }
1608
+ close() {
1609
+ this.socket.close();
1610
+ }
1611
+ on(event, listener) {
1612
+ const wrapped = (observed) => {
1613
+ if (event === "message" && "data" in observed) {
1614
+ listener(observed.data);
1615
+ return;
1616
+ }
1617
+ listener(observed);
1618
+ };
1619
+ const listeners = this.listeners.get(event) ?? /* @__PURE__ */ new Map();
1620
+ listeners.set(listener, wrapped);
1621
+ this.listeners.set(event, listeners);
1622
+ this.socket.addEventListener(event, wrapped);
1623
+ }
1624
+ off(event, listener) {
1625
+ const listeners = this.listeners.get(event);
1626
+ const wrapped = listeners?.get(listener);
1627
+ if (!listeners || !wrapped) {
1628
+ return;
1629
+ }
1630
+ this.socket.removeEventListener(event, wrapped);
1631
+ listeners.delete(listener);
1632
+ }
1633
+ };
1634
+ async function waitUntilOpen(socket, timeoutMs) {
1635
+ await waitForEvent(socket, "open", timeoutMs);
1636
+ }
1637
+ async function waitForEvent(socket, event, timeoutMs) {
1638
+ return new Promise((resolve, reject) => {
1639
+ const cleanup = installSocketListeners(socket, {
1640
+ timeoutMs,
1641
+ onEvent(observed) {
1642
+ if (observed === event) {
1643
+ cleanup();
1644
+ resolve();
1645
+ }
1646
+ },
1647
+ onError(error) {
1648
+ cleanup();
1649
+ reject(error instanceof Error ? error : new Error("gameplay socket error"));
1650
+ },
1651
+ onClose() {
1652
+ cleanup();
1653
+ reject(new Error("gameplay socket closed"));
1654
+ },
1655
+ onTimeout() {
1656
+ cleanup();
1657
+ reject(new Error("gameplay socket timed out"));
1658
+ }
1659
+ });
1660
+ });
1661
+ }
1662
+ async function waitForServerFrame(socket, predicate, timeoutMs) {
1663
+ return new Promise((resolve, reject) => {
1664
+ const cleanup = installSocketListeners(socket, {
1665
+ timeoutMs,
1666
+ onMessage(data) {
1667
+ let frame;
1668
+ try {
1669
+ frame = ServerGameplayFrameSchema.parse(JSON.parse(messageToString(data)));
1670
+ } catch (error) {
1671
+ cleanup();
1672
+ reject(error instanceof Error ? error : new Error("invalid gameplay authority frame"));
1673
+ return;
1674
+ }
1675
+ if (predicate(frame)) {
1676
+ cleanup();
1677
+ resolve(frame);
1678
+ }
1679
+ },
1680
+ onError(error) {
1681
+ cleanup();
1682
+ reject(error instanceof Error ? error : new Error("gameplay socket error"));
1683
+ },
1684
+ onClose() {
1685
+ cleanup();
1686
+ reject(new Error("gameplay socket closed"));
1687
+ },
1688
+ onTimeout() {
1689
+ cleanup();
1690
+ reject(new Error("gameplay socket timed out"));
1691
+ }
1692
+ });
1693
+ });
1694
+ }
1695
+ function installSocketListeners(socket, handlers) {
1696
+ const timer = setTimeout(handlers.onTimeout, handlers.timeoutMs);
1697
+ const onOpen = () => handlers.onEvent?.("open");
1698
+ const onMessage = (data) => handlers.onMessage?.(data);
1699
+ const onError = (error) => handlers.onError(error);
1700
+ const onClose = () => handlers.onClose();
1701
+ socket.on("open", onOpen);
1702
+ socket.on("message", onMessage);
1703
+ socket.on("error", onError);
1704
+ socket.on("close", onClose);
1705
+ return () => {
1706
+ clearTimeout(timer);
1707
+ socket.off?.("open", onOpen);
1708
+ socket.off?.("message", onMessage);
1709
+ socket.off?.("error", onError);
1710
+ socket.off?.("close", onClose);
1711
+ };
1712
+ }
1713
+ function readServerFrames(socket, signal) {
1714
+ const queue = [];
1715
+ let wake = null;
1716
+ let closed = false;
1717
+ let error = null;
1718
+ const wakeReader = () => {
1719
+ wake?.();
1720
+ wake = null;
1721
+ };
1722
+ const onMessage = (data) => {
1723
+ try {
1724
+ queue.push(ServerGameplayFrameSchema.parse(JSON.parse(messageToString(data))));
1725
+ } catch (candidate) {
1726
+ error = candidate instanceof Error ? candidate : new Error("invalid gameplay authority frame");
1727
+ }
1728
+ wakeReader();
1729
+ };
1730
+ const onError = (candidate) => {
1731
+ error = candidate instanceof Error ? candidate : new Error("gameplay socket error");
1732
+ wakeReader();
1733
+ };
1734
+ const onClose = () => {
1735
+ closed = true;
1736
+ wakeReader();
1737
+ };
1738
+ const onAbort = () => {
1739
+ closed = true;
1740
+ wakeReader();
1741
+ };
1742
+ socket.on("message", onMessage);
1743
+ socket.on("error", onError);
1744
+ socket.on("close", onClose);
1745
+ signal?.addEventListener("abort", onAbort, { once: true });
1746
+ const cleanup = () => {
1747
+ socket.off?.("message", onMessage);
1748
+ socket.off?.("error", onError);
1749
+ socket.off?.("close", onClose);
1750
+ signal?.removeEventListener("abort", onAbort);
1751
+ };
1752
+ const iterator = {
1753
+ async next() {
1754
+ while (!closed && !signal?.aborted) {
1755
+ const next = queue.shift();
1756
+ if (next) {
1757
+ return { done: false, value: next };
1758
+ }
1759
+ if (error) {
1760
+ cleanup();
1761
+ throw error;
1762
+ }
1763
+ await new Promise((resolve) => {
1764
+ wake = resolve;
1765
+ });
1766
+ }
1767
+ cleanup();
1768
+ if (error) {
1769
+ throw error;
1770
+ }
1771
+ return { done: true, value: void 0 };
1772
+ },
1773
+ async return(value) {
1774
+ closed = true;
1775
+ wakeReader();
1776
+ cleanup();
1777
+ return { done: true, value };
1778
+ },
1779
+ async throw(candidate) {
1780
+ closed = true;
1781
+ wakeReader();
1782
+ cleanup();
1783
+ throw candidate;
1784
+ },
1785
+ [Symbol.asyncIterator]() {
1786
+ return this;
1787
+ },
1788
+ async [Symbol.asyncDispose]() {
1789
+ await this.return(void 0);
1790
+ }
1791
+ };
1792
+ return iterator;
1793
+ }
1794
+ function messageToString(data) {
1795
+ if (typeof data === "string") {
1796
+ return data;
1797
+ }
1798
+ if (data instanceof ArrayBuffer) {
1799
+ return new TextDecoder().decode(data);
1800
+ }
1801
+ if (ArrayBuffer.isView(data)) {
1802
+ return new TextDecoder().decode(data);
1803
+ }
1804
+ return String(data);
1805
+ }
1806
+
1807
+ // src/services/gameplay-authority-submit.ts
1808
+ var CLIENT_ACTION_ID_HEADER = "X-Dreamboard-Client-Action-Id";
1809
+ var DEFAULT_TIMEOUT_MS = 1e4;
1810
+ async function submitGameplayAuthorityAction(options) {
1811
+ try {
1812
+ const requestCapability = options.capabilityRequester ?? createGameplayCapability;
1813
+ const connectAuthority = options.connectAuthority ?? connectGameplayAuthority;
1814
+ const capability = await requestCapability({
1815
+ path: {
1816
+ sessionId: options.path.sessionId,
1817
+ playerId: options.path.playerId
1818
+ }
1819
+ });
1820
+ if (capability.error || !capability.data) {
1821
+ return { error: capability.error ?? new Error("Missing capability.") };
1822
+ }
1823
+ const clientActionId = options.headers?.[CLIENT_ACTION_ID_HEADER] ?? options.clientActionIdFactory?.() ?? randomUUID2();
1824
+ const client2 = await connectAuthority({
1825
+ websocketUrl: capability.data.websocketUrl,
1826
+ capabilityToken: capability.data.token,
1827
+ openTimeoutMs: DEFAULT_TIMEOUT_MS,
1828
+ requestTimeoutMs: DEFAULT_TIMEOUT_MS
1829
+ });
1830
+ try {
1831
+ const frame = await client2.submitCommand({
1832
+ clientActionId,
1833
+ expectedVersion: options.body.expectedVersion,
1834
+ actionSetVersion: options.body.actionSetVersion,
1835
+ interactionId: options.path.interactionId,
1836
+ inputs: options.body.inputs ?? {}
1837
+ });
1838
+ if (frame.type === "command.rejected") {
1839
+ return {
1840
+ data: {
1841
+ success: false,
1842
+ accepted: false,
1843
+ version: typeof frame.currentVersion === "number" ? frame.currentVersion : options.body.expectedVersion,
1844
+ actionSetVersion: options.body.actionSetVersion,
1845
+ errorCode: typeof frame.errorCode === "string" ? frame.errorCode : void 0,
1846
+ message: typeof frame.message === "string" ? frame.message : void 0,
1847
+ clientActionId
1848
+ }
1849
+ };
1850
+ }
1851
+ const acceptedVersion = typeof frame.version === "number" ? frame.version : void 0;
1852
+ if (acceptedVersion === void 0) {
1853
+ return {
1854
+ error: new Error("Accepted frame did not include a numeric version.")
1855
+ };
1856
+ }
1857
+ const update = frame.update && typeof frame.update === "object" ? frame.update : {};
1858
+ const view = update.view && typeof update.view === "object" ? update.view : {};
1859
+ const projectedActionSetVersion = typeof view.actionSetVersion === "string" ? view.actionSetVersion : void 0;
1860
+ return {
1861
+ data: {
1862
+ success: true,
1863
+ accepted: true,
1864
+ durabilityStatus: "COMMITTED",
1865
+ version: acceptedVersion,
1866
+ actionSetVersion: projectedActionSetVersion ?? options.body.actionSetVersion,
1867
+ clientActionId
1868
+ }
1869
+ };
1870
+ } catch (error) {
1871
+ if (error instanceof GameplayAuthorityRecoveringError) {
1872
+ return {
1873
+ error: new Error(error.message || "Session authority is recovering.")
1874
+ };
1875
+ }
1876
+ throw error;
1877
+ } finally {
1878
+ client2.close();
1879
+ }
1880
+ } catch (error) {
1881
+ return { error };
1882
+ }
1883
+ }
1884
+
1885
+ // src/services/workflows/resolve-setup-profile.ts
1886
+ function resolveSetupProfileSelection(options) {
1887
+ const setupProfiles = options.manifest.setupProfiles ?? [];
1888
+ const requestedSetupProfileId = options.requestedSetupProfileId?.trim() || void 0;
1889
+ if (requestedSetupProfileId) {
1890
+ const requestedProfile = setupProfiles.find(
1891
+ (profile) => profile.id === requestedSetupProfileId
1892
+ );
1893
+ if (!requestedProfile) {
1894
+ const knownProfiles = setupProfiles.map((profile) => profile.id).join(", ");
1895
+ throw new Error(
1896
+ setupProfiles.length === 0 ? `Unknown setup profile '${requestedSetupProfileId}'. The manifest defines no setup profiles.` : `Unknown setup profile '${requestedSetupProfileId}'. Expected one of: ${knownProfiles}.`
1897
+ );
1898
+ }
1899
+ return {
1900
+ id: requestedProfile.id,
1901
+ name: requestedProfile.name,
1902
+ source: "explicit"
1903
+ };
1904
+ }
1905
+ if (setupProfiles.length === 0) {
1906
+ return {
1907
+ id: null,
1908
+ name: null,
1909
+ source: "none"
1910
+ };
1911
+ }
1912
+ if (setupProfiles.length === 1) {
1913
+ return {
1914
+ id: setupProfiles[0]?.id ?? null,
1915
+ name: setupProfiles[0]?.name ?? null,
1916
+ source: "implicit-single"
1917
+ };
1918
+ }
1919
+ return {
1920
+ id: setupProfiles[0]?.id ?? null,
1921
+ name: setupProfiles[0]?.name ?? null,
1922
+ source: "implicit-first"
1923
+ };
1924
+ }
1925
+ async function resolveSetupProfileSelectionForSession(options) {
1926
+ const manifest = await loadManifest(options.projectRoot);
1927
+ return resolveSetupProfileSelection({
1928
+ manifest,
1929
+ requestedSetupProfileId: options.requestedSetupProfileId
1930
+ });
1931
+ }
1932
+
1933
+ // src/utils/session-game-source.ts
1934
+ function projectIdFromSessionGameSource(source) {
1935
+ if (source.kind === "USER_COMPILED") {
1936
+ return source.projectId;
1937
+ }
1938
+ return `demo:${source.slug}:${source.revisionId}`;
1939
+ }
1940
+
1941
+ // src/services/testing/reducer-native-test-harness.ts
1942
+ globalThis.__DREAMBOARD_AUTHORING_WARNINGS__ = true;
1943
+ var GENERATED_TESTING_TYPES_PREFIX = "// Generated by dreamboard";
1944
+ var TESTING_TYPES_STUB = "export function defineScenario(scenario) { return scenario; }\n";
1945
+ var BASE_SUFFIX = ".base.ts";
1946
+ var SCENARIO_SUFFIX = ".scenario.ts";
1947
+ var SDK_UI_RUNTIME_EXTERNALS = [
1948
+ "@radix-ui/react-accordion",
1949
+ "@radix-ui/react-dialog",
1950
+ "@radix-ui/react-label",
1951
+ "@radix-ui/react-select",
1952
+ "@radix-ui/react-slot",
1953
+ "@radix-ui/react-tooltip",
1954
+ "@use-gesture/react",
1955
+ "clsx",
1956
+ "framer-motion",
1957
+ "lucide-react",
1958
+ "react",
1959
+ "react-dom",
1960
+ "vaul"
1961
+ ];
1962
+ function formatScenarioErrorForDisplay(options) {
1963
+ const message = options.error.message || "Scenario failed.";
1964
+ const scenarioFrame = findScenarioStackFrame({
1965
+ stack: options.error.stack,
1966
+ projectRoot: options.projectRoot,
1967
+ scenarioFilePath: options.scenarioFilePath
1968
+ });
1969
+ return scenarioFrame ? `${message}
1970
+ ${scenarioFrame}` : message;
1971
+ }
1972
+ function findScenarioStackFrame(options) {
1973
+ if (!options.stack) {
1974
+ return null;
1975
+ }
1976
+ const absolutePath = path3.resolve(options.scenarioFilePath);
1977
+ const relativePath = path3.relative(options.projectRoot, absolutePath);
1978
+ const normalizedRelativePath = relativePath.split(path3.sep).join("/");
1979
+ const escapedAbsolutePath = escapeRegExp(absolutePath);
1980
+ const escapedRelativePath = escapeRegExp(normalizedRelativePath);
1981
+ const absoluteFrame = new RegExp(`${escapedAbsolutePath}:(\\d+):(\\d+)`);
1982
+ const relativeFrame = new RegExp(`${escapedRelativePath}:(\\d+):(\\d+)`);
1983
+ for (const line of options.stack.split("\n")) {
1984
+ const normalizedLine = line.split(path3.sep).join("/");
1985
+ const match = normalizedLine.match(absoluteFrame) ?? normalizedLine.match(relativeFrame);
1986
+ if (match?.[1] && match?.[2]) {
1987
+ return `at ${normalizedRelativePath}:${match[1]}:${match[2]}`;
1988
+ }
1989
+ }
1990
+ return null;
1991
+ }
1992
+ function escapeRegExp(value) {
1993
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1994
+ }
1995
+ var projectReducerNativeModules = /* @__PURE__ */ new Map();
1996
+ function resolveProjectSdkModule(projectRoot, specifier) {
1997
+ const requireFromProject = createRequire(
1998
+ path3.join(projectRoot, "package.json")
1999
+ );
2000
+ return requireFromProject.resolve(specifier);
2001
+ }
2002
+ async function importProjectSdkModule(projectRoot, specifier) {
2003
+ const modulePath = resolveProjectSdkModule(projectRoot, specifier);
2004
+ return await import(pathToFileURL2(modulePath).href);
2005
+ }
2006
+ async function loadProjectReducerNativeModules(projectRoot) {
2007
+ const cacheKey = path3.resolve(projectRoot);
2008
+ const cached = projectReducerNativeModules.get(cacheKey);
2009
+ if (cached) {
2010
+ return cached;
2011
+ }
2012
+ const promise = Promise.all([
2013
+ importProjectSdkModule(cacheKey, "@dreamboard-games/sdk/reducer"),
2014
+ importProjectSdkModule(cacheKey, "@dreamboard-games/sdk/reducer-contract"),
2015
+ importProjectSdkModule(
2016
+ cacheKey,
2017
+ "@dreamboard-games/sdk/testing"
2018
+ )
2019
+ ]).then(([reducerModule, reducerContractModule, testingModule]) => {
2020
+ if (typeof reducerModule.createReducerBundle !== "function" || typeof reducerModule.contractFingerprint !== "function" || typeof reducerContractModule.materializeManifestTable !== "function" || typeof testingModule.createExpectApi !== "function") {
2021
+ throw new Error(
2022
+ "Installed @dreamboard-games/sdk does not expose the reducer-native test helpers required by this CLI."
2023
+ );
2024
+ }
2025
+ return {
2026
+ createReducerBundle: reducerModule.createReducerBundle,
2027
+ contractFingerprint: reducerModule.contractFingerprint,
2028
+ materializeManifestTable: reducerContractModule.materializeManifestTable,
2029
+ createExpectApi: testingModule.createExpectApi
2030
+ };
2031
+ });
2032
+ projectReducerNativeModules.set(cacheKey, promise);
2033
+ return promise;
2034
+ }
2035
+ function createSubmissionError(errorCode, message, fallbackMessage) {
2036
+ const error = new Error(message ?? fallbackMessage);
2037
+ error.name = "SubmissionError";
2038
+ error.errorCode = errorCode;
2039
+ return error;
2040
+ }
2041
+ function deepEqual(left, right) {
2042
+ return isDeepStrictEqual(left, right);
2043
+ }
2044
+ function shouldRefreshReducerTestingTypes(existingContent) {
2045
+ if (existingContent === null || existingContent.trim().length === 0 || existingContent === TESTING_TYPES_STUB || existingContent.startsWith(GENERATED_TESTING_TYPES_PREFIX)) {
2046
+ return true;
2047
+ }
2048
+ return false;
2049
+ }
2050
+ async function discoverFiles(root, suffix) {
2051
+ if (!await exists(root)) {
2052
+ return [];
2053
+ }
2054
+ const entries = await readdir(root, { withFileTypes: true });
2055
+ const files = [];
2056
+ for (const entry of entries) {
2057
+ const entryPath = path3.join(root, entry.name);
2058
+ if (entry.isDirectory()) {
2059
+ files.push(...await discoverFiles(entryPath, suffix));
2060
+ continue;
2061
+ }
2062
+ if (entry.isFile() && entry.name.endsWith(suffix)) {
2063
+ files.push(entryPath);
2064
+ }
2065
+ }
2066
+ files.sort();
2067
+ return files;
2068
+ }
2069
+ function isFunction(value) {
2070
+ return typeof value === "function";
2071
+ }
2072
+ function parseTypedBaseDefinition(value) {
2073
+ if (typeof value !== "object" || value === null || !("id" in value) || typeof value.id !== "string" || !("setup" in value) || !isFunction(value.setup)) {
2074
+ throw new Error("Invalid reducer-native base definition.");
2075
+ }
2076
+ const parentBaseId = "extends" in value && typeof value.extends === "string" ? value.extends : void 0;
2077
+ const seed = "seed" in value && typeof value.seed === "number" ? value.seed : void 0;
2078
+ const players = "players" in value && typeof value.players === "number" ? value.players : void 0;
2079
+ if ((seed === void 0 || players === void 0) && !parentBaseId) {
2080
+ throw new Error(
2081
+ "Invalid reducer-native base definition. Base definitions without --extends must declare numeric seed and players."
2082
+ );
2083
+ }
2084
+ const setupProfileId = "setupProfileId" in value && typeof value.setupProfileId === "string" ? value.setupProfileId : void 0;
2085
+ return {
2086
+ ...value,
2087
+ seed,
2088
+ players,
2089
+ setupProfileId,
2090
+ extends: parentBaseId
2091
+ };
2092
+ }
2093
+ function parseTypedScenarioDefinition(value) {
2094
+ if (typeof value !== "object" || value === null || !("id" in value) || typeof value.id !== "string" || !("from" in value) || typeof value.from !== "string" || !("when" in value) || !isFunction(value.when) || !("then" in value) || !isFunction(value.then)) {
2095
+ throw new Error("Invalid reducer-native scenario definition.");
2096
+ }
2097
+ const phase = "phase" in value && typeof value.phase === "string" ? value.phase : void 0;
2098
+ const stage = "stage" in value && typeof value.stage === "string" ? value.stage : void 0;
2099
+ return {
2100
+ ...value,
2101
+ phase,
2102
+ stage
2103
+ };
2104
+ }
2105
+ async function isReducerNativeTestingWorkspace(projectRoot) {
2106
+ return await exists(path3.join(projectRoot, "app", "game.ts")) && await exists(
2107
+ path3.join(projectRoot, "shared", "generated", "ui-contract.ts")
2108
+ );
2109
+ }
2110
+ async function ensureReducerNativeTestingFiles(projectRoot) {
2111
+ const testingTypesPath = "test/testing-types.ts";
2112
+ const testingContractPath = "test/generated/testing-contract.ts";
2113
+ const baseStatesPath = "test/generated/base-states.generated.ts";
2114
+ const baseStatesDtsPath = "test/generated/base-states.generated.d.ts";
2115
+ const scenarioManifestPath = "test/generated/scenario-manifest.generated.ts";
2116
+ await ensureDir(resolveWorkspacePath(projectRoot, "test"));
2117
+ await ensureDir(resolveWorkspacePath(projectRoot, "test/generated"));
2118
+ const existingTestingTypes = await readWorkspaceTextFileIfExists(
2119
+ projectRoot,
2120
+ testingTypesPath
2121
+ );
2122
+ if (shouldRefreshReducerTestingTypes(existingTestingTypes)) {
2123
+ await writeWorkspaceTextFile(
2124
+ projectRoot,
2125
+ testingTypesPath,
2126
+ REDUCER_TESTING_TYPES_WRAPPER_CONTENT
2127
+ );
2128
+ }
2129
+ const rejectionCodes = await collectKnownRejectionCodes(projectRoot);
2130
+ await writeWorkspaceTextFile(
2131
+ projectRoot,
2132
+ testingContractPath,
2133
+ buildReducerTestingContractContent({ rejectionCodes })
2134
+ );
2135
+ const header = "// Generated by dreamboard test. Do not edit by hand.\n";
2136
+ if (!await workspacePathExists(projectRoot, baseStatesPath)) {
2137
+ await writeWorkspaceTextFile(
2138
+ projectRoot,
2139
+ baseStatesPath,
2140
+ `${header}export const BASE_STATES = {} as const;
2141
+ export const BASE_STATES_CONTRACT_FINGERPRINT = undefined;
2142
+ `
2143
+ );
2144
+ } else {
2145
+ const existingBaseStates = await readWorkspaceTextFileIfExists(
2146
+ projectRoot,
2147
+ baseStatesPath
2148
+ );
2149
+ if (existingBaseStates && !existingBaseStates.includes("BASE_STATES_CONTRACT_FINGERPRINT")) {
2150
+ await writeWorkspaceTextFile(
2151
+ projectRoot,
2152
+ baseStatesPath,
2153
+ `${existingBaseStates.trimEnd()}
2154
+ export const BASE_STATES_CONTRACT_FINGERPRINT = undefined;
2155
+ `
2156
+ );
2157
+ }
2158
+ }
2159
+ if (!await workspacePathExists(projectRoot, baseStatesDtsPath)) {
2160
+ await writeWorkspaceTextFile(
2161
+ projectRoot,
2162
+ baseStatesDtsPath,
2163
+ `${header}export declare const BASE_STATES: Record<string, unknown>;
2164
+ export declare const BASE_STATES_CONTRACT_FINGERPRINT: string | undefined;
2165
+ `
2166
+ );
2167
+ } else {
2168
+ const existingBaseStatesDts = await readWorkspaceTextFileIfExists(
2169
+ projectRoot,
2170
+ baseStatesDtsPath
2171
+ );
2172
+ if (existingBaseStatesDts && !existingBaseStatesDts.includes("BASE_STATES_CONTRACT_FINGERPRINT")) {
2173
+ await writeWorkspaceTextFile(
2174
+ projectRoot,
2175
+ baseStatesDtsPath,
2176
+ `${existingBaseStatesDts.trimEnd()}
2177
+ export declare const BASE_STATES_CONTRACT_FINGERPRINT: string | undefined;
2178
+ `
2179
+ );
2180
+ }
2181
+ }
2182
+ if (!await workspacePathExists(projectRoot, scenarioManifestPath)) {
2183
+ await writeWorkspaceTextFile(
2184
+ projectRoot,
2185
+ scenarioManifestPath,
2186
+ `${header}export const SCENARIO_MANIFEST = [] as const;
2187
+ `
2188
+ );
2189
+ }
2190
+ }
2191
+ var DEFAULT_REJECTION_CODES = [
2192
+ "NOT_YOUR_TURN",
2193
+ "action-unavailable",
2194
+ "invalid-action-params",
2195
+ "prompt-not-owned"
2196
+ ];
2197
+ async function collectKnownRejectionCodes(projectRoot) {
2198
+ const knownCodes = new Set(DEFAULT_REJECTION_CODES);
2199
+ const gamePath = path3.join(projectRoot, "app", "game.ts");
2200
+ if (!await exists(gamePath)) {
2201
+ return Array.from(knownCodes).sort(
2202
+ (left, right) => left.localeCompare(right)
2203
+ );
2204
+ }
2205
+ try {
2206
+ const module = await importTypeScriptModule(gamePath);
2207
+ const phases = module.default?.phases ?? {};
2208
+ for (const phase of Object.values(phases)) {
2209
+ const interactions = phase.interactions ?? {};
2210
+ for (const interaction of Object.values(interactions)) {
2211
+ for (const errorCode of interaction.errorCodes ?? []) {
2212
+ if (typeof errorCode === "string" && errorCode.length > 0) {
2213
+ knownCodes.add(errorCode);
2214
+ }
2215
+ }
2216
+ }
2217
+ }
2218
+ } catch {
2219
+ }
2220
+ return Array.from(knownCodes).sort(
2221
+ (left, right) => left.localeCompare(right)
2222
+ );
2223
+ }
2224
+ async function loadTypedBases(projectRoot) {
2225
+ const baseFiles = await discoverFiles(
2226
+ resolveWorkspacePath(projectRoot, "test/bases"),
2227
+ BASE_SUFFIX
2228
+ );
2229
+ const loaded = [];
2230
+ for (const filePath of baseFiles) {
2231
+ const externals = reducerNativeTestHelperExternals(projectRoot, filePath);
2232
+ const [module, bundledText] = await Promise.all([
2233
+ importTypeScriptModule(filePath),
2234
+ bundleTypeScriptModuleText(filePath, { external: externals })
2235
+ ]);
2236
+ loaded.push({
2237
+ filePath,
2238
+ definition: parseTypedBaseDefinition(module.default),
2239
+ bundleHash: hashContent(bundledText)
2240
+ });
2241
+ }
2242
+ return loaded;
2243
+ }
2244
+ async function loadTypedScenarios(projectRoot, options) {
2245
+ const scenarioFiles = options.scenarioPath ? [resolveWorkspacePath(projectRoot, options.scenarioPath)] : await discoverFiles(
2246
+ resolveWorkspacePath(projectRoot, "test/scenarios"),
2247
+ SCENARIO_SUFFIX
2248
+ );
2249
+ const loaded = [];
2250
+ for (const filePath of scenarioFiles) {
2251
+ const externals = reducerNativeTestHelperExternals(projectRoot, filePath);
2252
+ const [module, bundledText] = await Promise.all([
2253
+ importTypeScriptModule(filePath),
2254
+ bundleTypeScriptModuleText(filePath, { external: externals })
2255
+ ]);
2256
+ loaded.push({
2257
+ filePath,
2258
+ definition: parseTypedScenarioDefinition(module.default),
2259
+ bundleHash: hashContent(bundledText)
2260
+ });
2261
+ }
2262
+ return loaded;
2263
+ }
2264
+ function reducerNativeTestHelperExternals(projectRoot, filePath) {
2265
+ const testingTypesPath = path3.join(projectRoot, "test", "testing-types");
2266
+ const relative = path3.relative(path3.dirname(filePath), testingTypesPath).replaceAll("\\", "/");
2267
+ const specifier = relative.startsWith(".") ? relative : `./${relative}`;
2268
+ return [specifier, `${specifier}.ts`, ...SDK_UI_RUNTIME_EXTERNALS];
2269
+ }
2270
+ var JS_MAX_SAFE_INTEGER = 9007199254740991n;
2271
+ var JS_MIN_SAFE_INTEGER = -JS_MAX_SAFE_INTEGER;
2272
+ var JS_MAX_SAFE_INTEGER_EXCLUSIVE = JS_MAX_SAFE_INTEGER + 1n;
2273
+ var KotlinSeededRandom = class {
2274
+ x;
2275
+ y;
2276
+ z;
2277
+ w;
2278
+ v;
2279
+ addend;
2280
+ constructor(seed) {
2281
+ const seedBig = BigInt.asIntN(64, BigInt(Math.trunc(seed)));
2282
+ const seed1 = Number(BigInt.asIntN(32, seedBig));
2283
+ const seed2 = Number(BigInt.asIntN(32, seedBig >> 32n));
2284
+ this.x = seed1 | 0;
2285
+ this.y = seed2 | 0;
2286
+ this.z = 0;
2287
+ this.w = 0;
2288
+ this.v = ~seed1;
2289
+ this.addend = seed1 << 10 ^ seed2 >>> 4 | 0;
2290
+ if ((this.x | this.y | this.z | this.w | this.v) === 0) {
2291
+ throw new Error(
2292
+ "Kotlin random seed must initialize at least one state word."
2293
+ );
2294
+ }
2295
+ for (let index = 0; index < 64; index += 1) {
2296
+ this.nextInt();
2297
+ }
2298
+ }
2299
+ nextInt() {
2300
+ let next = this.x | 0;
2301
+ next ^= next >>> 2;
2302
+ this.x = this.y;
2303
+ this.y = this.z;
2304
+ this.z = this.w;
2305
+ const currentV = this.v | 0;
2306
+ this.w = currentV;
2307
+ next = next ^ next << 1 ^ currentV ^ currentV << 4 | 0;
2308
+ this.v = next;
2309
+ this.addend = this.addend + 362437 | 0;
2310
+ return next + this.addend | 0;
2311
+ }
2312
+ nextBits(bitCount) {
2313
+ if (bitCount <= 0) {
2314
+ return 0;
2315
+ }
2316
+ return this.nextInt() >>> 32 - bitCount;
2317
+ }
2318
+ nextIntBound(bound) {
2319
+ if (bound <= 0) {
2320
+ throw new Error("bound must be positive");
2321
+ }
2322
+ if ((bound & -bound) === bound) {
2323
+ const bitCount = 31 - Math.clz32(bound);
2324
+ return this.nextBits(bitCount);
2325
+ }
2326
+ let value;
2327
+ while (true) {
2328
+ const bits = this.nextInt() >>> 1;
2329
+ value = bits % bound;
2330
+ if (bits - value + (bound - 1) >= 0) {
2331
+ return value;
2332
+ }
2333
+ }
2334
+ }
2335
+ nextLong() {
2336
+ return Number(this.nextLongBigInt());
2337
+ }
2338
+ nextLongBigInt() {
2339
+ const high = BigInt(this.nextInt());
2340
+ const low = BigInt(this.nextInt());
2341
+ return BigInt.asIntN(64, (high << 32n) + low);
2342
+ }
2343
+ nextReducerRuntimeSeed() {
2344
+ return Number(
2345
+ this.nextLongRange(JS_MIN_SAFE_INTEGER, JS_MAX_SAFE_INTEGER_EXCLUSIVE)
2346
+ );
2347
+ }
2348
+ nextLongRange(from, until) {
2349
+ if (until <= from) {
2350
+ throw new Error("until must be greater than from");
2351
+ }
2352
+ const bound = until - from;
2353
+ const mask = bound - 1n;
2354
+ if ((bound & mask) === 0n) {
2355
+ return from + (BigInt.asUintN(64, this.nextLongBigInt()) & mask);
2356
+ }
2357
+ while (true) {
2358
+ const bits = BigInt.asUintN(64, this.nextLongBigInt()) >> 1n;
2359
+ const value = bits % bound;
2360
+ if (BigInt.asIntN(64, bits + mask - value) >= 0n) {
2361
+ return from + value;
2362
+ }
2363
+ }
2364
+ }
2365
+ };
2366
+ function shuffleWithKotlinRandom(values, random) {
2367
+ const next = [...values];
2368
+ for (let index = next.length - 1; index > 0; index -= 1) {
2369
+ const swapIndex = random.nextIntBound(index + 1);
2370
+ const current = next[index];
2371
+ next[index] = next[swapIndex];
2372
+ next[swapIndex] = current;
2373
+ }
2374
+ return next;
2375
+ }
2376
+ function resolveEffectiveBaseSetup(options) {
2377
+ const inheritedSetupProfileId = options.base.setupProfileId ?? (options.base.extends && options.basesById ? resolveEffectiveBaseSetup({
2378
+ manifest: options.manifest,
2379
+ base: options.basesById.get(options.base.extends)?.definition ?? (() => {
2380
+ throw new Error(
2381
+ `Base '${options.base.id}' extends unknown parent '${options.base.extends}'.`
2382
+ );
2383
+ })(),
2384
+ basesById: options.basesById
2385
+ }).setupProfileId : void 0);
2386
+ const selection = resolveSetupProfileSelection({
2387
+ manifest: options.manifest,
2388
+ requestedSetupProfileId: inheritedSetupProfileId ?? void 0
2389
+ });
2390
+ return {
2391
+ setupProfileId: selection.id
2392
+ };
2393
+ }
2394
+ function resolveBaseDefinition(base, basesById) {
2395
+ const inherited = base.definition.extends !== void 0 ? resolveBaseDefinition(
2396
+ basesById.get(base.definition.extends) ?? (() => {
2397
+ throw new Error(
2398
+ `Base '${base.definition.id}' extends unknown parent '${base.definition.extends}'.`
2399
+ );
2400
+ })(),
2401
+ basesById
2402
+ ) : null;
2403
+ const seed = base.definition.seed ?? inherited?.seed;
2404
+ const players = base.definition.players ?? inherited?.players;
2405
+ if (seed === void 0 || players === void 0) {
2406
+ throw new Error(
2407
+ `Base '${base.definition.id}' must resolve numeric seed and players.`
2408
+ );
2409
+ }
2410
+ return {
2411
+ ...base.definition,
2412
+ seed,
2413
+ players,
2414
+ setupProfileId: base.definition.setupProfileId ?? inherited?.setupProfileId ?? void 0
2415
+ };
2416
+ }
2417
+ function summarizeTableValidationError(manifest, error) {
2418
+ const issues = error.message.split("; ").map((issue) => issue.trim()).filter((issue) => issue.length > 0);
2419
+ if (issues.length === 0 || !issues.every((issue) => issue.startsWith("table"))) {
2420
+ return error.message;
2421
+ }
2422
+ const boardBaseIdByRuntimeId = new Map(
2423
+ (manifest.boards ?? []).flatMap(
2424
+ (board) => board.scope === "perPlayer" ? Array.from(
2425
+ { length: manifest.players.maxPlayers },
2426
+ (_, index) => [`${board.id}:player-${index + 1}`, board.id]
2427
+ ) : [[board.id, board.id]]
2428
+ )
2429
+ );
2430
+ const representativeIssues = issues.slice(0, 3).map((issue) => {
2431
+ const [, runtimeBoardId = ""] = issue.match(/^table\.boards\.byId\.([^.]+)\./) ?? [];
2432
+ const boardBaseId = boardBaseIdByRuntimeId.get(runtimeBoardId);
2433
+ if (!boardBaseId) {
2434
+ return `- ${issue.replace(/^table\./, "")}`;
2435
+ }
2436
+ const boardSpecificPath = issue.replace(/^table\.boards\.byId\.[^.]+\./, "").replace(/^table\./, "");
2437
+ return `- board '${boardBaseId}' (${runtimeBoardId}): ${boardSpecificPath}`;
2438
+ });
2439
+ return [
2440
+ `Reducer-native table validation failed with ${issues.length} issue${issues.length === 1 ? "" : "s"}.`,
2441
+ "Likely root cause: the generated test table shape does not match the authored manifest topology.",
2442
+ ...representativeIssues,
2443
+ "Pass --debug for the full validation dump."
2444
+ ].join("\n");
2445
+ }
2446
+ var ShadowReducerRuntime = class {
2447
+ constructor(modules, manifest, gameModuleDefault, createInitialTable, seed, players, setupProfileId, debug = false) {
2448
+ this.modules = modules;
2449
+ this.manifest = manifest;
2450
+ this.gameModuleDefault = gameModuleDefault;
2451
+ this.createInitialTable = createInitialTable;
2452
+ this.seed = seed;
2453
+ this.players = players;
2454
+ this.setupProfileId = setupProfileId;
2455
+ this.debug = debug;
2456
+ if (typeof gameModuleDefault !== "object" || gameModuleDefault === null || !("contract" in gameModuleDefault)) {
2457
+ throw new Error(
2458
+ "app/game.ts must export a reducer-native game definition."
2459
+ );
2460
+ }
2461
+ this.bundle = this.modules.createReducerBundle(gameModuleDefault);
2462
+ this.runtime = this.bundle.createInProcessRuntime();
2463
+ this.playerIds = Array.from(
2464
+ { length: players },
2465
+ (_, index) => `player-${index + 1}`
2466
+ );
2467
+ }
2468
+ bundle;
2469
+ runtime;
2470
+ playerIds;
2471
+ historyRecords = [];
2472
+ version = 0;
2473
+ started = false;
2474
+ async start() {
2475
+ if (this.started) {
2476
+ return;
2477
+ }
2478
+ const random = new KotlinSeededRandom(this.seed);
2479
+ const shuffleItems = (values) => shuffleWithKotlinRandom(values, random);
2480
+ const table = JSON.parse(
2481
+ JSON.stringify(
2482
+ this.createInitialTable?.({
2483
+ playerIds: this.playerIds,
2484
+ shuffleItems
2485
+ }) ?? this.modules.materializeManifestTable({
2486
+ manifest: this.manifest,
2487
+ playerIds: this.playerIds,
2488
+ shuffleItems
2489
+ })
2490
+ )
2491
+ );
2492
+ const rngSeed = random.nextReducerRuntimeSeed();
2493
+ try {
2494
+ await this.runtime.initialize({
2495
+ table,
2496
+ playerIds: this.playerIds,
2497
+ rngSeed,
2498
+ setup: this.setupProfileId ? {
2499
+ profileId: this.setupProfileId
2500
+ } : null
2501
+ });
2502
+ } catch (error) {
2503
+ if (!this.debug && error instanceof Error) {
2504
+ throw new Error(summarizeTableValidationError(this.manifest, error));
2505
+ }
2506
+ throw error;
2507
+ }
2508
+ this.version = 0;
2509
+ this.started = true;
2510
+ }
2511
+ phase() {
2512
+ return (this.runtime.unsafeState()?.domain?.flow?.currentPhase ?? null) || "";
2513
+ }
2514
+ playerOrder() {
2515
+ return this.playerIds;
2516
+ }
2517
+ rawState() {
2518
+ return this.runtime.snapshot();
2519
+ }
2520
+ currentVersion() {
2521
+ return this.version;
2522
+ }
2523
+ hydrate(snapshot, version = 0) {
2524
+ this.runtime.hydrate({ state: structuredClone(snapshot) });
2525
+ this.version = version;
2526
+ this.started = true;
2527
+ }
2528
+ patchState(mutator) {
2529
+ const next = structuredClone(this.rawState());
2530
+ mutator(next);
2531
+ this.hydrate(next, this.version + 1);
2532
+ }
2533
+ projectAllSeats() {
2534
+ const projection = this.runtime.projectSeatsDynamic({
2535
+ playerIds: this.playerIds
2536
+ });
2537
+ const interactionsByRef = projection.interactionsByRef && typeof projection.interactionsByRef === "object" && !Array.isArray(projection.interactionsByRef) ? projection.interactionsByRef : {};
2538
+ const seats = Object.fromEntries(
2539
+ Object.entries(projection.seats ?? {}).map(([playerId, seat]) => {
2540
+ const availableInteractionRefs = Array.isArray(
2541
+ seat.availableInteractionRefs
2542
+ ) ? seat.availableInteractionRefs.filter(
2543
+ (ref) => typeof ref === "string"
2544
+ ) : [];
2545
+ const availableInteractions = seat.availableInteractions ?? availableInteractionRefs.map((ref) => interactionsByRef[ref]).filter(
2546
+ (descriptor) => !!descriptor && typeof descriptor === "object"
2547
+ );
2548
+ return [
2549
+ playerId,
2550
+ {
2551
+ view: seat.view,
2552
+ availableInteractions,
2553
+ zones: seat.zones
2554
+ }
2555
+ ];
2556
+ })
2557
+ );
2558
+ return {
2559
+ currentStage: projection.currentStage ?? null,
2560
+ stageSeats: projection.stageSeats ?? [],
2561
+ seats
2562
+ };
2563
+ }
2564
+ currentStage() {
2565
+ return this.projectAllSeats().currentStage;
2566
+ }
2567
+ view(playerId) {
2568
+ return this.runtime.projectSeatViewDynamic({
2569
+ playerId
2570
+ }) ?? null;
2571
+ }
2572
+ availableInteractionsForPlayer(playerId) {
2573
+ const projection = this.projectAllSeats();
2574
+ const seat = projection.seats[playerId];
2575
+ const descriptors = seat?.availableInteractions ?? [];
2576
+ return descriptors.filter(
2577
+ (descriptor) => !!descriptor && typeof descriptor.interactionId === "string"
2578
+ ).map((descriptor) => descriptor.interactionId);
2579
+ }
2580
+ /**
2581
+ * Phase-kind interaction descriptors (action + prompt) available to
2582
+ * `playerId` in the current phase. Surfaces the same projection the UI
2583
+ * SDK consumes, so scenarios can assert addressee authorization and
2584
+ * availability without reaching into game-specific state. Returned as
2585
+ * loose records — the typed `InteractionDescriptor` shape is narrowed
2586
+ * downstream in the workspace-generated `testing-contract.ts`.
2587
+ */
2588
+ interactionsForPlayer(playerId) {
2589
+ return this.projectAllSeats().seats[playerId]?.availableInteractions ?? [];
2590
+ }
2591
+ explain(playerId, interactionId) {
2592
+ const runtime = this.runtime;
2593
+ if (typeof runtime.explainInteraction !== "function") {
2594
+ throw new Error(
2595
+ "The installed @dreamboard-games/sdk does not expose interaction explanations. Update the workspace SDK pin."
2596
+ );
2597
+ }
2598
+ return runtime.explainInteraction({ playerId, interactionId });
2599
+ }
2600
+ clearHistory() {
2601
+ this.historyRecords.length = 0;
2602
+ }
2603
+ async applyInput(input) {
2604
+ const parsedInput = toReducerInput(input);
2605
+ const result = await this.runtime.dispatch({ input: parsedInput });
2606
+ if (result.kind === "reject") {
2607
+ const record = {
2608
+ input,
2609
+ accepted: false,
2610
+ errorCode: result.errorCode,
2611
+ message: result.message
2612
+ };
2613
+ this.historyRecords.push(record);
2614
+ throw createSubmissionError(
2615
+ result.errorCode,
2616
+ result.message,
2617
+ "Reducer input rejected."
2618
+ );
2619
+ }
2620
+ this.version += 1;
2621
+ this.historyRecords.push({ input, accepted: true });
2622
+ }
2623
+ async submitInteraction(playerId, interactionId, params) {
2624
+ await this.applyInput({
2625
+ kind: "interaction",
2626
+ playerId,
2627
+ interactionId,
2628
+ params
2629
+ });
2630
+ }
2631
+ };
2632
+ function toReducerInput(input) {
2633
+ return {
2634
+ kind: "interaction",
2635
+ playerId: input.playerId,
2636
+ interactionId: input.interactionId,
2637
+ params: input.params
2638
+ };
2639
+ }
2640
+ function sanitizeSnapshotSegment(value) {
2641
+ return value.replace(/[^a-zA-Z0-9._-]+/g, "-");
2642
+ }
2643
+ function createScenarioSnapshotMatcher(options) {
2644
+ return (filename, actual) => {
2645
+ const suffix = filename ? `.${sanitizeSnapshotSegment(filename)}` : "";
2646
+ const snapshotPath = resolveWorkspacePath(
2647
+ options.projectRoot,
2648
+ `test/generated/snapshots/${sanitizeSnapshotSegment(options.scenarioId)}${suffix}.snapshot.json`
2649
+ );
2650
+ const wrappedValue = {
2651
+ value: actual
2652
+ };
2653
+ const serialized = `${JSON.stringify(wrappedValue, null, 2)}
2654
+ `;
2655
+ mkdirSync(path3.dirname(snapshotPath), { recursive: true });
2656
+ if (!existsSync(snapshotPath) || options.updateSnapshots) {
2657
+ writeFileSync(snapshotPath, serialized, "utf8");
2658
+ return;
2659
+ }
2660
+ const previous = JSON.parse(readFileSync(snapshotPath, "utf8"));
2661
+ if (!deepEqual(previous.value, actual)) {
2662
+ throw new Error(
2663
+ `Snapshot mismatch for scenario '${options.scenarioId}'. Re-run with --update-snapshots to refresh ${path3.relative(options.projectRoot, snapshotPath)}.`
2664
+ );
2665
+ }
2666
+ };
2667
+ }
2668
+ async function createScenarioContext(options) {
2669
+ const api = {
2670
+ start: async () => {
2671
+ await options.shadow.start();
2672
+ },
2673
+ patchState: async (mutator) => {
2674
+ await api.start();
2675
+ if (options.live || options.actionPlan) {
2676
+ throw new Error(
2677
+ "game.patchState is only supported for reducer snapshot scenarios. Use it to materialize a state before --from-scenario or reducer tests, not inside live replay."
2678
+ );
2679
+ }
2680
+ options.shadow.patchState(mutator);
2681
+ },
2682
+ submit: async (playerId, interactionId, params) => {
2683
+ await api.start();
2684
+ const interactionParams = params ?? {};
2685
+ const normalizedInputs = interactionParams && typeof interactionParams === "object" && !Array.isArray(interactionParams) ? interactionParams : {};
2686
+ const previousVersion = options.live ? options.live.version : options.actionPlan ? options.shadow.currentVersion() : 0;
2687
+ if (options.live) {
2688
+ if (!options.live.actionSetVersion) {
2689
+ options.live.actionSetVersion = await fetchLiveActionSetVersion(
2690
+ options.live.sessionId,
2691
+ playerId
2692
+ );
2693
+ }
2694
+ const submittedActionSetVersion = options.live.actionSetVersion;
2695
+ const submitStartedAt = performance.now();
2696
+ const clientActionId = randomUUID3();
2697
+ const { data, error, response } = await submitGameplayAuthorityAction({
2698
+ path: {
2699
+ sessionId: options.live.sessionId,
2700
+ playerId,
2701
+ interactionId
2702
+ },
2703
+ body: {
2704
+ expectedVersion: previousVersion,
2705
+ actionSetVersion: options.live.actionSetVersion,
2706
+ inputs: normalizedInputs
2707
+ },
2708
+ headers: { "X-Dreamboard-Client-Action-Id": clientActionId }
2709
+ });
2710
+ const durationMs = performance.now() - submitStartedAt;
2711
+ options.live.diagnostics?.push({
2712
+ index: options.live.submitIndex ?? 0,
2713
+ playerId,
2714
+ interactionId,
2715
+ inputs: normalizedInputs,
2716
+ expectedVersion: previousVersion,
2717
+ actionSetVersion: submittedActionSetVersion,
2718
+ responseStatus: response?.status,
2719
+ responseBody: options.live.captureResponseBody === false ? void 0 : JSON.stringify(error ?? data ?? null),
2720
+ accepted: data?.accepted ?? void 0,
2721
+ errorCode: data?.accepted === false ? data.errorCode ?? void 0 : error && typeof error === "object" && "detail" in error ? String(error.detail) : void 0,
2722
+ backendTiming: response?.headers?.get("server-timing") ?? response?.headers?.get("x-dreamboard-timing") ?? void 0,
2723
+ durationMs
2724
+ });
2725
+ options.live.submitIndex = (options.live.submitIndex ?? 0) + 1;
2726
+ if (error) {
2727
+ throw createSubmissionError(
2728
+ "api-error",
2729
+ void 0,
2730
+ "Failed to submit interaction"
2731
+ );
2732
+ }
2733
+ if (data?.accepted === false) {
2734
+ const shadowError = await tryShadowSubmit(
2735
+ options.shadow,
2736
+ playerId,
2737
+ interactionId,
2738
+ interactionParams
2739
+ );
2740
+ if (!shadowError || shadowError.errorCode !== data.errorCode) {
2741
+ throw new Error(
2742
+ "Live session rejection diverged from reducer shadow state."
2743
+ );
2744
+ }
2745
+ throw createSubmissionError(
2746
+ data.errorCode ?? void 0,
2747
+ data.message ?? void 0,
2748
+ "Interaction rejected"
2749
+ );
2750
+ }
2751
+ options.live.version = typeof data?.version === "number" ? data.version : previousVersion + 1;
2752
+ options.live.actionSetVersion = data?.actionSetVersion ?? options.live.actionSetVersion;
2753
+ }
2754
+ await options.shadow.submitInteraction(
2755
+ playerId,
2756
+ interactionId,
2757
+ interactionParams
2758
+ );
2759
+ if (options.actionPlan) {
2760
+ options.actionPlan.diagnostics.push({
2761
+ index: options.actionPlan.submitIndex ?? 0,
2762
+ playerId,
2763
+ interactionId,
2764
+ inputs: normalizedInputs,
2765
+ expectedVersion: previousVersion,
2766
+ actionSetVersion: "",
2767
+ accepted: true,
2768
+ durationMs: 0
2769
+ });
2770
+ options.actionPlan.submitIndex = (options.actionPlan.submitIndex ?? 0) + 1;
2771
+ }
2772
+ }
2773
+ };
2774
+ return {
2775
+ game: api,
2776
+ players: () => options.shadow.playerOrder(),
2777
+ seat: (index) => {
2778
+ const order = options.shadow.playerOrder();
2779
+ if (!Number.isInteger(index) || index < 0 || index >= order.length) {
2780
+ throw new Error(
2781
+ `seat(${index}) is out of range; scenario has ${order.length} player(s).`
2782
+ );
2783
+ }
2784
+ return order[index];
2785
+ },
2786
+ state: () => options.shadow.phase(),
2787
+ view: (playerId) => options.shadow.view(playerId),
2788
+ interactions: (playerId) => options.shadow.interactionsForPlayer(playerId),
2789
+ explain: (playerId, interactionId) => options.shadow.explain(playerId, interactionId),
2790
+ expect: options.expect
2791
+ };
2792
+ }
2793
+ async function tryShadowSubmit(shadow, playerId, interactionId, params) {
2794
+ try {
2795
+ await shadow.submitInteraction(playerId, interactionId, params);
2796
+ throw new Error("Expected shadow interaction to reject.");
2797
+ } catch (error) {
2798
+ if (error instanceof Error && error.name === "SubmissionError") {
2799
+ return error;
2800
+ }
2801
+ throw error;
2802
+ }
2803
+ }
2804
+ async function createSessionFromScenario(options) {
2805
+ const startedAt = Date.now();
2806
+ const materialized = await materializeScenarioReducerState(options);
2807
+ const reducerHarnessMs = Date.now() - startedAt;
2808
+ const hydrateStartedAt = Date.now();
2809
+ const {
2810
+ data: snapshot,
2811
+ error,
2812
+ response
2813
+ } = await createProjectSessionFromReducerSnapshot({
2814
+ path: { projectId: options.projectId },
2815
+ body: {
2816
+ compiledResultId: options.compiledResultId,
2817
+ seed: materialized.seed,
2818
+ playerCount: materialized.playerCount,
2819
+ setupProfileId: materialized.setupProfileId ?? void 0,
2820
+ baseId: materialized.baseId,
2821
+ scenarioId: materialized.scenarioId,
2822
+ reducerState: materialized.reducerState,
2823
+ reducerStateVersion: materialized.reducerStateVersion,
2824
+ fingerprintMetadata: materialized.fingerprintMetadata
2825
+ }
2826
+ });
2827
+ const backendHydrateMs = Date.now() - hydrateStartedAt;
2828
+ if (error || !snapshot) {
2829
+ throw toDreamboardApiError(
2830
+ error,
2831
+ response,
2832
+ `Failed to materialize scenario '${options.scenarioId}' from reducer snapshot`
2833
+ );
2834
+ }
2835
+ return {
2836
+ sessionId: snapshot.context.sessionId,
2837
+ shortCode: snapshot.context.shortCode,
2838
+ gameId: projectIdFromSessionGameSource(snapshot.context.gameSource),
2839
+ seed: materialized.seed,
2840
+ playerCount: materialized.playerCount,
2841
+ setupProfileId: materialized.setupProfileId,
2842
+ scenarioId: materialized.scenarioId,
2843
+ phase: materialized.phase,
2844
+ stage: materialized.stage,
2845
+ materialization: {
2846
+ mode: "snapshot",
2847
+ totalMs: Date.now() - startedAt,
2848
+ reducerHarnessMs,
2849
+ backendHydrateMs
2850
+ }
2851
+ };
2852
+ }
2853
+ var MATERIALIZED_SCENARIO_CACHE_VERSION = 1;
2854
+ function materializedScenarioCachePath(options) {
2855
+ return [
2856
+ PROJECT_DIR_NAME,
2857
+ "dev",
2858
+ "scenario-cache",
2859
+ `${sanitizeSnapshotSegment(options.baseId)}.${sanitizeSnapshotSegment(
2860
+ options.scenarioId
2861
+ )}.${options.fingerprintHash}.json`
2862
+ ].join("/");
2863
+ }
2864
+ function materializedScenarioCacheFilePath(options) {
2865
+ return resolveWorkspacePath(
2866
+ options.projectRoot,
2867
+ materializedScenarioCachePath(options)
2868
+ );
2869
+ }
2870
+ async function readMaterializedScenarioCache(options) {
2871
+ const text = await readWorkspaceTextFileIfExists(
2872
+ options.projectRoot,
2873
+ materializedScenarioCachePath(options)
2874
+ );
2875
+ if (!text) return null;
2876
+ try {
2877
+ const payload = JSON.parse(
2878
+ text
2879
+ );
2880
+ if (payload.cacheVersion !== MATERIALIZED_SCENARIO_CACHE_VERSION || payload.fingerprintHash !== options.fingerprintHash || !payload.materialized) {
2881
+ return null;
2882
+ }
2883
+ return payload.materialized;
2884
+ } catch {
2885
+ return null;
2886
+ }
2887
+ }
2888
+ async function writeMaterializedScenarioCache(options) {
2889
+ const cachePath = materializedScenarioCacheFilePath(options);
2890
+ await ensureDir(path3.dirname(cachePath));
2891
+ await writeWorkspaceJsonFile(
2892
+ options.projectRoot,
2893
+ materializedScenarioCachePath(options),
2894
+ {
2895
+ cacheVersion: MATERIALIZED_SCENARIO_CACHE_VERSION,
2896
+ fingerprintHash: options.fingerprintHash,
2897
+ materialized: options.materialized
2898
+ }
2899
+ );
2900
+ }
2901
+ async function materializeScenarioReducerState(options) {
2902
+ await ensureReducerNativeTestingFiles(options.projectRoot);
2903
+ let preloadedGeneratedBaseStates;
2904
+ if (options.trustGeneratedFingerprint === true) {
2905
+ const [generatedBaseStates2, scenarioManifest] = await Promise.all([
2906
+ loadGeneratedBaseStates(options.projectRoot),
2907
+ loadGeneratedScenarioManifest(options.projectRoot)
2908
+ ]);
2909
+ preloadedGeneratedBaseStates = generatedBaseStates2;
2910
+ const scenarioEntry = scenarioManifest.find(
2911
+ (entry) => entry.id === options.scenarioId
2912
+ );
2913
+ const generatedBase2 = scenarioEntry ? generatedBaseStates2?.[baseStateKey(scenarioEntry.base)] : null;
2914
+ if (generatedBase2 && generatedBase2.fingerprint.compiledResultId === options.compiledResultId && generatedBase2.fingerprint.gameId === options.gameId) {
2915
+ const cached2 = await readMaterializedScenarioCache({
2916
+ projectRoot: options.projectRoot,
2917
+ baseId: scenarioEntry.base,
2918
+ scenarioId: options.scenarioId,
2919
+ fingerprintHash: fingerprintHash(generatedBase2.fingerprint)
2920
+ });
2921
+ if (cached2) {
2922
+ return cached2;
2923
+ }
2924
+ }
2925
+ }
2926
+ const [bases, scenarios, generatedBaseStates, manifest] = await Promise.all([
2927
+ loadTypedBases(options.projectRoot),
2928
+ loadTypedScenarios(options.projectRoot, {}),
2929
+ preloadedGeneratedBaseStates === void 0 ? loadGeneratedBaseStates(options.projectRoot) : Promise.resolve(preloadedGeneratedBaseStates),
2930
+ loadManifest(options.projectRoot)
2931
+ ]);
2932
+ const matchingScenarios = scenarios.filter(
2933
+ (scenario2) => scenario2.definition.id === options.scenarioId
2934
+ );
2935
+ if (matchingScenarios.length === 0) {
2936
+ throw new Error(
2937
+ `Unknown scenario '${options.scenarioId}'. Available scenarios: ${scenarios.map((scenario2) => scenario2.definition.id).sort().join(", ")}`
2938
+ );
2939
+ }
2940
+ if (matchingScenarios.length > 1) {
2941
+ throw new Error(
2942
+ `Scenario id '${options.scenarioId}' is defined more than once. Keep one scenario per file and one unique id per workspace.`
2943
+ );
2944
+ }
2945
+ const scenario = matchingScenarios[0];
2946
+ const basesById = new Map(bases.map((base2) => [base2.definition.id, base2]));
2947
+ validateTypedScenarioBases([scenario], basesById);
2948
+ const base = basesById.get(scenario.definition.from);
2949
+ if (!base) {
2950
+ throw new Error(
2951
+ `Missing typed base '${scenario.definition.from}' for scenario '${scenario.definition.id}'.`
2952
+ );
2953
+ }
2954
+ const generatedBase = generatedBaseStates?.[baseStateKey(base.definition.id)];
2955
+ if (!generatedBase) {
2956
+ throw new Error(
2957
+ `Missing generated base artifact for '${base.definition.id}'. Run 'dreamboard test' before using --from-scenario.`
2958
+ );
2959
+ }
2960
+ if (typeof generatedBase.version !== "number") {
2961
+ throw new Error(
2962
+ `Generated base artifact for '${base.definition.id}' is stale. Run 'dreamboard test' before using --from-scenario.`
2963
+ );
2964
+ }
2965
+ const canTrustGeneratedFingerprint = options.trustGeneratedFingerprint === true && generatedBase.fingerprint.compiledResultId === options.compiledResultId && generatedBase.fingerprint.gameId === options.gameId;
2966
+ const current = canTrustGeneratedFingerprint ? generatedBase.fingerprint : await currentFingerprint({
2967
+ projectRoot: options.projectRoot,
2968
+ base,
2969
+ basesById,
2970
+ compiledResultId: options.compiledResultId,
2971
+ gameId: options.gameId
2972
+ });
2973
+ if (!canTrustGeneratedFingerprint) {
2974
+ validateGeneratedFingerprint({
2975
+ generated: generatedBase.fingerprint,
2976
+ current
2977
+ });
2978
+ }
2979
+ const currentHash = fingerprintHash(current);
2980
+ const cached = await readMaterializedScenarioCache({
2981
+ projectRoot: options.projectRoot,
2982
+ baseId: base.definition.id,
2983
+ scenarioId: scenario.definition.id,
2984
+ fingerprintHash: currentHash
2985
+ });
2986
+ if (cached) {
2987
+ return cached;
2988
+ }
2989
+ const [gameModule, manifestContractModule, modules] = await Promise.all([
2990
+ importTypeScriptModule(
2991
+ path3.join(options.projectRoot, "app", "game.ts")
2992
+ ),
2993
+ importTypeScriptModule(
2994
+ path3.join(options.projectRoot, "shared", "manifest-contract.ts")
2995
+ ),
2996
+ loadProjectReducerNativeModules(options.projectRoot)
2997
+ ]);
2998
+ const createInitialTable = typeof manifestContractModule.createInitialTable === "function" ? manifestContractModule.createInitialTable : null;
2999
+ const resolvedBase = resolveBaseDefinition(base, basesById);
3000
+ const effectiveSetup = resolveEffectiveBaseSetup({
3001
+ manifest,
3002
+ base: base.definition,
3003
+ basesById
3004
+ });
3005
+ const shadow = new ShadowReducerRuntime(
3006
+ modules,
3007
+ manifest,
3008
+ gameModule.default,
3009
+ createInitialTable,
3010
+ resolvedBase.seed,
3011
+ resolvedBase.players,
3012
+ effectiveSetup.setupProfileId,
3013
+ options.debug ?? false
3014
+ );
3015
+ shadow.hydrate(generatedBase.snapshot, generatedBase.version);
3016
+ const context = await createScenarioContext({
3017
+ shadow,
3018
+ expect: modules.createExpectApi()
3019
+ });
3020
+ shadow.clearHistory();
3021
+ await scenario.definition.when(context);
3022
+ if (scenario.definition.phase && shadow.phase() !== scenario.definition.phase) {
3023
+ throw new Error(
3024
+ `Scenario '${scenario.definition.id}' expected phase '${scenario.definition.phase}' but reached '${shadow.phase()}'.`
3025
+ );
3026
+ }
3027
+ if (scenario.definition.stage && shadow.currentStage() !== scenario.definition.stage) {
3028
+ throw new Error(
3029
+ `Scenario '${scenario.definition.id}' expected stage '${scenario.definition.stage}' but reached '${shadow.currentStage() ?? "null"}'.`
3030
+ );
3031
+ }
3032
+ const materialized = {
3033
+ baseId: base.definition.id,
3034
+ scenarioId: scenario.definition.id,
3035
+ seed: resolvedBase.seed,
3036
+ playerCount: resolvedBase.players,
3037
+ setupProfileId: effectiveSetup.setupProfileId,
3038
+ reducerState: shadow.rawState(),
3039
+ reducerStateVersion: shadow.currentVersion(),
3040
+ fingerprintMetadata: {
3041
+ baseFingerprintHash: fingerprintHash(generatedBase.fingerprint),
3042
+ currentFingerprintHash: fingerprintHash(current),
3043
+ baseBundleHash: generatedBase.fingerprint.baseBundleHash,
3044
+ manifestHash: generatedBase.fingerprint.manifestHash,
3045
+ appBundleHash: generatedBase.fingerprint.appBundleHash,
3046
+ uiContractHash: generatedBase.fingerprint.uiContractHash,
3047
+ baseId: base.definition.id,
3048
+ scenarioId: scenario.definition.id
3049
+ },
3050
+ phase: shadow.phase(),
3051
+ stage: shadow.currentStage()
3052
+ };
3053
+ await writeMaterializedScenarioCache({
3054
+ projectRoot: options.projectRoot,
3055
+ baseId: base.definition.id,
3056
+ scenarioId: scenario.definition.id,
3057
+ fingerprintHash: currentHash,
3058
+ materialized
3059
+ });
3060
+ return materialized;
3061
+ }
3062
+ async function fetchLiveActionSetVersion(sessionId, playerId) {
3063
+ const { data, error, response } = await getSessionSnapshot({
3064
+ path: { sessionId },
3065
+ query: { playerId }
3066
+ });
3067
+ if (error || !data || data.type !== "gameplay") {
3068
+ throw toDreamboardApiError(
3069
+ error ?? { detail: "Gameplay snapshot was unavailable." },
3070
+ response,
3071
+ "Failed to read live gameplay action set version"
3072
+ );
3073
+ }
3074
+ return data.gameplay.actionSetVersion;
3075
+ }
3076
+ function baseStateKey(baseId) {
3077
+ return baseId;
3078
+ }
3079
+ function fingerprintHash(fingerprint) {
3080
+ return hashContent(JSON.stringify(fingerprint));
3081
+ }
3082
+ function sortBasesForArtifacts(bases, basesById) {
3083
+ const ordered = [];
3084
+ const visiting = /* @__PURE__ */ new Set();
3085
+ const visited = /* @__PURE__ */ new Set();
3086
+ const visit = (base) => {
3087
+ if (visited.has(base.definition.id)) {
3088
+ return;
3089
+ }
3090
+ if (visiting.has(base.definition.id)) {
3091
+ throw new Error(
3092
+ `Cyclic reducer-native base inheritance detected at '${base.definition.id}'.`
3093
+ );
3094
+ }
3095
+ visiting.add(base.definition.id);
3096
+ if (base.definition.extends) {
3097
+ const parent = basesById.get(base.definition.extends);
3098
+ if (!parent) {
3099
+ throw new Error(
3100
+ `Base '${base.definition.id}' extends unknown parent '${base.definition.extends}'.`
3101
+ );
3102
+ }
3103
+ visit(parent);
3104
+ }
3105
+ visiting.delete(base.definition.id);
3106
+ visited.add(base.definition.id);
3107
+ ordered.push(base);
3108
+ };
3109
+ for (const base of bases) {
3110
+ visit(base);
3111
+ }
3112
+ return ordered;
3113
+ }
3114
+ function writeProjectionSnapshots(options) {
3115
+ const projectionDir = resolveWorkspacePath(
3116
+ options.projectRoot,
3117
+ `test/generated/bases/${sanitizeSnapshotSegment(options.baseId)}`
3118
+ );
3119
+ rmSync(projectionDir, { recursive: true, force: true });
3120
+ mkdirSync(projectionDir, { recursive: true });
3121
+ const projection = options.shadow.projectAllSeats();
3122
+ for (const [playerId, seatProjection] of Object.entries(projection.seats)) {
3123
+ const outputPath = resolveWorkspacePath(
3124
+ options.projectRoot,
3125
+ `test/generated/bases/${sanitizeSnapshotSegment(options.baseId)}/${sanitizeSnapshotSegment(playerId)}.projection.json`
3126
+ );
3127
+ writeFileSync(
3128
+ outputPath,
3129
+ `${JSON.stringify(
3130
+ {
3131
+ currentStage: projection.currentStage,
3132
+ stageSeats: projection.stageSeats,
3133
+ ...seatProjection
3134
+ },
3135
+ null,
3136
+ 2
3137
+ )}
3138
+ `,
3139
+ "utf8"
3140
+ );
3141
+ }
3142
+ }
3143
+ function validateTypedScenarioBases(scenarios, basesById) {
3144
+ const available = new Set(basesById.keys());
3145
+ const invalid = scenarios.filter((scenario) => !available.has(scenario.definition.from)).map(
3146
+ (scenario) => path3.relative(process.cwd(), scenario.filePath) + ` -> '${scenario.definition.from}'`
3147
+ );
3148
+ if (invalid.length > 0) {
3149
+ throw new Error(
3150
+ `Unknown scenario base(s): ${invalid.join(", ")}. Available bases: ${Array.from(available).sort().join(", ")}`
3151
+ );
3152
+ }
3153
+ }
3154
+ async function writeReducerNativeGeneratedFiles(options) {
3155
+ await ensureReducerNativeTestingFiles(options.projectRoot);
3156
+ const manifest = await loadManifest(options.projectRoot);
3157
+ const manifestHash = hashContent(JSON.stringify(manifest));
3158
+ const appBundleHash = hashContent(
3159
+ await bundleTypeScriptModuleText(
3160
+ path3.join(options.projectRoot, "app", "game.ts")
3161
+ )
3162
+ );
3163
+ const uiContractHash = hashContent(
3164
+ await bundleTypeScriptModuleText(
3165
+ path3.join(options.projectRoot, "shared", "generated", "ui-contract.ts"),
3166
+ { external: SDK_UI_RUNTIME_EXTERNALS }
3167
+ )
3168
+ );
3169
+ const generatedDir = resolveWorkspacePath(
3170
+ options.projectRoot,
3171
+ "test/generated"
3172
+ );
3173
+ await ensureDir(generatedDir);
3174
+ const baseStates = {};
3175
+ const [gameModule, manifestContractModule, modules] = await Promise.all([
3176
+ importTypeScriptModule(
3177
+ path3.join(options.projectRoot, "app", "game.ts")
3178
+ ),
3179
+ importTypeScriptModule(
3180
+ path3.join(options.projectRoot, "shared", "manifest-contract.ts")
3181
+ ),
3182
+ loadProjectReducerNativeModules(options.projectRoot)
3183
+ ]);
3184
+ const createInitialTable = typeof manifestContractModule.createInitialTable === "function" ? manifestContractModule.createInitialTable : null;
3185
+ const contractFingerprintValue = modules.contractFingerprint(
3186
+ gameModule.default
3187
+ ).value;
3188
+ const basesById = new Map(
3189
+ options.bases.map((base) => [base.definition.id, base])
3190
+ );
3191
+ for (const base of sortBasesForArtifacts(options.bases, basesById)) {
3192
+ const resolvedBase = resolveBaseDefinition(base, basesById);
3193
+ const effectiveSetup = resolveEffectiveBaseSetup({
3194
+ manifest,
3195
+ base: base.definition,
3196
+ basesById
3197
+ });
3198
+ const shadow = new ShadowReducerRuntime(
3199
+ modules,
3200
+ manifest,
3201
+ gameModule.default,
3202
+ createInitialTable,
3203
+ resolvedBase.seed,
3204
+ resolvedBase.players,
3205
+ effectiveSetup.setupProfileId,
3206
+ options.debug ?? false
3207
+ );
3208
+ let parentFingerprintHash = null;
3209
+ if (base.definition.extends) {
3210
+ const parentArtifact = baseStates[baseStateKey(base.definition.extends)];
3211
+ if (!parentArtifact) {
3212
+ throw new Error(
3213
+ `Base '${base.definition.id}' extends '${base.definition.extends}', but the parent artifact does not exist yet.`
3214
+ );
3215
+ }
3216
+ if (parentArtifact.fingerprint.seed !== resolvedBase.seed) {
3217
+ throw new Error(
3218
+ `Base '${base.definition.id}' extends '${base.definition.extends}' but changes seed from ${parentArtifact.fingerprint.seed} to ${resolvedBase.seed}.`
3219
+ );
3220
+ }
3221
+ if (parentArtifact.fingerprint.players !== resolvedBase.players) {
3222
+ throw new Error(
3223
+ `Base '${base.definition.id}' extends '${base.definition.extends}' but changes players from ${parentArtifact.fingerprint.players} to ${resolvedBase.players}.`
3224
+ );
3225
+ }
3226
+ if ((parentArtifact.fingerprint.setupProfileId ?? null) !== (effectiveSetup.setupProfileId ?? null)) {
3227
+ throw new Error(
3228
+ `Base '${base.definition.id}' extends '${base.definition.extends}' but changes setup profile from ${parentArtifact.fingerprint.setupProfileId ?? "none"} to ${effectiveSetup.setupProfileId ?? "none"}.`
3229
+ );
3230
+ }
3231
+ parentFingerprintHash = fingerprintHash(parentArtifact.fingerprint);
3232
+ shadow.hydrate(parentArtifact.snapshot, parentArtifact.version);
3233
+ }
3234
+ const context = await createScenarioContext({
3235
+ shadow,
3236
+ expect: modules.createExpectApi()
3237
+ });
3238
+ await context.game.start();
3239
+ try {
3240
+ await base.definition.setup({
3241
+ game: context.game,
3242
+ players: context.players,
3243
+ seat: context.seat
3244
+ });
3245
+ } catch (error) {
3246
+ const message = error instanceof Error ? error.message : String(error);
3247
+ throw new Error(
3248
+ `Base '${base.definition.id}' setup failed with setupProfileId '${effectiveSetup.setupProfileId ?? "none"}': ${message}`,
3249
+ { cause: error instanceof Error ? error : void 0 }
3250
+ );
3251
+ }
3252
+ baseStates[baseStateKey(base.definition.id)] = {
3253
+ key: baseStateKey(base.definition.id),
3254
+ base: base.definition.id,
3255
+ snapshot: shadow.rawState(),
3256
+ version: shadow.currentVersion(),
3257
+ fingerprint: {
3258
+ base: base.definition.id,
3259
+ seed: resolvedBase.seed,
3260
+ players: resolvedBase.players,
3261
+ baseBundleHash: base.bundleHash,
3262
+ manifestHash,
3263
+ appBundleHash,
3264
+ uiContractHash,
3265
+ setupProfileId: effectiveSetup.setupProfileId,
3266
+ compiledResultId: options.compiledResultId,
3267
+ gameId: options.gameId,
3268
+ parentBaseId: base.definition.extends ?? null,
3269
+ parentFingerprintHash,
3270
+ contractFingerprint: contractFingerprintValue
3271
+ }
3272
+ };
3273
+ writeProjectionSnapshots({
3274
+ projectRoot: options.projectRoot,
3275
+ baseId: base.definition.id,
3276
+ shadow
3277
+ });
3278
+ }
3279
+ const header = "// Generated by dreamboard test. Do not edit by hand.\n";
3280
+ await writeWorkspaceTextFile(
3281
+ options.projectRoot,
3282
+ "test/generated/base-states.generated.ts",
3283
+ `${header}export const BASE_STATES = ${JSON.stringify(baseStates, null, 2)} as const;
3284
+ export const BASE_STATES_CONTRACT_FINGERPRINT = ${JSON.stringify(contractFingerprintValue)};
3285
+ `
3286
+ );
3287
+ await writeWorkspaceTextFile(
3288
+ options.projectRoot,
3289
+ "test/generated/base-states.generated.d.ts",
3290
+ `${header}export declare const BASE_STATES: Record<string, unknown>;
3291
+ export declare const BASE_STATES_CONTRACT_FINGERPRINT: string | undefined;
3292
+ `
3293
+ );
3294
+ await writeWorkspaceTextFile(
3295
+ options.projectRoot,
3296
+ "test/generated/scenario-manifest.generated.ts",
3297
+ `${header}export const SCENARIO_MANIFEST = ${JSON.stringify(
3298
+ options.scenarios.map((scenario) => ({
3299
+ id: scenario.definition.id,
3300
+ filePath: path3.relative(generatedDir, scenario.filePath),
3301
+ base: scenario.definition.from
3302
+ })),
3303
+ null,
3304
+ 2
3305
+ )} as const;
3306
+ `
3307
+ );
3308
+ await writeWorkspaceJsonFile(
3309
+ options.projectRoot,
3310
+ "test/generated/.generation-meta.json",
3311
+ {
3312
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
3313
+ contractFingerprint: contractFingerprintValue,
3314
+ scenarioCount: options.scenarios.length,
3315
+ baseStateCount: options.bases.length
3316
+ }
3317
+ );
3318
+ }
3319
+ async function loadGeneratedBaseStates(projectRoot) {
3320
+ const filePath = path3.join(
3321
+ projectRoot,
3322
+ "test",
3323
+ "generated",
3324
+ "base-states.generated.ts"
3325
+ );
3326
+ if (!await exists(filePath)) {
3327
+ return null;
3328
+ }
3329
+ const module = await importTypeScriptModule(filePath);
3330
+ return module.BASE_STATES ?? null;
3331
+ }
3332
+ async function loadGeneratedScenarioManifest(projectRoot) {
3333
+ const filePath = path3.join(
3334
+ projectRoot,
3335
+ "test",
3336
+ "generated",
3337
+ "scenario-manifest.generated.ts"
3338
+ );
3339
+ if (!await exists(filePath)) {
3340
+ return [];
3341
+ }
3342
+ const module = await importTypeScriptModule(filePath);
3343
+ const entries = module.SCENARIO_MANIFEST;
3344
+ if (!Array.isArray(entries)) {
3345
+ return [];
3346
+ }
3347
+ return entries.flatMap((entry) => {
3348
+ if (entry && typeof entry === "object" && "id" in entry && "base" in entry && typeof entry.id === "string" && typeof entry.base === "string") {
3349
+ return [{ id: entry.id, base: entry.base }];
3350
+ }
3351
+ return [];
3352
+ });
3353
+ }
3354
+ function validateGeneratedFingerprint(options) {
3355
+ const mismatches = [];
3356
+ if (options.generated.contractFingerprint && options.current.contractFingerprint && options.generated.contractFingerprint !== options.current.contractFingerprint) {
3357
+ const error = new Error(
3358
+ `Base states were generated for contract ${options.generated.contractFingerprint} but the current contract is ${options.current.contractFingerprint}. Remedy: run \`dreamboard test\`, then re-run the tests.`
3359
+ );
3360
+ error.code = STALE_CONTRACT_ARTIFACT_CODE;
3361
+ throw error;
3362
+ }
3363
+ if (options.generated.baseBundleHash !== options.current.baseBundleHash) {
3364
+ mismatches.push("base module changed");
3365
+ }
3366
+ if (options.generated.manifestHash !== options.current.manifestHash) {
3367
+ mismatches.push("manifest changed");
3368
+ }
3369
+ if (options.generated.appBundleHash !== options.current.appBundleHash) {
3370
+ mismatches.push("game reducer bundle changed");
3371
+ }
3372
+ if (options.generated.uiContractHash !== options.current.uiContractHash) {
3373
+ mismatches.push("ui contract changed");
3374
+ }
3375
+ if (options.generated.seed !== options.current.seed || options.generated.players !== options.current.players) {
3376
+ mismatches.push("base seed/player count changed");
3377
+ }
3378
+ if ((options.generated.setupProfileId ?? null) !== (options.current.setupProfileId ?? null)) {
3379
+ mismatches.push("base setup profile changed");
3380
+ }
3381
+ if ((options.generated.parentBaseId ?? null) !== (options.current.parentBaseId ?? null)) {
3382
+ mismatches.push("base parent changed");
3383
+ }
3384
+ if ((options.generated.parentFingerprintHash ?? null) !== (options.current.parentFingerprintHash ?? null)) {
3385
+ mismatches.push("parent base artifact changed");
3386
+ }
3387
+ if (mismatches.length > 0) {
3388
+ throw new Error(
3389
+ `${mismatches.join("; ")}. Run 'dreamboard test' to refresh reducer-native base artifacts.`
3390
+ );
3391
+ }
3392
+ }
3393
+ async function currentFingerprint(options) {
3394
+ const manifest = await loadManifest(options.projectRoot);
3395
+ const [gameModule, modules] = await Promise.all([
3396
+ importTypeScriptModule(
3397
+ path3.join(options.projectRoot, "app", "game.ts")
3398
+ ),
3399
+ loadProjectReducerNativeModules(options.projectRoot)
3400
+ ]);
3401
+ const contractFingerprintValue = modules.contractFingerprint(
3402
+ gameModule.default
3403
+ ).value;
3404
+ const resolvedBase = resolveBaseDefinition(
3405
+ options.base,
3406
+ options.basesById ?? /* @__PURE__ */ new Map([[options.base.definition.id, options.base]])
3407
+ );
3408
+ const effectiveSetup = resolveEffectiveBaseSetup({
3409
+ manifest,
3410
+ base: options.base.definition,
3411
+ basesById: options.basesById
3412
+ });
3413
+ let parentFingerprintHash = null;
3414
+ if (options.base.definition.extends) {
3415
+ const parentBase = options.basesById?.get(options.base.definition.extends);
3416
+ if (!parentBase) {
3417
+ throw new Error(
3418
+ `Base '${options.base.definition.id}' extends unknown parent '${options.base.definition.extends}'.`
3419
+ );
3420
+ }
3421
+ parentFingerprintHash = fingerprintHash(
3422
+ await currentFingerprint({
3423
+ projectRoot: options.projectRoot,
3424
+ base: parentBase,
3425
+ basesById: options.basesById,
3426
+ compiledResultId: options.compiledResultId,
3427
+ gameId: options.gameId
3428
+ })
3429
+ );
3430
+ }
3431
+ return {
3432
+ base: options.base.definition.id,
3433
+ seed: resolvedBase.seed,
3434
+ players: resolvedBase.players,
3435
+ baseBundleHash: options.base.bundleHash,
3436
+ manifestHash: hashContent(JSON.stringify(manifest)),
3437
+ appBundleHash: hashContent(
3438
+ await bundleTypeScriptModuleText(
3439
+ path3.join(options.projectRoot, "app", "game.ts")
3440
+ )
3441
+ ),
3442
+ uiContractHash: hashContent(
3443
+ await bundleTypeScriptModuleText(
3444
+ path3.join(options.projectRoot, "shared", "generated", "ui-contract.ts"),
3445
+ { external: SDK_UI_RUNTIME_EXTERNALS }
3446
+ )
3447
+ ),
3448
+ setupProfileId: effectiveSetup.setupProfileId,
3449
+ compiledResultId: options.compiledResultId,
3450
+ gameId: options.gameId,
3451
+ parentBaseId: options.base.definition.extends ?? null,
3452
+ parentFingerprintHash,
3453
+ contractFingerprint: contractFingerprintValue
3454
+ };
3455
+ }
3456
+ async function generateReducerNativeArtifacts(options) {
3457
+ await ensureReducerNativeTestingFiles(options.projectRoot);
3458
+ const [bases, scenarios] = await Promise.all([
3459
+ loadTypedBases(options.projectRoot),
3460
+ loadTypedScenarios(options.projectRoot, {
3461
+ scenarioPath: options.scenarioPath
3462
+ })
3463
+ ]);
3464
+ const basesById = new Map(bases.map((base) => [base.definition.id, base]));
3465
+ validateTypedScenarioBases(scenarios, basesById);
3466
+ await writeReducerNativeGeneratedFiles({
3467
+ projectRoot: options.projectRoot,
3468
+ bases,
3469
+ scenarios,
3470
+ compiledResultId: options.compiledResultId,
3471
+ gameId: options.gameId,
3472
+ debug: options.debug
3473
+ });
3474
+ return { bases, scenarios };
3475
+ }
3476
+ async function runReducerNativeScenarios(options) {
3477
+ await ensureReducerNativeTestingFiles(options.projectRoot);
3478
+ const [
3479
+ bases,
3480
+ scenarios,
3481
+ initialGeneratedBaseStates,
3482
+ manifest,
3483
+ gameModule,
3484
+ manifestContractModule,
3485
+ modules
3486
+ ] = await Promise.all([
3487
+ loadTypedBases(options.projectRoot),
3488
+ loadTypedScenarios(options.projectRoot, {
3489
+ scenarioPath: options.scenarioPath
3490
+ }),
3491
+ loadGeneratedBaseStates(options.projectRoot),
3492
+ loadManifest(options.projectRoot),
3493
+ importTypeScriptModule(
3494
+ path3.join(options.projectRoot, "app", "game.ts")
3495
+ ),
3496
+ importTypeScriptModule(
3497
+ path3.join(options.projectRoot, "shared", "manifest-contract.ts")
3498
+ ),
3499
+ loadProjectReducerNativeModules(options.projectRoot)
3500
+ ]);
3501
+ let generatedBaseStates = initialGeneratedBaseStates;
3502
+ const createInitialTable = typeof manifestContractModule.createInitialTable === "function" ? manifestContractModule.createInitialTable : null;
3503
+ const basesById = new Map(bases.map((base) => [base.definition.id, base]));
3504
+ validateTypedScenarioBases(scenarios, basesById);
3505
+ if (options.updateSnapshots) {
3506
+ await writeReducerNativeGeneratedFiles({
3507
+ projectRoot: options.projectRoot,
3508
+ bases,
3509
+ scenarios,
3510
+ compiledResultId: options.compiledResultId,
3511
+ gameId: options.gameId,
3512
+ debug: options.debug
3513
+ });
3514
+ generatedBaseStates = await loadGeneratedBaseStates(options.projectRoot);
3515
+ }
3516
+ let passed = 0;
3517
+ let failed = 0;
3518
+ const results = [];
3519
+ for (const scenario of scenarios) {
3520
+ const base = basesById.get(scenario.definition.from);
3521
+ if (!base) {
3522
+ throw new Error(
3523
+ `Missing typed base '${scenario.definition.from}' for scenario '${scenario.definition.id}'.`
3524
+ );
3525
+ }
3526
+ if (generatedBaseStates?.[baseStateKey(base.definition.id)]) {
3527
+ validateGeneratedFingerprint({
3528
+ generated: generatedBaseStates[baseStateKey(base.definition.id)].fingerprint,
3529
+ current: await currentFingerprint({
3530
+ projectRoot: options.projectRoot,
3531
+ base,
3532
+ basesById,
3533
+ compiledResultId: options.compiledResultId,
3534
+ gameId: options.gameId
3535
+ })
3536
+ });
3537
+ }
3538
+ try {
3539
+ const resolvedBase = resolveBaseDefinition(base, basesById);
3540
+ const effectiveSetup = resolveEffectiveBaseSetup({
3541
+ manifest,
3542
+ base: base.definition,
3543
+ basesById
3544
+ });
3545
+ const shadow = new ShadowReducerRuntime(
3546
+ modules,
3547
+ manifest,
3548
+ gameModule.default,
3549
+ createInitialTable,
3550
+ resolvedBase.seed,
3551
+ resolvedBase.players,
3552
+ effectiveSetup.setupProfileId,
3553
+ options.debug ?? false
3554
+ );
3555
+ if (base.definition.extends) {
3556
+ const parentArtifact = generatedBaseStates?.[baseStateKey(base.definition.extends)];
3557
+ if (!parentArtifact) {
3558
+ throw new Error(
3559
+ `Base '${base.definition.id}' extends '${base.definition.extends}', but the parent artifact is missing. Run 'dreamboard test' first.`
3560
+ );
3561
+ }
3562
+ shadow.hydrate(parentArtifact.snapshot, parentArtifact.version);
3563
+ }
3564
+ const context = await createScenarioContext({
3565
+ shadow,
3566
+ expect: modules.createExpectApi({
3567
+ matchSnapshot: createScenarioSnapshotMatcher({
3568
+ projectRoot: options.projectRoot,
3569
+ scenarioId: scenario.definition.id,
3570
+ updateSnapshots: options.updateSnapshots ?? false
3571
+ })
3572
+ })
3573
+ });
3574
+ await context.game.start();
3575
+ await base.definition.setup({
3576
+ game: context.game,
3577
+ players: context.players,
3578
+ seat: context.seat
3579
+ });
3580
+ shadow.clearHistory();
3581
+ await scenario.definition.when(context);
3582
+ if (scenario.definition.phase && shadow.phase() !== scenario.definition.phase) {
3583
+ throw new Error(
3584
+ `Scenario '${scenario.definition.id}' expected phase '${scenario.definition.phase}' but reached '${shadow.phase()}'.`
3585
+ );
3586
+ }
3587
+ if (scenario.definition.stage && shadow.currentStage() !== scenario.definition.stage) {
3588
+ throw new Error(
3589
+ `Scenario '${scenario.definition.id}' expected stage '${scenario.definition.stage}' but reached '${shadow.currentStage() ?? "null"}'.`
3590
+ );
3591
+ }
3592
+ await scenario.definition.then(context);
3593
+ passed += 1;
3594
+ results.push({
3595
+ id: scenario.definition.id,
3596
+ success: true
3597
+ });
3598
+ } catch (error) {
3599
+ failed += 1;
3600
+ results.push({
3601
+ id: scenario.definition.id,
3602
+ success: false,
3603
+ errorCode: isStaleContractArtifactError(error) ? STALE_CONTRACT_ARTIFACT_CODE : void 0,
3604
+ error: error instanceof Error ? formatScenarioErrorForDisplay({
3605
+ error,
3606
+ projectRoot: options.projectRoot,
3607
+ scenarioFilePath: scenario.filePath
3608
+ }) : `Scenario '${scenario.definition.id}' failed.`
3609
+ });
3610
+ } finally {
3611
+ }
3612
+ }
3613
+ return { passed, failed, results };
3614
+ }
3615
+
3616
+ // src/services/project/local-maintainer-registry-shared.ts
3617
+ import crypto2 from "crypto";
3618
+ import path4 from "path";
3619
+ var localRegistryAddress = readLocalRegistryAddress();
3620
+ var LOCAL_REGISTRY_HOST = localRegistryAddress.host;
3621
+ var LOCAL_REGISTRY_PORT = localRegistryAddress.port;
3622
+ var LOCAL_REGISTRY_URL = `http://${LOCAL_REGISTRY_HOST}:${LOCAL_REGISTRY_PORT}`;
3623
+ var LOCAL_SCOPE_NPMRC_CONTENT = `@dreamboard-games:registry=${LOCAL_REGISTRY_URL}
3624
+ `;
3625
+ function readLocalRegistryAddress() {
3626
+ const urlOverride = process.env.DREAMBOARD_LOCAL_REGISTRY_URL?.trim();
3627
+ const hostOverride = process.env.DREAMBOARD_LOCAL_REGISTRY_HOST?.trim();
3628
+ const portOverride = process.env.DREAMBOARD_LOCAL_REGISTRY_PORT?.trim();
3629
+ if (urlOverride) {
3630
+ let parsed;
3631
+ try {
3632
+ parsed = new URL(urlOverride);
3633
+ } catch {
3634
+ throw new Error(
3635
+ `Invalid DREAMBOARD_LOCAL_REGISTRY_URL '${urlOverride}'. Expected an http://host:port URL.`
3636
+ );
3637
+ }
3638
+ if (parsed.protocol !== "http:" || !parsed.hostname || !parsed.port) {
3639
+ throw new Error(
3640
+ `Invalid DREAMBOARD_LOCAL_REGISTRY_URL '${urlOverride}'. Expected an http://host:port URL.`
3641
+ );
3642
+ }
3643
+ return {
3644
+ host: hostOverride || parsed.hostname,
3645
+ port: parseLocalRegistryPort(portOverride || parsed.port)
3646
+ };
3647
+ }
3648
+ return {
3649
+ host: hostOverride || "127.0.0.1",
3650
+ port: portOverride ? parseLocalRegistryPort(portOverride) : 4873
3651
+ };
3652
+ }
3653
+ function parseLocalRegistryPort(raw) {
3654
+ const port = Number.parseInt(raw, 10);
3655
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
3656
+ throw new Error(
3657
+ `Invalid DREAMBOARD_LOCAL_REGISTRY_PORT '${raw}'. Expected a TCP port from 1 to 65535.`
3658
+ );
3659
+ }
3660
+ return port;
3661
+ }
3662
+ function shortHash(value) {
3663
+ return crypto2.createHash("sha256").update(value).digest("hex").slice(0, 12);
3664
+ }
3665
+ function isLocalMaintainerRegistryEnabled(apiBaseUrl) {
3666
+ let isLocalLoopbackUrl = false;
3667
+ try {
3668
+ const parsed = new URL(apiBaseUrl);
3669
+ isLocalLoopbackUrl = parsed.protocol === "http:" && (parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1");
3670
+ } catch {
3671
+ isLocalLoopbackUrl = false;
3672
+ }
3673
+ return !IS_PUBLISHED_BUILD && (apiBaseUrl === ENVIRONMENT_CONFIGS.local?.apiBaseUrl || isLocalLoopbackUrl) && BUILD_CHANNEL === "development";
3674
+ }
3675
+ function didLocalMaintainerSnapshotChange(previous, next) {
3676
+ if (!next) {
3677
+ return false;
3678
+ }
3679
+ return previous?.snapshotId !== next.snapshotId;
3680
+ }
3681
+
3682
+ export {
3683
+ createPkcePair,
3684
+ buildClerkAuthorizationUrl,
3685
+ exchangeClerkOAuthCode,
3686
+ exchangeDreamboardUserToken,
3687
+ IS_PUBLISHED_BUILD,
3688
+ PUBLISHED_ENVIRONMENT,
3689
+ createUserTokenManager,
3690
+ resolveLocalHarnessAccessToken,
3691
+ resolveConfig,
3692
+ configureClient,
3693
+ refreshResolvedAuthSession,
3694
+ requireAuth,
3695
+ getAuthTokenExpiry,
3696
+ resolveProjectContext,
3697
+ parseConfigFlags,
3698
+ parsePlayerCountFlags,
3699
+ parseNewCommandArgs,
3700
+ parseCloneCommandArgs,
3701
+ parseCommitScopedCommandArgs,
3702
+ parseProjectRepositoryCommandArgs,
3703
+ parseBuildCommandArgs,
3704
+ parseReleasePublishCommandArgs,
3705
+ parseDevCommandArgs,
3706
+ parseAuthCommandArgs,
3707
+ CONFIG_FLAG_ARGS,
3708
+ STALE_CONTRACT_ARTIFACT_CODE,
3709
+ STALE_CONTRACT_ARTIFACT_EXIT_CODE,
3710
+ toDreamboardApiError,
3711
+ isDreamboardApiError,
3712
+ isStaleContractArtifactMessage,
3713
+ isStaleContractArtifactError,
3714
+ getCliErrorExitCode,
3715
+ presentCliError,
3716
+ formatCliError,
3717
+ normalizeSlug,
3718
+ titleFromSlug,
3719
+ parsePositiveInt,
3720
+ findCompiledResultsForAuthoringState,
3721
+ waitForCompiledResultJobSdk,
3722
+ importTypeScriptModule,
3723
+ resolveSetupProfileSelectionForSession,
3724
+ projectIdFromSessionGameSource,
3725
+ isReducerNativeTestingWorkspace,
3726
+ ensureReducerNativeTestingFiles,
3727
+ createSessionFromScenario,
3728
+ generateReducerNativeArtifacts,
3729
+ runReducerNativeScenarios,
3730
+ LOCAL_REGISTRY_URL,
3731
+ shortHash,
3732
+ isLocalMaintainerRegistryEnabled,
3733
+ didLocalMaintainerSnapshotChange
3734
+ };
3735
+ //# sourceMappingURL=chunk-RTNKVNQA.js.map