@dreamboard-games/cli 0.1.30-alpha.2 → 0.1.30-alpha.21

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