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