@mushi-mushi/cli 0.38.0 → 0.40.0
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/dist/{chunk-AIZRI665.js → chunk-AWASJDQI.js} +62 -33
- package/dist/{chunk-KOBEOGNF.js → chunk-CG5KPP4S.js} +62 -33
- package/dist/chunk-CNJIN4ST.js +10 -0
- package/dist/{chunk-QZMSGTVZ.js → chunk-ETFORW35.js} +1 -1
- package/dist/chunk-FA5LABKE.js +2279 -0
- package/dist/chunk-JWG2QI3W.js +8 -0
- package/dist/{chunk-JXAH3XKH.js → chunk-PGLH5XP2.js} +3 -3
- package/dist/chunk-TNTSV54C.js +160 -0
- package/dist/{chunk-V3DR4WLG.js → chunk-UV4DMSQH.js} +1 -1
- package/dist/{chunk-BUCMB4NS.js → chunk-WXICRZIU.js} +4 -4
- package/dist/{connect-M2IGP63E.js → connect-BSMHOKUQ.js} +4 -4
- package/dist/{connect-OTHJSNHC.js → connect-NKWXYGN7.js} +4 -4
- package/dist/{daemon-VYXTQ5TG.js → daemon-6SCU35YF.js} +3 -3
- package/dist/{detect-WZT5X6LP.js → detect-SOXPECZ3.js} +5 -1
- package/dist/detect.d.ts +17 -1
- package/dist/detect.js +5 -1
- package/dist/index.js +130 -62
- package/dist/init.js +11 -2264
- package/dist/{snippet-inject-NDAPEL2T.js → snippet-inject-AVGVHTUJ.js} +3 -2
- package/dist/{snippet-inject-LPRWTQDE.js → snippet-inject-ETGBPDYB.js} +3 -2
- package/dist/{version-ULUVAZ3V.js → version-SLVFYTAI.js} +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/wizard-args.d.ts +35 -1
- package/dist/wizard-args.js +14 -95
- package/dist/wizard-bin.d.ts +32 -0
- package/dist/wizard-bin.js +106 -0
- package/package.json +8 -1
- package/templates/node/.env.example +4 -0
- package/templates/node/README.md +12 -0
- package/templates/node/gitignore +6 -0
- package/templates/node/package.json +15 -0
- package/templates/node/src/server.mjs +38 -0
- package/templates/svelte/.env.example +4 -0
- package/templates/svelte/README.md +10 -0
- package/templates/svelte/gitignore +6 -0
- package/templates/svelte/index.html +12 -0
- package/templates/svelte/package.json +20 -0
- package/templates/svelte/src/App.svelte +20 -0
- package/templates/svelte/src/main.ts +12 -0
- package/templates/svelte/vite.config.ts +6 -0
- package/templates/vue/.env.example +4 -0
- package/templates/vue/README.md +10 -0
- package/templates/vue/gitignore +6 -0
- package/templates/vue/index.html +12 -0
- package/templates/vue/package.json +20 -0
- package/templates/vue/src/App.vue +22 -0
- package/templates/vue/src/main.ts +12 -0
- package/templates/vue/vite.config.ts +6 -0
- package/dist/chunk-DJNAPA4D.js +0 -10
- package/dist/chunk-M5LN4ZWQ.js +0 -8
|
@@ -0,0 +1,2279 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CLI_KEY_LABEL,
|
|
3
|
+
CLI_KEY_SCOPES,
|
|
4
|
+
SDK_KEY_LABEL,
|
|
5
|
+
SDK_KEY_SCOPES,
|
|
6
|
+
apiCall,
|
|
7
|
+
apiKeyHeaders,
|
|
8
|
+
apiKeyHint,
|
|
9
|
+
cliSetupDeepLink,
|
|
10
|
+
consoleUrl,
|
|
11
|
+
describeUnsafeSdkKey,
|
|
12
|
+
ensureClientId,
|
|
13
|
+
fetchIngestSetup,
|
|
14
|
+
loadConfig,
|
|
15
|
+
maybeShowTelemetryNotice,
|
|
16
|
+
openInBrowser,
|
|
17
|
+
probeKeyScope,
|
|
18
|
+
projectIdHint,
|
|
19
|
+
reportsUrl,
|
|
20
|
+
resolveConsoleUrl,
|
|
21
|
+
resolveConsoleUrlSync,
|
|
22
|
+
resolveProfileName,
|
|
23
|
+
sanitizeCliCredentials,
|
|
24
|
+
sanitizeEndpoint,
|
|
25
|
+
saveConfig,
|
|
26
|
+
savedSdkKeyFor,
|
|
27
|
+
trySaveKeyToKeychain
|
|
28
|
+
} from "./chunk-UV4DMSQH.js";
|
|
29
|
+
import {
|
|
30
|
+
MUSHI_CLI_VERSION
|
|
31
|
+
} from "./chunk-JWG2QI3W.js";
|
|
32
|
+
import {
|
|
33
|
+
FRAMEWORKS,
|
|
34
|
+
detectFramework,
|
|
35
|
+
detectPackageManager,
|
|
36
|
+
envVarsToWrite,
|
|
37
|
+
installCommand,
|
|
38
|
+
isLauncherOnly,
|
|
39
|
+
isMushiSdkPackage,
|
|
40
|
+
readPackageJson
|
|
41
|
+
} from "./chunk-AWASJDQI.js";
|
|
42
|
+
import {
|
|
43
|
+
CLOUD_API_ENDPOINT,
|
|
44
|
+
CLOUD_MCP_OAUTH_URL,
|
|
45
|
+
TEST_REPORT_FETCH_TIMEOUT_MS,
|
|
46
|
+
firstEndpoint,
|
|
47
|
+
normalizeEndpoint,
|
|
48
|
+
resolveCloudEndpoint
|
|
49
|
+
} from "./chunk-2DMHQVRU.js";
|
|
50
|
+
|
|
51
|
+
// src/init.ts
|
|
52
|
+
import * as p from "@clack/prompts";
|
|
53
|
+
import { spawn } from "child_process";
|
|
54
|
+
import { randomUUID } from "crypto";
|
|
55
|
+
import { appendFileSync, existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync } from "fs";
|
|
56
|
+
import { join as join2 } from "path";
|
|
57
|
+
|
|
58
|
+
// src/hosting-env-hint.ts
|
|
59
|
+
var LOVABLE_BOLT_DOCS = "https://kensaur.us/mushi-mushi/docs/quickstart/lovable-bolt";
|
|
60
|
+
function envVarNames(block) {
|
|
61
|
+
return block.split("\n").map((line) => /^([A-Z_][A-Z0-9_]*)=/.exec(line.trim())?.[1]).filter((name) => Boolean(name));
|
|
62
|
+
}
|
|
63
|
+
function hostingEnvHint(envBlock, envFile) {
|
|
64
|
+
const names = envVarNames(envBlock);
|
|
65
|
+
const first = names[0] ?? "MUSHI_PROJECT_ID";
|
|
66
|
+
const last = names[names.length - 1] ?? first;
|
|
67
|
+
return [
|
|
68
|
+
`Your deployed site needs these too. The values are in ${envFile}; copy them from there:`,
|
|
69
|
+
...names.map((n) => ` ${n}`),
|
|
70
|
+
"",
|
|
71
|
+
`Vercel: Project \u2192 Settings \u2192 Environment Variables, or \`vercel env add ${first} production\` (it asks for the value).`,
|
|
72
|
+
`Netlify: Project configuration \u2192 Environment variables, or \`netlify env:set ${last} "<value>"\`.`,
|
|
73
|
+
"Then redeploy: a NEXT_PUBLIC_ / VITE_ variable only reaches the site on the next build.",
|
|
74
|
+
`Lovable or Bolt: no variables needed; paste the script tag instead: ${LOVABLE_BOLT_DOCS}`
|
|
75
|
+
].join("\n");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// src/device-auth.ts
|
|
79
|
+
var DEVICE_FETCH_TIMEOUT_MS = 15e3;
|
|
80
|
+
var DEFAULT_SLOW_DOWN_MS = 5e3;
|
|
81
|
+
function trimTrailingSlash(endpoint) {
|
|
82
|
+
let end = endpoint.length;
|
|
83
|
+
while (end > 0 && endpoint.charCodeAt(end - 1) === 47) end--;
|
|
84
|
+
return endpoint.slice(0, end);
|
|
85
|
+
}
|
|
86
|
+
async function deviceFetch(url, init = {}) {
|
|
87
|
+
const controller = new AbortController();
|
|
88
|
+
const timer = setTimeout(() => controller.abort(), DEVICE_FETCH_TIMEOUT_MS);
|
|
89
|
+
try {
|
|
90
|
+
return await fetch(url, { ...init, signal: controller.signal });
|
|
91
|
+
} finally {
|
|
92
|
+
clearTimeout(timer);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
async function startDeviceAuth(endpoint, clientId) {
|
|
96
|
+
const base = trimTrailingSlash(endpoint);
|
|
97
|
+
const res = await deviceFetch(`${base}/v1/cli/auth/device/start`, {
|
|
98
|
+
method: "POST",
|
|
99
|
+
headers: { "Content-Type": "application/json" },
|
|
100
|
+
body: JSON.stringify(clientId ? { client_id: clientId } : {})
|
|
101
|
+
});
|
|
102
|
+
const json = await res.json().catch(() => null);
|
|
103
|
+
if (!res.ok || !json?.ok || !json.data) {
|
|
104
|
+
throw new Error(
|
|
105
|
+
json?.error?.message ?? `Could not start browser sign-in (HTTP ${res.status}).`
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
return json.data;
|
|
109
|
+
}
|
|
110
|
+
async function pollDeviceToken(endpoint, deviceCode) {
|
|
111
|
+
const base = trimTrailingSlash(endpoint);
|
|
112
|
+
try {
|
|
113
|
+
const res = await deviceFetch(`${base}/v1/cli/auth/device/token`, {
|
|
114
|
+
method: "POST",
|
|
115
|
+
headers: { "Content-Type": "application/json" },
|
|
116
|
+
body: JSON.stringify({ device_code: deviceCode })
|
|
117
|
+
});
|
|
118
|
+
const json = await res.json().catch(() => ({}));
|
|
119
|
+
if (res.ok && json.ok && json.data?.cli_token) {
|
|
120
|
+
return { status: "approved", cliToken: json.data.cli_token, userId: json.data.user_id };
|
|
121
|
+
}
|
|
122
|
+
switch (json.error) {
|
|
123
|
+
case "authorization_pending":
|
|
124
|
+
return { status: "pending" };
|
|
125
|
+
case "slow_down": {
|
|
126
|
+
const retryAfterHeader = res.headers?.get?.("Retry-After");
|
|
127
|
+
const retryAfterSeconds = retryAfterHeader ? Number(retryAfterHeader) : NaN;
|
|
128
|
+
const retryAfterMs = Number.isFinite(retryAfterSeconds) && retryAfterSeconds > 0 ? retryAfterSeconds * 1e3 : DEFAULT_SLOW_DOWN_MS;
|
|
129
|
+
return { status: "slow_down", retryAfterMs };
|
|
130
|
+
}
|
|
131
|
+
case "access_denied":
|
|
132
|
+
return { status: "denied" };
|
|
133
|
+
case "expired_token":
|
|
134
|
+
return { status: "expired" };
|
|
135
|
+
default:
|
|
136
|
+
return {
|
|
137
|
+
status: "error",
|
|
138
|
+
message: json.error_description ?? json.error ?? `HTTP ${res.status}`,
|
|
139
|
+
// 5xx is a server hiccup the next poll may clear; 408 (gateway
|
|
140
|
+
// timeout) is equally transient. Any other 4xx is a definitive
|
|
141
|
+
// rejection (already claimed / invalid_grant) that won't fix
|
|
142
|
+
// itself. (429/slow_down is handled above as its own outcome.)
|
|
143
|
+
retryable: res.status >= 500 || res.status === 408
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
} catch (err) {
|
|
147
|
+
return {
|
|
148
|
+
status: "error",
|
|
149
|
+
message: err instanceof Error ? err.message : String(err),
|
|
150
|
+
retryable: true
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
var defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
155
|
+
var deviceAuthRetryDelayMs = 1e3;
|
|
156
|
+
async function waitForCliToken(endpoint, session, opts = {}) {
|
|
157
|
+
const sleep = opts.sleep ?? defaultSleep;
|
|
158
|
+
const now = opts.now ?? Date.now;
|
|
159
|
+
let intervalMs = (session.interval || 5) * 1e3;
|
|
160
|
+
const deadline = now() + (session.expires_in || 600) * 1e3;
|
|
161
|
+
const maxConsecutiveErrors = opts.maxConsecutiveErrors ?? 5;
|
|
162
|
+
let consecutiveErrors = 0;
|
|
163
|
+
let firstPoll = true;
|
|
164
|
+
while (now() < deadline) {
|
|
165
|
+
if (!firstPoll) {
|
|
166
|
+
await sleep(intervalMs);
|
|
167
|
+
}
|
|
168
|
+
firstPoll = false;
|
|
169
|
+
const outcome = await pollDeviceToken(endpoint, session.device_code);
|
|
170
|
+
switch (outcome.status) {
|
|
171
|
+
case "approved":
|
|
172
|
+
return outcome.cliToken;
|
|
173
|
+
case "pending":
|
|
174
|
+
consecutiveErrors = 0;
|
|
175
|
+
opts.onPending?.();
|
|
176
|
+
continue;
|
|
177
|
+
case "slow_down":
|
|
178
|
+
consecutiveErrors = 0;
|
|
179
|
+
intervalMs = Math.max(intervalMs, outcome.retryAfterMs);
|
|
180
|
+
opts.onSlowDown?.(outcome.retryAfterMs);
|
|
181
|
+
continue;
|
|
182
|
+
case "denied":
|
|
183
|
+
throw new Error("Login was denied in the browser.");
|
|
184
|
+
case "expired":
|
|
185
|
+
throw new Error("The login code expired. Run sign-in again.");
|
|
186
|
+
case "error":
|
|
187
|
+
if (!outcome.retryable) {
|
|
188
|
+
throw new Error(outcome.message);
|
|
189
|
+
}
|
|
190
|
+
consecutiveErrors += 1;
|
|
191
|
+
if (consecutiveErrors >= maxConsecutiveErrors) {
|
|
192
|
+
throw new Error(outcome.message);
|
|
193
|
+
}
|
|
194
|
+
opts.onTransientError?.(outcome.message, consecutiveErrors);
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
throw new Error("Login timed out before approval. Run sign-in again.");
|
|
199
|
+
}
|
|
200
|
+
function cliAuthHeaders(cliToken) {
|
|
201
|
+
return {
|
|
202
|
+
"Content-Type": "application/json",
|
|
203
|
+
Authorization: `Bearer ${cliToken}`
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
var DeviceAuthRequestError = class extends Error {
|
|
207
|
+
step;
|
|
208
|
+
status;
|
|
209
|
+
retryable;
|
|
210
|
+
constructor(step, message, status) {
|
|
211
|
+
super(message);
|
|
212
|
+
this.name = "DeviceAuthRequestError";
|
|
213
|
+
this.step = step;
|
|
214
|
+
this.status = status;
|
|
215
|
+
this.retryable = status === void 0 || status >= 500 || status === 408;
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
async function withOneRetry(run) {
|
|
219
|
+
try {
|
|
220
|
+
return await run();
|
|
221
|
+
} catch (err) {
|
|
222
|
+
if (err instanceof DeviceAuthRequestError && err.retryable) {
|
|
223
|
+
if (deviceAuthRetryDelayMs > 0) {
|
|
224
|
+
await defaultSleep(deviceAuthRetryDelayMs);
|
|
225
|
+
}
|
|
226
|
+
return run();
|
|
227
|
+
}
|
|
228
|
+
throw err;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
async function listProjects(endpoint, cliToken) {
|
|
232
|
+
const base = trimTrailingSlash(endpoint);
|
|
233
|
+
return withOneRetry(async () => {
|
|
234
|
+
let res;
|
|
235
|
+
try {
|
|
236
|
+
res = await deviceFetch(`${base}/v1/cli/projects`, { headers: cliAuthHeaders(cliToken) });
|
|
237
|
+
} catch (err) {
|
|
238
|
+
throw new DeviceAuthRequestError(
|
|
239
|
+
"list_projects",
|
|
240
|
+
`Could not reach ${base}/v1/cli/projects: ${err instanceof Error ? err.message : String(err)}`
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
const json = await res.json().catch(() => null);
|
|
244
|
+
if (res.ok && json?.ok) return json.data?.projects ?? [];
|
|
245
|
+
throw new DeviceAuthRequestError(
|
|
246
|
+
"list_projects",
|
|
247
|
+
json?.error?.message ?? `Could not list projects (HTTP ${res.status}).`,
|
|
248
|
+
res.status
|
|
249
|
+
);
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
async function createProject(endpoint, cliToken, name, opts = {}) {
|
|
253
|
+
const base = trimTrailingSlash(endpoint);
|
|
254
|
+
const res = await deviceFetch(`${base}/v1/cli/projects`, {
|
|
255
|
+
method: "POST",
|
|
256
|
+
headers: cliAuthHeaders(cliToken),
|
|
257
|
+
body: JSON.stringify({ name, ...opts.scopes ? { scopes: opts.scopes } : {} })
|
|
258
|
+
});
|
|
259
|
+
const json = await res.json().catch(() => null);
|
|
260
|
+
if (!res.ok || !json?.ok || !json.data) {
|
|
261
|
+
throw new Error(json?.error?.message ?? `Could not create project (HTTP ${res.status}).`);
|
|
262
|
+
}
|
|
263
|
+
const { id, name: created, slug, apiKey } = json.data;
|
|
264
|
+
return { id, name: created, slug, apiKey: apiKey ?? null };
|
|
265
|
+
}
|
|
266
|
+
async function mintProjectKey(endpoint, cliToken, projectId, opts = {}) {
|
|
267
|
+
const base = trimTrailingSlash(endpoint);
|
|
268
|
+
let res;
|
|
269
|
+
try {
|
|
270
|
+
res = await deviceFetch(`${base}/v1/cli/projects/${projectId}/keys`, {
|
|
271
|
+
method: "POST",
|
|
272
|
+
headers: cliAuthHeaders(cliToken),
|
|
273
|
+
body: JSON.stringify({
|
|
274
|
+
...opts.scopes ? { scopes: opts.scopes } : {},
|
|
275
|
+
...opts.label ? { label: opts.label } : {}
|
|
276
|
+
})
|
|
277
|
+
});
|
|
278
|
+
} catch (err) {
|
|
279
|
+
throw new DeviceAuthRequestError(
|
|
280
|
+
"mint_key",
|
|
281
|
+
`Could not reach ${base}/v1/cli/projects/\u2026/keys: ${err instanceof Error ? err.message : String(err)}`
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
const json = await res.json().catch(() => null);
|
|
285
|
+
if (res.ok && json?.ok && json.data?.key) return json.data.key;
|
|
286
|
+
throw new DeviceAuthRequestError(
|
|
287
|
+
"mint_key",
|
|
288
|
+
json?.error?.message ?? `Could not mint an SDK key (HTTP ${res.status}).`,
|
|
289
|
+
res.status
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// src/auth-ui.ts
|
|
294
|
+
var LINE = "\u2500".repeat(58);
|
|
295
|
+
function printAuthBanner(userCode, verificationUri) {
|
|
296
|
+
console.log("");
|
|
297
|
+
console.log(` \u250C${LINE}\u2510`);
|
|
298
|
+
console.log(` \u2502 Browser sign-in \u2014 follow these 3 steps \u2502`);
|
|
299
|
+
console.log(` \u251C${LINE}\u2524`);
|
|
300
|
+
console.log(` \u2502 \u2502`);
|
|
301
|
+
console.log(` \u2502 1. A browser tab will open (or visit the URL below) \u2502`);
|
|
302
|
+
console.log(` \u2502 2. Sign in if prompted, then click "Approve" \u2502`);
|
|
303
|
+
console.log(` \u2502 3. Come back here \u2014 setup continues automatically \u2502`);
|
|
304
|
+
console.log(` \u2502 \u2502`);
|
|
305
|
+
console.log(` \u251C${LINE}\u2524`);
|
|
306
|
+
console.log(` \u2502 Verification code (show in browser \u2014 NOT terminal): \u2502`);
|
|
307
|
+
console.log(` \u2502 \u2502`);
|
|
308
|
+
console.log(` \u2502 ${userCode.padEnd(52)}\u2502`);
|
|
309
|
+
console.log(` \u2502 \u2502`);
|
|
310
|
+
console.log(` \u2502 \u26A0 Do NOT paste or type this code in your terminal \u2502`);
|
|
311
|
+
console.log(` \u2514${LINE}\u2518`);
|
|
312
|
+
console.log("");
|
|
313
|
+
console.log(` If the browser didn't open, visit this URL and approve:`);
|
|
314
|
+
console.log(` ${verificationUri}`);
|
|
315
|
+
console.log("");
|
|
316
|
+
console.log(" \u23F3 Waiting for browser approval\u2026 (Ctrl+C to cancel)");
|
|
317
|
+
console.log("");
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// src/login.ts
|
|
321
|
+
function slugify(value) {
|
|
322
|
+
return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
323
|
+
}
|
|
324
|
+
function defaultProjectName(packageName, cwd) {
|
|
325
|
+
const fromPkg = packageName?.replace(/^@[^/]+\//, "").trim();
|
|
326
|
+
if (fromPkg) return fromPkg;
|
|
327
|
+
const parts = cwd.split(/[\\/]/).filter(Boolean);
|
|
328
|
+
return parts[parts.length - 1] || "my-app";
|
|
329
|
+
}
|
|
330
|
+
function chooseProjectNonInteractive(projects, preferredName) {
|
|
331
|
+
const wanted = slugify(preferredName);
|
|
332
|
+
const match = projects.find((p2) => slugify(p2.name) === wanted || p2.slug !== void 0 && slugify(p2.slug) === wanted);
|
|
333
|
+
return match ? { kind: "existing", id: match.id, name: match.name } : { kind: "new", name: preferredName };
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// src/freshness.ts
|
|
337
|
+
var REGISTRY = "https://registry.npmjs.org";
|
|
338
|
+
var DEFAULT_TIMEOUT_MS = 2e3;
|
|
339
|
+
async function checkFreshness(packageName, currentVersion, opts = {}) {
|
|
340
|
+
if (!opts.ignoreOptOut && process.env.MUSHI_NO_UPDATE_CHECK === "1") return null;
|
|
341
|
+
const registry = opts.registry ?? REGISTRY;
|
|
342
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
343
|
+
const controller = new AbortController();
|
|
344
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
345
|
+
try {
|
|
346
|
+
const res = await fetch(
|
|
347
|
+
`${registry}/${encodeURIComponent(packageName)}/latest`,
|
|
348
|
+
{
|
|
349
|
+
signal: controller.signal,
|
|
350
|
+
headers: { Accept: "application/json" }
|
|
351
|
+
}
|
|
352
|
+
);
|
|
353
|
+
if (!res.ok) return null;
|
|
354
|
+
const body = await res.json();
|
|
355
|
+
const latest = typeof body.version === "string" ? body.version : null;
|
|
356
|
+
if (!latest) return null;
|
|
357
|
+
return {
|
|
358
|
+
current: currentVersion,
|
|
359
|
+
latest,
|
|
360
|
+
isOutdated: isNewerStableVersion(latest, currentVersion)
|
|
361
|
+
};
|
|
362
|
+
} catch {
|
|
363
|
+
return null;
|
|
364
|
+
} finally {
|
|
365
|
+
clearTimeout(timer);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
function isNewerStableVersion(latest, current) {
|
|
369
|
+
const latestCore = stripPreRelease(latest);
|
|
370
|
+
if (hasPreReleaseTag(latest)) return false;
|
|
371
|
+
const [la, lb, lc] = parse(latestCore);
|
|
372
|
+
const [ca, cb, cc] = parse(stripPreRelease(current));
|
|
373
|
+
if (la !== ca) return la > ca;
|
|
374
|
+
if (lb !== cb) return lb > cb;
|
|
375
|
+
return lc > cc;
|
|
376
|
+
}
|
|
377
|
+
function stripPreRelease(version) {
|
|
378
|
+
const idx = version.search(/[-+]/);
|
|
379
|
+
return idx === -1 ? version : version.slice(0, idx);
|
|
380
|
+
}
|
|
381
|
+
function hasPreReleaseTag(version) {
|
|
382
|
+
const plus = version.indexOf("+");
|
|
383
|
+
const hyphen = version.indexOf("-");
|
|
384
|
+
return hyphen !== -1 && (plus === -1 || hyphen < plus);
|
|
385
|
+
}
|
|
386
|
+
function parse(version) {
|
|
387
|
+
const parts = version.split(".").map((part) => Number(part));
|
|
388
|
+
return [
|
|
389
|
+
Number.isFinite(parts[0]) ? parts[0] : 0,
|
|
390
|
+
Number.isFinite(parts[1]) ? parts[1] : 0,
|
|
391
|
+
Number.isFinite(parts[2]) ? parts[2] : 0
|
|
392
|
+
];
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// src/monorepo.ts
|
|
396
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "fs";
|
|
397
|
+
import { dirname, join, resolve } from "path";
|
|
398
|
+
var WORKSPACE_GLOB_CANDIDATES = ["apps/*", "packages/*", "examples/*"];
|
|
399
|
+
var FRAMEWORK_DEPS = {
|
|
400
|
+
next: "Next.js",
|
|
401
|
+
nuxt: "Nuxt",
|
|
402
|
+
"@sveltejs/kit": "SvelteKit",
|
|
403
|
+
"@angular/core": "Angular",
|
|
404
|
+
expo: "Expo",
|
|
405
|
+
"react-native": "React Native",
|
|
406
|
+
"@capacitor/core": "Capacitor",
|
|
407
|
+
svelte: "Svelte",
|
|
408
|
+
vue: "Vue",
|
|
409
|
+
react: "React"
|
|
410
|
+
};
|
|
411
|
+
function detectWorkspaceHint(cwd) {
|
|
412
|
+
const root = findWorkspaceRoot(cwd);
|
|
413
|
+
if (!root) return null;
|
|
414
|
+
const rootPkg = readPackageJsonSafely(join(root, "package.json"));
|
|
415
|
+
if (rootPkg && getFrameworkFromPkg(rootPkg)) return null;
|
|
416
|
+
const source = existsSync(join(root, "pnpm-workspace.yaml")) ? "pnpm-workspace" : root === cwd ? "package-json" : "parent";
|
|
417
|
+
const apps = collectAppsFromGlobs(root);
|
|
418
|
+
if (apps.length === 0) return null;
|
|
419
|
+
return { root, apps, source };
|
|
420
|
+
}
|
|
421
|
+
function findWorkspaceRoot(start) {
|
|
422
|
+
let dir = resolve(start);
|
|
423
|
+
for (let i = 0; i < 8; i++) {
|
|
424
|
+
if (isWorkspaceRoot(dir)) return dir;
|
|
425
|
+
const parent = dirname(dir);
|
|
426
|
+
if (parent === dir) break;
|
|
427
|
+
dir = parent;
|
|
428
|
+
}
|
|
429
|
+
return null;
|
|
430
|
+
}
|
|
431
|
+
function isWorkspaceRoot(dir) {
|
|
432
|
+
if (existsSync(join(dir, "pnpm-workspace.yaml"))) return true;
|
|
433
|
+
const pkg = readPackageJsonSafely(join(dir, "package.json"));
|
|
434
|
+
if (!pkg) return false;
|
|
435
|
+
return Boolean(pkg.workspaces);
|
|
436
|
+
}
|
|
437
|
+
function collectAppsFromGlobs(root) {
|
|
438
|
+
const results = [];
|
|
439
|
+
for (const glob of WORKSPACE_GLOB_CANDIDATES) {
|
|
440
|
+
const prefix = glob.replace("/*", "");
|
|
441
|
+
const parentDir = join(root, prefix);
|
|
442
|
+
if (!existsSync(parentDir)) continue;
|
|
443
|
+
let entries;
|
|
444
|
+
try {
|
|
445
|
+
entries = readdirSync(parentDir);
|
|
446
|
+
} catch {
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
for (const entry of entries) {
|
|
450
|
+
const pkgPath = join(parentDir, entry, "package.json");
|
|
451
|
+
if (!isFileSafe(pkgPath)) continue;
|
|
452
|
+
const pkg = readPackageJsonSafely(pkgPath);
|
|
453
|
+
if (!pkg) continue;
|
|
454
|
+
const framework = getFrameworkFromPkg(pkg);
|
|
455
|
+
if (!framework) continue;
|
|
456
|
+
results.push({
|
|
457
|
+
name: pkg.name ?? `${prefix}/${entry}`,
|
|
458
|
+
relativePath: `${prefix}/${entry}`,
|
|
459
|
+
framework
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return results;
|
|
464
|
+
}
|
|
465
|
+
function readPackageJsonSafely(path) {
|
|
466
|
+
if (!isFileSafe(path)) return null;
|
|
467
|
+
try {
|
|
468
|
+
return JSON.parse(readFileSync(path, "utf-8"));
|
|
469
|
+
} catch {
|
|
470
|
+
return null;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
function isFileSafe(path) {
|
|
474
|
+
try {
|
|
475
|
+
return existsSync(path) && statSync(path).isFile();
|
|
476
|
+
} catch {
|
|
477
|
+
return false;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
function getFrameworkFromPkg(pkg) {
|
|
481
|
+
const deps = {
|
|
482
|
+
...pkg.dependencies ?? {},
|
|
483
|
+
...pkg.devDependencies ?? {},
|
|
484
|
+
...pkg.peerDependencies ?? {}
|
|
485
|
+
};
|
|
486
|
+
for (const dep of Object.keys(FRAMEWORK_DEPS)) {
|
|
487
|
+
if (dep in deps) return FRAMEWORK_DEPS[dep];
|
|
488
|
+
}
|
|
489
|
+
return void 0;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// src/doctor.ts
|
|
493
|
+
var SIGN_IN_HINT = "Run `npx mushi-mushi` in your app folder \u2014 browser sign-in saves the API key, project and endpoint.";
|
|
494
|
+
function checkCliConfig(config) {
|
|
495
|
+
return [
|
|
496
|
+
{
|
|
497
|
+
// No saved endpoint is not a failure: every command falls back to Mushi
|
|
498
|
+
// Cloud (endpoint.ts), so reporting "No endpoint" first sent people
|
|
499
|
+
// hunting for a URL they never needed.
|
|
500
|
+
name: "CLI config file",
|
|
501
|
+
ok: true,
|
|
502
|
+
detail: config.endpoint ? `endpoint=${config.endpoint}` : `endpoint=${CLOUD_API_ENDPOINT} (Mushi Cloud default \u2014 set MUSHI_API_ENDPOINT for a self-hosted backend)`
|
|
503
|
+
},
|
|
504
|
+
{
|
|
505
|
+
name: "API key configured",
|
|
506
|
+
ok: Boolean(config.apiKey),
|
|
507
|
+
detail: config.apiKey ? `apiKey=${config.apiKey.slice(0, 8)}\u2026${config.apiKey.slice(-4)}` : "No API key saved."
|
|
508
|
+
},
|
|
509
|
+
{
|
|
510
|
+
name: "Project ID configured",
|
|
511
|
+
ok: Boolean(config.projectId),
|
|
512
|
+
detail: config.projectId ? `projectId=${config.projectId}` : "No default project saved."
|
|
513
|
+
}
|
|
514
|
+
];
|
|
515
|
+
}
|
|
516
|
+
async function checkEndpointReachability(endpoint, doFetch = globalThis.fetch) {
|
|
517
|
+
try {
|
|
518
|
+
const safeEndpoint = sanitizeEndpoint(endpoint);
|
|
519
|
+
const res = await doFetch(`${safeEndpoint}/health`, {
|
|
520
|
+
signal: AbortSignal.timeout(5e3)
|
|
521
|
+
});
|
|
522
|
+
return {
|
|
523
|
+
name: "Endpoint reachable",
|
|
524
|
+
ok: res.status === 200,
|
|
525
|
+
detail: `GET ${safeEndpoint}/health \u2192 ${res.status}`
|
|
526
|
+
};
|
|
527
|
+
} catch (err) {
|
|
528
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
529
|
+
return { name: "Endpoint reachable", ok: false, detail: `Fetch failed: ${msg}` };
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
async function checkCliAuthPath(config, doFetch = globalThis.fetch) {
|
|
533
|
+
const checks = [];
|
|
534
|
+
const base = sanitizeEndpoint(config.endpoint ?? CLOUD_API_ENDPOINT);
|
|
535
|
+
let dateHeader = null;
|
|
536
|
+
try {
|
|
537
|
+
const res = await doFetch(`${base}/v1/cli/auth/device/token`, {
|
|
538
|
+
method: "POST",
|
|
539
|
+
headers: { "Content-Type": "application/json" },
|
|
540
|
+
body: JSON.stringify({ device_code: "doctor-probe" }),
|
|
541
|
+
signal: AbortSignal.timeout(8e3)
|
|
542
|
+
});
|
|
543
|
+
dateHeader = res.headers?.get?.("date") ?? null;
|
|
544
|
+
const signInRouteReachable = res.status === 400 || res.status === 429;
|
|
545
|
+
checks.push({
|
|
546
|
+
name: "Sign-in route reachable",
|
|
547
|
+
ok: signInRouteReachable,
|
|
548
|
+
detail: signInRouteReachable ? `POST ${base}/v1/cli/auth/device/token \u2192 ${res.status} (route deployed and answering)` : `POST ${base}/v1/cli/auth/device/token \u2192 ${res.status} \u2014 expected HTTP 400 (invalid device_code) or 429 (slow_down); the API may be down or mis-deployed.`
|
|
549
|
+
});
|
|
550
|
+
} catch (err) {
|
|
551
|
+
checks.push({
|
|
552
|
+
name: "Sign-in route reachable",
|
|
553
|
+
ok: false,
|
|
554
|
+
detail: `Fetch failed: ${err instanceof Error ? err.message : String(err)} \u2014 check network/proxy/firewall to ${base}.`
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
if (dateHeader) {
|
|
558
|
+
const serverMs = Date.parse(dateHeader);
|
|
559
|
+
if (!Number.isNaN(serverMs)) {
|
|
560
|
+
const skewSec = Math.round(Math.abs(Date.now() - serverMs) / 1e3);
|
|
561
|
+
const ok = skewSec <= 120;
|
|
562
|
+
checks.push({
|
|
563
|
+
name: "System clock in sync",
|
|
564
|
+
ok,
|
|
565
|
+
warn: !ok && skewSec <= 300,
|
|
566
|
+
detail: ok ? `Local clock within ${skewSec}s of the server.` : `Local clock is ${skewSec}s off the server \u2014 sign-in codes expire fast; fix your system time.`
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
if (config.apiKey && config.projectId) {
|
|
571
|
+
try {
|
|
572
|
+
const res = await doFetch(`${base}/v1/sync/whoami`, {
|
|
573
|
+
method: "POST",
|
|
574
|
+
headers: {
|
|
575
|
+
"Content-Type": "application/json",
|
|
576
|
+
...apiKeyHeaders(config.apiKey, config.projectId)
|
|
577
|
+
},
|
|
578
|
+
body: JSON.stringify({}),
|
|
579
|
+
signal: AbortSignal.timeout(8e3)
|
|
580
|
+
});
|
|
581
|
+
const json = await res.json().catch(() => null);
|
|
582
|
+
const ok = res.ok && json?.ok === true;
|
|
583
|
+
checks.push({
|
|
584
|
+
name: "Saved credentials valid",
|
|
585
|
+
ok,
|
|
586
|
+
detail: ok ? `API key resolves to project "${json?.data?.project_name ?? config.projectId}".` : `${json?.error?.message ?? `whoami \u2192 HTTP ${res.status}`} \u2014 re-run \`npx mushi-mushi\` to sign in again.`
|
|
587
|
+
});
|
|
588
|
+
} catch (err) {
|
|
589
|
+
checks.push({
|
|
590
|
+
name: "Saved credentials valid",
|
|
591
|
+
ok: false,
|
|
592
|
+
detail: `whoami fetch failed: ${err instanceof Error ? err.message : String(err)}`
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
} else {
|
|
596
|
+
checks.push({
|
|
597
|
+
name: "Saved credentials valid",
|
|
598
|
+
ok: true,
|
|
599
|
+
warn: true,
|
|
600
|
+
detail: "No saved CLI credentials yet \u2014 normal before the first successful sign-in."
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
return checks;
|
|
604
|
+
}
|
|
605
|
+
async function checkSdkInstall(cwd) {
|
|
606
|
+
try {
|
|
607
|
+
const { readFile } = await import("fs/promises");
|
|
608
|
+
const { join: join3, resolve: resolve2 } = await import("path");
|
|
609
|
+
const root = resolve2(cwd);
|
|
610
|
+
const pkgPath = join3(root, "package.json");
|
|
611
|
+
const pkg = JSON.parse(await readFile(pkgPath, "utf8"));
|
|
612
|
+
const deps = { ...pkg.dependencies ?? {}, ...pkg.devDependencies ?? {} };
|
|
613
|
+
const sdks = [
|
|
614
|
+
"mushi-mushi",
|
|
615
|
+
"@mushi-mushi/react",
|
|
616
|
+
"@mushi-mushi/web",
|
|
617
|
+
"@mushi-mushi/core",
|
|
618
|
+
"@mushi-mushi/react-native",
|
|
619
|
+
"@mushi-mushi/vue",
|
|
620
|
+
"@mushi-mushi/svelte",
|
|
621
|
+
"@mushi-mushi/angular",
|
|
622
|
+
"@mushi-mushi/capacitor",
|
|
623
|
+
"@mushi-mushi/node"
|
|
624
|
+
];
|
|
625
|
+
const installed = sdks.filter((s) => deps[s] && !isLauncherOnly(s, deps[s]));
|
|
626
|
+
return {
|
|
627
|
+
name: "SDK installed in this repo",
|
|
628
|
+
ok: installed.length > 0,
|
|
629
|
+
detail: installed.length > 0 ? installed.map((s) => `${s}@${deps[s]}`).join(", ") : "No Mushi Mushi SDK (mushi-mushi) in package.json \u2014 run `npx mushi-mushi` to install"
|
|
630
|
+
};
|
|
631
|
+
} catch {
|
|
632
|
+
return null;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
async function checkServerPreflight(config, doFetch = globalThis.fetch) {
|
|
636
|
+
if (!config.projectId || !config.apiKey || !config.endpoint) {
|
|
637
|
+
return [
|
|
638
|
+
{
|
|
639
|
+
name: "Server preflight",
|
|
640
|
+
ok: false,
|
|
641
|
+
detail: "Need projectId, apiKey, and endpoint. Run `mushi login` and `mushi config projectId <uuid>`."
|
|
642
|
+
}
|
|
643
|
+
];
|
|
644
|
+
}
|
|
645
|
+
try {
|
|
646
|
+
const { endpoint, apiKey, projectId } = sanitizeCliCredentials(config);
|
|
647
|
+
const res = await doFetch(`${endpoint}/v1/admin/projects/${projectId}/preflight`, {
|
|
648
|
+
headers: apiKeyHeaders(apiKey, projectId),
|
|
649
|
+
signal: AbortSignal.timeout(8e3)
|
|
650
|
+
});
|
|
651
|
+
if (res.ok) {
|
|
652
|
+
const body = await res.json();
|
|
653
|
+
const serverChecks = body.data?.checks ?? [];
|
|
654
|
+
return serverChecks.map((sc) => ({
|
|
655
|
+
name: `[server] ${sc.label}`,
|
|
656
|
+
ok: sc.ready,
|
|
657
|
+
detail: sc.ready ? "" : sc.hint
|
|
658
|
+
}));
|
|
659
|
+
}
|
|
660
|
+
if (res.status === 403) {
|
|
661
|
+
let errCode;
|
|
662
|
+
try {
|
|
663
|
+
const body = await res.json();
|
|
664
|
+
errCode = body?.error?.code;
|
|
665
|
+
} catch {
|
|
666
|
+
}
|
|
667
|
+
if (errCode === "INSUFFICIENT_SCOPE") {
|
|
668
|
+
return [
|
|
669
|
+
{
|
|
670
|
+
name: "Server preflight",
|
|
671
|
+
ok: true,
|
|
672
|
+
detail: "Skipped \u2014 your key has report:write scope only (pre-Jun 2026 key). Run `mushi login --upgrade-scope` to get mcp:read and run admin checks."
|
|
673
|
+
}
|
|
674
|
+
];
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
const text2 = await res.text().catch(() => "");
|
|
678
|
+
return [
|
|
679
|
+
{
|
|
680
|
+
name: "Server preflight",
|
|
681
|
+
ok: false,
|
|
682
|
+
detail: `HTTP ${res.status}: ${text2.slice(0, 120)}`
|
|
683
|
+
}
|
|
684
|
+
];
|
|
685
|
+
} catch (err) {
|
|
686
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
687
|
+
return [{ name: "Server preflight", ok: false, detail: `Fetch failed: ${msg}` }];
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
async function checkIngestSetup(config, doFetch = globalThis.fetch) {
|
|
691
|
+
if (!config.apiKey || !config.endpoint) {
|
|
692
|
+
return [
|
|
693
|
+
{
|
|
694
|
+
name: "Ingest setup",
|
|
695
|
+
ok: false,
|
|
696
|
+
detail: "Need apiKey and endpoint. Run `mushi connect`."
|
|
697
|
+
}
|
|
698
|
+
];
|
|
699
|
+
}
|
|
700
|
+
try {
|
|
701
|
+
const data = await fetchIngestSetup(
|
|
702
|
+
{ endpoint: config.endpoint, apiKey: config.apiKey, projectId: config.projectId },
|
|
703
|
+
doFetch
|
|
704
|
+
);
|
|
705
|
+
if (!data) {
|
|
706
|
+
return [
|
|
707
|
+
{
|
|
708
|
+
name: "Ingest setup",
|
|
709
|
+
ok: false,
|
|
710
|
+
detail: "Request to /v1/sync/ingest-setup failed or returned invalid payload"
|
|
711
|
+
}
|
|
712
|
+
];
|
|
713
|
+
}
|
|
714
|
+
const steps = data.steps ?? [];
|
|
715
|
+
const checks = steps.filter((s) => s.required).map((s) => ({
|
|
716
|
+
name: `[ingest] ${s.label}`,
|
|
717
|
+
ok: s.complete,
|
|
718
|
+
detail: s.complete ? "" : s.hint ?? ""
|
|
719
|
+
}));
|
|
720
|
+
const diag = data.diagnostic;
|
|
721
|
+
if (diag?.last_sdk_seen_at) {
|
|
722
|
+
checks.push({
|
|
723
|
+
name: "[ingest] Last SDK heartbeat",
|
|
724
|
+
ok: true,
|
|
725
|
+
detail: `${diag.last_sdk_seen_at}${diag.last_sdk_endpoint_host ? ` @ ${diag.last_sdk_endpoint_host}` : ""}`
|
|
726
|
+
});
|
|
727
|
+
}
|
|
728
|
+
return checks.length > 0 ? checks : [{ name: "Ingest setup", ok: false, detail: "Empty response from /v1/sync/ingest-setup" }];
|
|
729
|
+
} catch (err) {
|
|
730
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
731
|
+
return [{ name: "Ingest setup", ok: false, detail: `Fetch failed: ${msg}` }];
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
async function checkQaStoriesHealth(config, doFetch = globalThis.fetch) {
|
|
735
|
+
if (!config.projectId || !config.apiKey || !config.endpoint) {
|
|
736
|
+
return [
|
|
737
|
+
{
|
|
738
|
+
name: "QA stories health",
|
|
739
|
+
ok: false,
|
|
740
|
+
detail: "Need projectId, apiKey, and endpoint for QA story checks."
|
|
741
|
+
}
|
|
742
|
+
];
|
|
743
|
+
}
|
|
744
|
+
const checks = [];
|
|
745
|
+
try {
|
|
746
|
+
const { endpoint, apiKey, projectId } = sanitizeCliCredentials(config);
|
|
747
|
+
const headers = apiKeyHeaders(apiKey, projectId);
|
|
748
|
+
const storiesRes = await doFetch(`${endpoint}/v1/admin/projects/${projectId}/qa-coverage`, {
|
|
749
|
+
headers,
|
|
750
|
+
signal: AbortSignal.timeout(8e3)
|
|
751
|
+
});
|
|
752
|
+
if (!storiesRes.ok) {
|
|
753
|
+
checks.push({
|
|
754
|
+
name: "[qa] Fetch QA stories",
|
|
755
|
+
ok: false,
|
|
756
|
+
detail: `HTTP ${storiesRes.status}`
|
|
757
|
+
});
|
|
758
|
+
return checks;
|
|
759
|
+
}
|
|
760
|
+
const storiesBody = await storiesRes.json();
|
|
761
|
+
const stories = storiesBody.data?.coverage ?? [];
|
|
762
|
+
const enabled = stories.filter((s) => s.enabled);
|
|
763
|
+
if (enabled.length === 0) {
|
|
764
|
+
checks.push({
|
|
765
|
+
name: "[qa] Enabled QA stories",
|
|
766
|
+
ok: true,
|
|
767
|
+
detail: "No enabled stories \u2014 create one at /qa-coverage"
|
|
768
|
+
});
|
|
769
|
+
return checks;
|
|
770
|
+
}
|
|
771
|
+
checks.push({
|
|
772
|
+
name: "[qa] Enabled QA stories",
|
|
773
|
+
ok: true,
|
|
774
|
+
detail: `${enabled.length} enabled story/stories configured`
|
|
775
|
+
});
|
|
776
|
+
const slackRes = await doFetch(
|
|
777
|
+
`${endpoint}/v1/admin/projects/${projectId}/integrations/probe/slack`,
|
|
778
|
+
{
|
|
779
|
+
method: "POST",
|
|
780
|
+
headers,
|
|
781
|
+
signal: AbortSignal.timeout(6e3)
|
|
782
|
+
}
|
|
783
|
+
);
|
|
784
|
+
const slackBody = slackRes.ok ? await slackRes.json() : null;
|
|
785
|
+
const slackOk = slackBody?.status === "ok";
|
|
786
|
+
checks.push({
|
|
787
|
+
name: "[qa] Slack notifications configured",
|
|
788
|
+
ok: slackOk,
|
|
789
|
+
detail: slackOk ? "Slack connected \u2014 failures will notify your channel" : "Slack not connected \u2014 you won't be notified when stories fail. Visit /integrations \u2192 Add to Slack."
|
|
790
|
+
});
|
|
791
|
+
const fcRes = await doFetch(
|
|
792
|
+
`${endpoint}/v1/admin/projects/${projectId}/integrations/probe/firecrawl`,
|
|
793
|
+
{
|
|
794
|
+
method: "POST",
|
|
795
|
+
headers,
|
|
796
|
+
signal: AbortSignal.timeout(6e3)
|
|
797
|
+
}
|
|
798
|
+
);
|
|
799
|
+
const fcBody = fcRes.ok ? await fcRes.json() : null;
|
|
800
|
+
const hasFirecrawlStories = enabled.some(
|
|
801
|
+
(s) => !s.browser_provider || s.browser_provider === "firecrawl_actions"
|
|
802
|
+
);
|
|
803
|
+
if (hasFirecrawlStories) {
|
|
804
|
+
const fcOk = fcBody?.status === "ok";
|
|
805
|
+
checks.push({
|
|
806
|
+
name: "[qa] Firecrawl API key configured",
|
|
807
|
+
ok: fcOk,
|
|
808
|
+
detail: fcOk ? "Firecrawl key is resolvable \u2014 stories will run without Unauthorized errors" : "No Firecrawl key found \u2014 enabled stories using firecrawl_actions will 401. Add a key at /integrations \u2192 BYOK keys."
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
} catch (err) {
|
|
812
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
813
|
+
checks.push({ name: "[qa] QA stories health", ok: false, detail: `Fetch failed: ${msg}` });
|
|
814
|
+
}
|
|
815
|
+
return checks;
|
|
816
|
+
}
|
|
817
|
+
async function checkHostAppWiring(cwd) {
|
|
818
|
+
const checks = [];
|
|
819
|
+
try {
|
|
820
|
+
const { readFile, access } = await import("fs/promises");
|
|
821
|
+
const { join: join3, resolve: resolve2 } = await import("path");
|
|
822
|
+
const root = resolve2(cwd);
|
|
823
|
+
const pkgPath = join3(root, "package.json");
|
|
824
|
+
const pkg = JSON.parse(await readFile(pkgPath, "utf8"));
|
|
825
|
+
const deps = { ...pkg.dependencies ?? {}, ...pkg.devDependencies ?? {} };
|
|
826
|
+
const isCapHybrid = Boolean(deps["@capacitor/core"] && deps["react"]);
|
|
827
|
+
const envCandidates = [".env.local", ".env"];
|
|
828
|
+
let envContent = "";
|
|
829
|
+
for (const f of envCandidates) {
|
|
830
|
+
try {
|
|
831
|
+
envContent = await readFile(join3(root, f), "utf8");
|
|
832
|
+
break;
|
|
833
|
+
} catch {
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
const hasProjectId = /VITE_MUSHI_PROJECT_ID=|NEXT_PUBLIC_MUSHI_PROJECT_ID=|MUSHI_PROJECT_ID=/.test(envContent);
|
|
837
|
+
const hasApiKey = /VITE_MUSHI_API_KEY=|NEXT_PUBLIC_MUSHI_API_KEY=|MUSHI_API_KEY=/.test(
|
|
838
|
+
envContent
|
|
839
|
+
);
|
|
840
|
+
checks.push({
|
|
841
|
+
name: "[host] Mushi env vars in .env.local",
|
|
842
|
+
ok: hasProjectId && hasApiKey,
|
|
843
|
+
detail: hasProjectId && hasApiKey ? "VITE_/MUSHI_ project id + API key found" : "Run `mushi connect --write-env` or add VITE_MUSHI_PROJECT_ID + VITE_MUSHI_API_KEY"
|
|
844
|
+
});
|
|
845
|
+
let mcpFound = null;
|
|
846
|
+
for (const rel of [".mcp.json", join3(".cursor", "mcp.json")]) {
|
|
847
|
+
try {
|
|
848
|
+
await access(join3(root, rel));
|
|
849
|
+
mcpFound = rel;
|
|
850
|
+
break;
|
|
851
|
+
} catch {
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
checks.push({
|
|
855
|
+
name: "[host] MCP config",
|
|
856
|
+
ok: mcpFound !== null,
|
|
857
|
+
detail: mcpFound ? `${mcpFound} present` : "No .mcp.json (Claude Code) or .cursor/mcp.json (Cursor) \u2014 run `npx mushi-mushi setup --ide claude` or `--ide cursor` for two-way reporter replies"
|
|
858
|
+
});
|
|
859
|
+
if (isCapHybrid) {
|
|
860
|
+
const hasWebSdk = Boolean(
|
|
861
|
+
deps["mushi-mushi"] && !isLauncherOnly("mushi-mushi", deps["mushi-mushi"]) || deps["@mushi-mushi/web"] || deps["@mushi-mushi/react"]
|
|
862
|
+
);
|
|
863
|
+
checks.push({
|
|
864
|
+
name: "[host] Capacitor hybrid \u2014 WebView SDK",
|
|
865
|
+
ok: hasWebSdk,
|
|
866
|
+
detail: hasWebSdk ? "Use mushi-mushi (or mushi-mushi/react) in the WebView (initMushi in main.tsx)" : "Install mushi-mushi for Capacitor WebView reporting"
|
|
867
|
+
});
|
|
868
|
+
checks.push({
|
|
869
|
+
name: "[host] Capacitor native plugin (optional)",
|
|
870
|
+
ok: true,
|
|
871
|
+
detail: deps["@mushi-mushi/capacitor"] ? `@mushi-mushi/capacitor@${deps["@mushi-mushi/capacitor"]} installed` : "Optional: @mushi-mushi/capacitor for native shell parity \u2014 WebView SDK covers most flows"
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
} catch {
|
|
875
|
+
checks.push({
|
|
876
|
+
name: "[host] Host app detection",
|
|
877
|
+
ok: false,
|
|
878
|
+
detail: "No package.json in cwd \u2014 run from your app repo root"
|
|
879
|
+
});
|
|
880
|
+
}
|
|
881
|
+
return checks;
|
|
882
|
+
}
|
|
883
|
+
var HASH_ROUTER_PATTERNS = [
|
|
884
|
+
/\bHashRouter\b/,
|
|
885
|
+
/\bcreateHashRouter\b/,
|
|
886
|
+
/location\.hash\b/,
|
|
887
|
+
/addEventListener\(['"]hashchange['"]/
|
|
888
|
+
];
|
|
889
|
+
var HASH_TEMPLATE_PATTERN = /['"`]\/?#\//;
|
|
890
|
+
async function scanDirForPattern(dir, patterns, maxDepth = 6, maxFiles = 2e3) {
|
|
891
|
+
const { readdir, readFile } = await import("fs/promises");
|
|
892
|
+
const { join: join3 } = await import("path");
|
|
893
|
+
let count = 0;
|
|
894
|
+
async function walk(d, depth) {
|
|
895
|
+
if (depth > maxDepth || count > maxFiles) return null;
|
|
896
|
+
let entries = [];
|
|
897
|
+
try {
|
|
898
|
+
entries = await readdir(d, { withFileTypes: true });
|
|
899
|
+
} catch {
|
|
900
|
+
return null;
|
|
901
|
+
}
|
|
902
|
+
for (const e of entries) {
|
|
903
|
+
if (e.name.startsWith(".") || e.name === "node_modules" || e.name === "dist") continue;
|
|
904
|
+
const full = join3(d, e.name);
|
|
905
|
+
if (e.isDirectory()) {
|
|
906
|
+
const found = await walk(full, depth + 1);
|
|
907
|
+
if (found) return found;
|
|
908
|
+
} else if (/\.[cm]?[jt]sx?$/.test(e.name)) {
|
|
909
|
+
count++;
|
|
910
|
+
try {
|
|
911
|
+
const src = await readFile(full, "utf8");
|
|
912
|
+
if (patterns.some((p2) => p2.test(src))) return full;
|
|
913
|
+
} catch {
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
return null;
|
|
918
|
+
}
|
|
919
|
+
const { resolve: resolve2 } = await import("path");
|
|
920
|
+
for (const sub of ["src", "app", "pages", "lib", "components"]) {
|
|
921
|
+
const found = await walk(join3(resolve2(dir), sub), 0);
|
|
922
|
+
if (found) return found;
|
|
923
|
+
}
|
|
924
|
+
return walk(resolve2(dir), 0);
|
|
925
|
+
}
|
|
926
|
+
async function checkHashRouterCapture(cwd) {
|
|
927
|
+
const hashFile = await scanDirForPattern(cwd, HASH_ROUTER_PATTERNS);
|
|
928
|
+
if (!hashFile) return [];
|
|
929
|
+
const templateFile = await scanDirForPattern(cwd, [HASH_TEMPLATE_PATTERN]);
|
|
930
|
+
if (templateFile) {
|
|
931
|
+
return [
|
|
932
|
+
{
|
|
933
|
+
name: "[host] Hash-router route capture",
|
|
934
|
+
ok: true,
|
|
935
|
+
detail: `Hash-router detected (${hashFile}) and /#/ route templates found in Mushi config \u2014 routes will be captured correctly.`
|
|
936
|
+
}
|
|
937
|
+
];
|
|
938
|
+
}
|
|
939
|
+
return [
|
|
940
|
+
{
|
|
941
|
+
name: "[host] Hash-router route capture",
|
|
942
|
+
ok: true,
|
|
943
|
+
warn: true,
|
|
944
|
+
detail: `Hash-router detected (${hashFile}) but no /#/ route templates found in your Mushi init call. Add discoverInventory.routeTemplates with /#/-prefixed patterns (e.g. ['/#/article/[slug]']) so Mushi captures parametric hash routes correctly \u2014 without these, all hash navigations appear as a single "/#/" route in the inventory.`
|
|
945
|
+
}
|
|
946
|
+
];
|
|
947
|
+
}
|
|
948
|
+
function isJsonObject(value) {
|
|
949
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
950
|
+
}
|
|
951
|
+
function normalizeProjectPath(path) {
|
|
952
|
+
const slashed = path.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
953
|
+
return process.platform === "win32" ? slashed.toLowerCase() : slashed;
|
|
954
|
+
}
|
|
955
|
+
async function collectMcpSources(root, home) {
|
|
956
|
+
const { readFile } = await import("fs/promises");
|
|
957
|
+
const { join: join3 } = await import("path");
|
|
958
|
+
const sources = [];
|
|
959
|
+
const invalid = [];
|
|
960
|
+
const plainFiles = [
|
|
961
|
+
{ path: join3(root, ".mcp.json"), claudeCode: true },
|
|
962
|
+
{ path: join3(root, ".cursor", "mcp.json"), claudeCode: false },
|
|
963
|
+
{ path: join3(home, ".cursor", "mcp.json"), claudeCode: false }
|
|
964
|
+
];
|
|
965
|
+
for (const file of plainFiles) {
|
|
966
|
+
let raw;
|
|
967
|
+
try {
|
|
968
|
+
raw = await readFile(file.path, "utf8");
|
|
969
|
+
} catch {
|
|
970
|
+
continue;
|
|
971
|
+
}
|
|
972
|
+
try {
|
|
973
|
+
const parsed = JSON.parse(raw);
|
|
974
|
+
const servers = isJsonObject(parsed) && isJsonObject(parsed.mcpServers) ? parsed.mcpServers : {};
|
|
975
|
+
sources.push({ path: file.path, servers, claudeCode: file.claudeCode });
|
|
976
|
+
} catch {
|
|
977
|
+
invalid.push(file.path);
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
const claudeJsonPath = join3(home, ".claude.json");
|
|
981
|
+
try {
|
|
982
|
+
const parsed = JSON.parse(await readFile(claudeJsonPath, "utf8"));
|
|
983
|
+
if (isJsonObject(parsed)) {
|
|
984
|
+
const servers = isJsonObject(parsed.mcpServers) ? { ...parsed.mcpServers } : {};
|
|
985
|
+
const projects = isJsonObject(parsed.projects) ? parsed.projects : {};
|
|
986
|
+
const wanted = normalizeProjectPath(root);
|
|
987
|
+
for (const [projectPath, entry] of Object.entries(projects)) {
|
|
988
|
+
if (normalizeProjectPath(projectPath) === wanted && isJsonObject(entry) && isJsonObject(entry.mcpServers)) {
|
|
989
|
+
Object.assign(servers, entry.mcpServers);
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
sources.push({ path: claudeJsonPath, servers, claudeCode: true });
|
|
993
|
+
}
|
|
994
|
+
} catch {
|
|
995
|
+
}
|
|
996
|
+
return { sources, invalid };
|
|
997
|
+
}
|
|
998
|
+
function claudeOAuthCannotDiscover(entry, url) {
|
|
999
|
+
let host;
|
|
1000
|
+
try {
|
|
1001
|
+
host = new URL(url).hostname.toLowerCase();
|
|
1002
|
+
} catch {
|
|
1003
|
+
return false;
|
|
1004
|
+
}
|
|
1005
|
+
if (!host.endsWith(".supabase.co")) return false;
|
|
1006
|
+
const headers = isJsonObject(entry.headers) ? Object.keys(entry.headers).map((h) => h.toLowerCase()) : [];
|
|
1007
|
+
if (headers.includes("authorization") || headers.includes("x-mushi-api-key")) return false;
|
|
1008
|
+
const oauth = isJsonObject(entry.oauth) ? entry.oauth : {};
|
|
1009
|
+
return typeof oauth.authServerMetadataUrl !== "string" || oauth.authServerMetadataUrl.length === 0;
|
|
1010
|
+
}
|
|
1011
|
+
function assessMushiEntry(source, name, entry, cliKeySaved) {
|
|
1012
|
+
const label = `${name} (${source.path})`;
|
|
1013
|
+
if (!isJsonObject(entry)) return { usable: false, stdio: false, detail: `${label}: not an object` };
|
|
1014
|
+
if (typeof entry.url === "string") {
|
|
1015
|
+
if (source.claudeCode && entry.type !== "http" && entry.type !== "sse") {
|
|
1016
|
+
return {
|
|
1017
|
+
usable: false,
|
|
1018
|
+
stdio: false,
|
|
1019
|
+
detail: `${label}: has a url but no "type": "http" \u2014 Claude Code skips it`
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
if (source.claudeCode && claudeOAuthCannotDiscover(entry, entry.url)) {
|
|
1023
|
+
return {
|
|
1024
|
+
usable: false,
|
|
1025
|
+
stdio: false,
|
|
1026
|
+
detail: `${label}: Claude Code sign-in cannot find OAuth metadata on a supabase.co URL ("Dynamic Client Registration rejected (HTTP 404)") \u2014 use ${CLOUD_MCP_OAUTH_URL} for Mushi Cloud, or add "oauth": { "authServerMetadataUrl": "<url>/.well-known/oauth-authorization-server" }`
|
|
1027
|
+
};
|
|
1028
|
+
}
|
|
1029
|
+
return { usable: true, stdio: false, detail: `${label}: hosted OAuth \u2014 sign in from the IDE's MCP panel` };
|
|
1030
|
+
}
|
|
1031
|
+
const env = isJsonObject(entry.env) ? entry.env : {};
|
|
1032
|
+
const key = env.MUSHI_API_KEY;
|
|
1033
|
+
const endpoint = env.MUSHI_API_ENDPOINT;
|
|
1034
|
+
if (typeof endpoint === "string" && !/^https?:\/\//.test(endpoint) && !/^\$\{.+\}$/.test(endpoint)) {
|
|
1035
|
+
return { usable: false, stdio: true, detail: `${label}: MUSHI_API_ENDPOINT is not a URL` };
|
|
1036
|
+
}
|
|
1037
|
+
if (typeof key === "string" && key.startsWith("mushi_")) {
|
|
1038
|
+
return { usable: true, stdio: true, detail: `${label}: key written inline` };
|
|
1039
|
+
}
|
|
1040
|
+
if (key === void 0 || typeof key === "string" && /^\$\{.*\}$/.test(key)) {
|
|
1041
|
+
return cliKeySaved ? { usable: true, stdio: true, detail: `${label}: key from MUSHI_API_KEY or the saved CLI config` } : {
|
|
1042
|
+
usable: false,
|
|
1043
|
+
stdio: true,
|
|
1044
|
+
detail: `${label}: reads the key from MUSHI_API_KEY or the CLI config, and neither is set`
|
|
1045
|
+
};
|
|
1046
|
+
}
|
|
1047
|
+
return { usable: false, stdio: true, detail: `${label}: MUSHI_API_KEY is neither a mushi_ key nor a placeholder` };
|
|
1048
|
+
}
|
|
1049
|
+
async function checkMcpConfig(config, cwd, doFetch = globalThis.fetch, home) {
|
|
1050
|
+
const checks = [];
|
|
1051
|
+
const { resolve: resolve2 } = await import("path");
|
|
1052
|
+
const { homedir } = await import("os");
|
|
1053
|
+
const root = resolve2(cwd);
|
|
1054
|
+
const { sources, invalid } = await collectMcpSources(root, home ?? homedir());
|
|
1055
|
+
if (invalid.length > 0) {
|
|
1056
|
+
checks.push({
|
|
1057
|
+
name: "[mcp] MCP config valid JSON",
|
|
1058
|
+
ok: false,
|
|
1059
|
+
detail: `Not valid JSON: ${invalid.join(", ")}`
|
|
1060
|
+
});
|
|
1061
|
+
}
|
|
1062
|
+
if (sources.length === 0) {
|
|
1063
|
+
if (invalid.length === 0) {
|
|
1064
|
+
checks.push({
|
|
1065
|
+
name: "[mcp] MCP config present",
|
|
1066
|
+
ok: false,
|
|
1067
|
+
detail: "No .mcp.json, .cursor/mcp.json, ~/.cursor/mcp.json or ~/.claude.json found."
|
|
1068
|
+
});
|
|
1069
|
+
}
|
|
1070
|
+
return checks;
|
|
1071
|
+
}
|
|
1072
|
+
checks.push({
|
|
1073
|
+
name: "[mcp] MCP config present",
|
|
1074
|
+
ok: true,
|
|
1075
|
+
detail: `Found: ${sources.map((s) => s.path).join(", ")}`
|
|
1076
|
+
});
|
|
1077
|
+
const mushiEntries = sources.flatMap(
|
|
1078
|
+
(source) => Object.entries(source.servers).filter(([name]) => name === "mushi" || name.startsWith("mushi-")).map(([name, entry]) => ({ source, name, entry }))
|
|
1079
|
+
);
|
|
1080
|
+
if (mushiEntries.length === 0) {
|
|
1081
|
+
checks.push({
|
|
1082
|
+
name: "[mcp] mushi server entry",
|
|
1083
|
+
ok: false,
|
|
1084
|
+
detail: "No mushi or mushi-* server in any MCP config."
|
|
1085
|
+
});
|
|
1086
|
+
return checks;
|
|
1087
|
+
}
|
|
1088
|
+
checks.push({
|
|
1089
|
+
name: "[mcp] mushi server entry",
|
|
1090
|
+
ok: true,
|
|
1091
|
+
detail: `Found: ${mushiEntries.map(({ name }) => name).join(", ")}`
|
|
1092
|
+
});
|
|
1093
|
+
const assessed = mushiEntries.map(
|
|
1094
|
+
({ source, name, entry }) => assessMushiEntry(source, name, entry, Boolean(config.apiKey))
|
|
1095
|
+
);
|
|
1096
|
+
checks.push({
|
|
1097
|
+
name: "[mcp] mushi entries usable",
|
|
1098
|
+
ok: assessed.every((a) => a.usable),
|
|
1099
|
+
detail: assessed.map((a) => a.detail).join("; ")
|
|
1100
|
+
});
|
|
1101
|
+
if (assessed.some((a) => a.stdio && a.usable) && config.apiKey && config.endpoint) {
|
|
1102
|
+
try {
|
|
1103
|
+
const { endpoint, apiKey } = sanitizeCliCredentials(config);
|
|
1104
|
+
const res = await doFetch(`${endpoint}/v1/admin/mcp/account-overview`, {
|
|
1105
|
+
headers: apiKeyHeaders(apiKey, config.projectId),
|
|
1106
|
+
signal: AbortSignal.timeout(6e3)
|
|
1107
|
+
});
|
|
1108
|
+
if (res.ok) {
|
|
1109
|
+
const body = await res.json();
|
|
1110
|
+
const projectCount = body?.data?.total ?? 0;
|
|
1111
|
+
checks.push({
|
|
1112
|
+
name: "[mcp] account-overview reachable",
|
|
1113
|
+
ok: true,
|
|
1114
|
+
detail: `Key is valid; ${projectCount} accessible project${projectCount === 1 ? "" : "s"}`
|
|
1115
|
+
});
|
|
1116
|
+
} else {
|
|
1117
|
+
let detail = `GET /v1/admin/mcp/account-overview \u2192 HTTP ${res.status}. Verify the API key is active.`;
|
|
1118
|
+
try {
|
|
1119
|
+
const errBody = await res.json();
|
|
1120
|
+
const nested = errBody["error"];
|
|
1121
|
+
const errCode = nested?.["code"] ?? errBody["code"] ?? "";
|
|
1122
|
+
if (errCode === "INSUFFICIENT_SCOPE") {
|
|
1123
|
+
detail = `Key has report:write scope only \u2014 run \`mushi login --upgrade-scope\` then \`mushi setup\` to get mcp:read.`;
|
|
1124
|
+
}
|
|
1125
|
+
} catch {
|
|
1126
|
+
}
|
|
1127
|
+
checks.push({
|
|
1128
|
+
name: "[mcp] account-overview reachable",
|
|
1129
|
+
ok: false,
|
|
1130
|
+
detail
|
|
1131
|
+
});
|
|
1132
|
+
}
|
|
1133
|
+
} catch (err) {
|
|
1134
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1135
|
+
checks.push({
|
|
1136
|
+
name: "[mcp] account-overview reachable",
|
|
1137
|
+
ok: false,
|
|
1138
|
+
detail: `Probe failed: ${msg}. Check MUSHI_API_ENDPOINT and network connectivity.`
|
|
1139
|
+
});
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
return checks;
|
|
1143
|
+
}
|
|
1144
|
+
var FIX_HINTS = {
|
|
1145
|
+
"Mushi set up here": "Run `npx mushi-mushi` in your app folder \u2014 it signs you in, installs the SDK and writes the env vars.",
|
|
1146
|
+
"API key configured": SIGN_IN_HINT,
|
|
1147
|
+
"Project ID configured": SIGN_IN_HINT,
|
|
1148
|
+
"Endpoint reachable": "Check your network and that MUSHI_API_ENDPOINT points at `\u2026/functions/v1/api`.",
|
|
1149
|
+
"[ingest]": "Open the console Onboarding wizard \u2192 Install SDK \u2192 submit a test report, or run `mushi connect --wait`.",
|
|
1150
|
+
"[server]": "Open Settings \u2192 Integrations: connect GitHub, index codebase, add Anthropic BYOK key, enable autofix.",
|
|
1151
|
+
"[mcp]": "Run `npx mushi-mushi setup --ide cursor` (or `--ide claude`) to rewrite the Mushi MCP entry."
|
|
1152
|
+
};
|
|
1153
|
+
function fixHintForCheck(name) {
|
|
1154
|
+
if (FIX_HINTS[name]) return FIX_HINTS[name];
|
|
1155
|
+
if (name.startsWith("[ingest]")) return FIX_HINTS["[ingest]"];
|
|
1156
|
+
if (name.startsWith("[server]") || name.startsWith("[preflight]")) return FIX_HINTS["[server]"];
|
|
1157
|
+
if (name.startsWith("[mcp]")) return FIX_HINTS["[mcp]"];
|
|
1158
|
+
return void 0;
|
|
1159
|
+
}
|
|
1160
|
+
async function checkVersionDrift(cwd, doFetch) {
|
|
1161
|
+
const checks = [];
|
|
1162
|
+
const { MUSHI_CLI_VERSION: MUSHI_CLI_VERSION2 } = await import("./version.js");
|
|
1163
|
+
if (MUSHI_CLI_VERSION2 === "0.0.0-dev") return checks;
|
|
1164
|
+
const parse2 = (v) => {
|
|
1165
|
+
const m = v.replace(/^[~^]/, "").match(/^(\d+)\.(\d+)\.(\d+)/);
|
|
1166
|
+
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : [0, 0, 0];
|
|
1167
|
+
};
|
|
1168
|
+
const isBehind = (installed, latest) => {
|
|
1169
|
+
const [a1, a2, a3] = parse2(installed);
|
|
1170
|
+
const [b1, b2, b3] = parse2(latest);
|
|
1171
|
+
return a1 !== b1 ? a1 < b1 : a2 !== b2 ? a2 < b2 : a3 < b3;
|
|
1172
|
+
};
|
|
1173
|
+
try {
|
|
1174
|
+
const res = await doFetch("https://registry.npmjs.org/@mushi-mushi/cli/latest", {
|
|
1175
|
+
signal: AbortSignal.timeout(3e3)
|
|
1176
|
+
});
|
|
1177
|
+
if (res.ok) {
|
|
1178
|
+
const { version: latest } = await res.json();
|
|
1179
|
+
if (latest && isBehind(MUSHI_CLI_VERSION2, latest)) {
|
|
1180
|
+
checks.push({
|
|
1181
|
+
name: "CLI version",
|
|
1182
|
+
ok: true,
|
|
1183
|
+
warn: true,
|
|
1184
|
+
detail: `Installed ${MUSHI_CLI_VERSION2}, latest is ${latest}. Run \`mushi upgrade\` (or npm i -g @mushi-mushi/cli@latest).`
|
|
1185
|
+
});
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
} catch {
|
|
1189
|
+
}
|
|
1190
|
+
try {
|
|
1191
|
+
const { readFile } = await import("fs/promises");
|
|
1192
|
+
const { join: join3 } = await import("path");
|
|
1193
|
+
const pkg = JSON.parse(await readFile(join3(cwd, "package.json"), "utf8"));
|
|
1194
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
1195
|
+
const candidates = Object.entries(deps).filter(([name, spec]) => isMushiSdkPackage(name) && !isLauncherOnly(name, spec)).filter(([, v]) => /^[~^]?\d/.test(v));
|
|
1196
|
+
const drifted = (await Promise.all(
|
|
1197
|
+
candidates.map(async ([name, v]) => {
|
|
1198
|
+
try {
|
|
1199
|
+
const res = await doFetch(`https://registry.npmjs.org/${name}/latest`, {
|
|
1200
|
+
signal: AbortSignal.timeout(3e3)
|
|
1201
|
+
});
|
|
1202
|
+
if (!res.ok) return null;
|
|
1203
|
+
const { version: latest } = await res.json();
|
|
1204
|
+
return latest && isBehind(v, latest) ? [name, v, latest] : null;
|
|
1205
|
+
} catch {
|
|
1206
|
+
return null;
|
|
1207
|
+
}
|
|
1208
|
+
})
|
|
1209
|
+
)).filter((d) => d !== null);
|
|
1210
|
+
if (drifted.length > 0) {
|
|
1211
|
+
checks.push({
|
|
1212
|
+
name: "SDK version drift",
|
|
1213
|
+
ok: true,
|
|
1214
|
+
warn: true,
|
|
1215
|
+
detail: `${drifted.map(([n, v, l]) => `${n}@${v} (latest ${l})`).join(", ")} \u2014 behind npm latest. Run \`mushi upgrade\` in this repo.`
|
|
1216
|
+
});
|
|
1217
|
+
}
|
|
1218
|
+
} catch {
|
|
1219
|
+
}
|
|
1220
|
+
return checks;
|
|
1221
|
+
}
|
|
1222
|
+
async function checkPipelineDoctor(config, doFetch) {
|
|
1223
|
+
if (!config.endpoint || !config.apiKey) return [];
|
|
1224
|
+
try {
|
|
1225
|
+
const res = await doFetch(`${config.endpoint.replace(/\/$/, "")}/v1/admin/doctor`, {
|
|
1226
|
+
headers: apiKeyHeaders(config.apiKey),
|
|
1227
|
+
signal: AbortSignal.timeout(1e4)
|
|
1228
|
+
});
|
|
1229
|
+
if (res.status === 401 || res.status === 403) return [];
|
|
1230
|
+
if (!res.ok) {
|
|
1231
|
+
return [{
|
|
1232
|
+
name: "[pipeline] Server doctor",
|
|
1233
|
+
ok: true,
|
|
1234
|
+
warn: true,
|
|
1235
|
+
detail: `GET /v1/admin/doctor returned HTTP ${res.status} \u2014 pipeline health unknown.`
|
|
1236
|
+
}];
|
|
1237
|
+
}
|
|
1238
|
+
const body = await res.json();
|
|
1239
|
+
return (body.data?.checks ?? []).map((ch) => ({
|
|
1240
|
+
name: `[pipeline] ${ch.name}`,
|
|
1241
|
+
ok: ch.status !== "fail",
|
|
1242
|
+
warn: ch.status === "warn",
|
|
1243
|
+
detail: ch.hint ? `${ch.summary} \u2192 Fix: ${ch.hint}` : ch.summary
|
|
1244
|
+
}));
|
|
1245
|
+
} catch {
|
|
1246
|
+
return [{
|
|
1247
|
+
name: "[pipeline] Server doctor",
|
|
1248
|
+
ok: true,
|
|
1249
|
+
warn: true,
|
|
1250
|
+
detail: "Could not reach /v1/admin/doctor (timeout) \u2014 pipeline health unknown."
|
|
1251
|
+
}];
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
var HEARTBEAT_ROWS = /* @__PURE__ */ new Set(["never_seen", "sdk_stale"]);
|
|
1255
|
+
async function checkHealthRegistry(config, doFetch) {
|
|
1256
|
+
if (!config.endpoint || !config.apiKey || !config.projectId) return [];
|
|
1257
|
+
let creds;
|
|
1258
|
+
try {
|
|
1259
|
+
creds = sanitizeCliCredentials(config);
|
|
1260
|
+
} catch {
|
|
1261
|
+
return [];
|
|
1262
|
+
}
|
|
1263
|
+
try {
|
|
1264
|
+
const { endpoint, apiKey, projectId } = creds;
|
|
1265
|
+
const res = await doFetch(`${endpoint}/v1/admin/health-checks?projectId=${encodeURIComponent(projectId)}`, {
|
|
1266
|
+
headers: apiKeyHeaders(apiKey, projectId),
|
|
1267
|
+
signal: AbortSignal.timeout(3e4)
|
|
1268
|
+
});
|
|
1269
|
+
if (res.status === 401 || res.status === 403 || res.status === 404) return [];
|
|
1270
|
+
if (!res.ok) {
|
|
1271
|
+
return [{ name: "[health] Health check", ok: true, warn: true, detail: `GET /v1/admin/health-checks returned HTTP ${res.status}; health unknown.` }];
|
|
1272
|
+
}
|
|
1273
|
+
const body = await res.json();
|
|
1274
|
+
const rows = (body.data?.projects?.[0]?.checks ?? []).filter((r) => r.source !== "doctor" && !HEARTBEAT_ROWS.has(r.id));
|
|
1275
|
+
const out = [];
|
|
1276
|
+
for (const r of rows) {
|
|
1277
|
+
if (r.status === "ok") continue;
|
|
1278
|
+
const waiting = r.affects && r.affects > 0 ? ` ${r.affects} waiting on this.` : "";
|
|
1279
|
+
const fix = r.fix ? ` \u2192 Fix: ${r.fix.label}${r.fix.to ? ` (console ${r.fix.to})` : ""}${r.fix.steps?.length ? `: ${r.fix.steps.join(" ")}` : ""}` : "";
|
|
1280
|
+
out.push({
|
|
1281
|
+
name: `[health] ${r.title}`,
|
|
1282
|
+
ok: true,
|
|
1283
|
+
warn: true,
|
|
1284
|
+
detail: r.status === "unknown" ? `Not checked: ${r.detail}` : `${r.detail}${waiting}${fix}`
|
|
1285
|
+
});
|
|
1286
|
+
}
|
|
1287
|
+
const passing = rows.filter((r) => r.status === "ok").length;
|
|
1288
|
+
if (passing > 0) out.push({ name: "[health] Other checks", ok: true, detail: `${passing} passed.` });
|
|
1289
|
+
return out;
|
|
1290
|
+
} catch {
|
|
1291
|
+
return [{ name: "[health] Health check", ok: true, warn: true, detail: "Could not reach /v1/admin/health-checks (timeout); health unknown." }];
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
async function runDoctor(config, options = {}) {
|
|
1295
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
1296
|
+
const checks = [];
|
|
1297
|
+
const isFull = options.full === true;
|
|
1298
|
+
const runServer = isFull || options.server !== false;
|
|
1299
|
+
const runIngest = isFull || options.ingest !== false;
|
|
1300
|
+
const sdkCheck = await checkSdkInstall(options.cwd ?? process.cwd());
|
|
1301
|
+
if (!config.apiKey && !config.projectId && !sdkCheck?.ok && !options.auth && !isFull) {
|
|
1302
|
+
return {
|
|
1303
|
+
ready: false,
|
|
1304
|
+
checks: [
|
|
1305
|
+
{
|
|
1306
|
+
name: "Mushi set up here",
|
|
1307
|
+
ok: false,
|
|
1308
|
+
detail: "Not set up yet \u2014 no saved Mushi credentials and no Mushi SDK in this folder."
|
|
1309
|
+
}
|
|
1310
|
+
]
|
|
1311
|
+
};
|
|
1312
|
+
}
|
|
1313
|
+
checks.push(...checkCliConfig(config));
|
|
1314
|
+
if (config.endpoint) {
|
|
1315
|
+
checks.push(await checkEndpointReachability(config.endpoint, doFetch));
|
|
1316
|
+
}
|
|
1317
|
+
if (sdkCheck) checks.push(sdkCheck);
|
|
1318
|
+
if (sdkCheck?.ok && !sdkCheck.warn) {
|
|
1319
|
+
const { findSdkImport } = await import("./snippet-inject-AVGVHTUJ.js");
|
|
1320
|
+
const imported = await findSdkImport(options.cwd ?? process.cwd());
|
|
1321
|
+
checks.push(
|
|
1322
|
+
imported ? { name: "SDK init snippet wired", ok: true, detail: `Found SDK usage in ${imported.file}` } : {
|
|
1323
|
+
name: "SDK init snippet wired",
|
|
1324
|
+
ok: true,
|
|
1325
|
+
warn: true,
|
|
1326
|
+
detail: "Package installed but no @mushi-mushi import found in src/app \u2014 paste the init snippet from `mushi init` into your entry file."
|
|
1327
|
+
}
|
|
1328
|
+
);
|
|
1329
|
+
}
|
|
1330
|
+
if (runServer) {
|
|
1331
|
+
const serverChecks = await checkServerPreflight(config, doFetch);
|
|
1332
|
+
checks.push(...serverChecks);
|
|
1333
|
+
checks.push(...await checkPipelineDoctor(config, doFetch));
|
|
1334
|
+
checks.push(...await checkHealthRegistry(config, doFetch));
|
|
1335
|
+
}
|
|
1336
|
+
checks.push(...await checkVersionDrift(options.cwd ?? process.cwd(), doFetch));
|
|
1337
|
+
if (runIngest) {
|
|
1338
|
+
const ingestChecks = await checkIngestSetup(config, doFetch);
|
|
1339
|
+
checks.push(...ingestChecks);
|
|
1340
|
+
}
|
|
1341
|
+
if (isFull || options.qaStories) {
|
|
1342
|
+
const qaChecks = await checkQaStoriesHealth(config, doFetch);
|
|
1343
|
+
checks.push(...qaChecks);
|
|
1344
|
+
}
|
|
1345
|
+
if (isFull || options.hostApp) {
|
|
1346
|
+
const hostChecks = await checkHostAppWiring(options.cwd ?? process.cwd());
|
|
1347
|
+
checks.push(...hostChecks);
|
|
1348
|
+
const hashChecks = await checkHashRouterCapture(options.cwd ?? process.cwd());
|
|
1349
|
+
checks.push(...hashChecks);
|
|
1350
|
+
}
|
|
1351
|
+
if (isFull || options.mcp) {
|
|
1352
|
+
const mcpChecks = await checkMcpConfig(config, options.cwd ?? process.cwd(), doFetch);
|
|
1353
|
+
checks.push(...mcpChecks);
|
|
1354
|
+
}
|
|
1355
|
+
if (isFull || options.auth) {
|
|
1356
|
+
checks.push(...await checkCliAuthPath(config, doFetch));
|
|
1357
|
+
}
|
|
1358
|
+
const heartbeatPassed = checks.some((c) => c.name === "[ingest] Last SDK heartbeat" && c.ok);
|
|
1359
|
+
if (heartbeatPassed) {
|
|
1360
|
+
const idx = checks.findIndex((c) => c.name === "SDK installed in this repo" && !c.ok);
|
|
1361
|
+
if (idx >= 0) {
|
|
1362
|
+
checks[idx] = {
|
|
1363
|
+
...checks[idx],
|
|
1364
|
+
ok: true,
|
|
1365
|
+
warn: true,
|
|
1366
|
+
detail: "No mushi-mushi or @mushi-mushi/* package in cwd package.json \u2014 but live heartbeats confirm the SDK is active. Run from your app repo or install with `npx mushi-mushi`."
|
|
1367
|
+
};
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
return { checks, ready: checks.every((c) => c.ok) };
|
|
1371
|
+
}
|
|
1372
|
+
function formatDoctorResult(result) {
|
|
1373
|
+
const PASS = "OK";
|
|
1374
|
+
const WARN = "WARN";
|
|
1375
|
+
const FAIL = "FAIL";
|
|
1376
|
+
const lines = [];
|
|
1377
|
+
const printedHints = /* @__PURE__ */ new Set();
|
|
1378
|
+
for (const c of result.checks) {
|
|
1379
|
+
const icon = !c.ok ? FAIL : c.warn ? WARN : PASS;
|
|
1380
|
+
lines.push(`${icon} ${c.name}`);
|
|
1381
|
+
if (c.detail) lines.push(` ${c.detail}`);
|
|
1382
|
+
if (!c.ok) {
|
|
1383
|
+
const hint = fixHintForCheck(c.name);
|
|
1384
|
+
if (hint && !printedHints.has(hint)) {
|
|
1385
|
+
printedHints.add(hint);
|
|
1386
|
+
lines.push(` \u2192 Fix: ${hint}`);
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
const failed = result.checks.filter((c) => !c.ok);
|
|
1391
|
+
const warned = result.checks.filter((c) => c.ok && c.warn);
|
|
1392
|
+
if (failed.length === 0) {
|
|
1393
|
+
if (warned.length > 0) {
|
|
1394
|
+
lines.push(
|
|
1395
|
+
`
|
|
1396
|
+
All checks passed with ${warned.length} advisory warning${warned.length === 1 ? "" : "s"}. The CLI is ready.`
|
|
1397
|
+
);
|
|
1398
|
+
} else {
|
|
1399
|
+
lines.push("\nAll checks passed. The CLI is ready.");
|
|
1400
|
+
}
|
|
1401
|
+
} else {
|
|
1402
|
+
lines.push(`
|
|
1403
|
+
${failed.length} check${failed.length === 1 ? "" : "s"} failed.`);
|
|
1404
|
+
lines.push("Fix the items above and re-run `mushi doctor`.");
|
|
1405
|
+
}
|
|
1406
|
+
return lines.join("\n");
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
// src/init.ts
|
|
1410
|
+
var NATIVE_FRAMEWORK_IDS = /* @__PURE__ */ new Set(["expo", "react-native", "capacitor"]);
|
|
1411
|
+
var ENV_FILES = [".env.local", ".env"];
|
|
1412
|
+
function isInteractive() {
|
|
1413
|
+
return Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
1414
|
+
}
|
|
1415
|
+
var PROJECT_ID_PATTERN = /^(?:proj_[A-Za-z0-9_-]{10,}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
|
|
1416
|
+
var API_KEY_PATTERN = /^(mushi_|mush_pk_)[A-Za-z0-9_-]{10,}$/;
|
|
1417
|
+
async function runInit(options = {}) {
|
|
1418
|
+
const cwd = options.cwd ?? process.cwd();
|
|
1419
|
+
if (options.audit) {
|
|
1420
|
+
await runInitAudit(cwd);
|
|
1421
|
+
return;
|
|
1422
|
+
}
|
|
1423
|
+
ensureInteractiveOrBailOut(options);
|
|
1424
|
+
if (!isInteractive()) options = { ...options, yes: true };
|
|
1425
|
+
p.intro("Mushi setup");
|
|
1426
|
+
await printFreshnessHint();
|
|
1427
|
+
warnIfWorkspaceRoot(cwd);
|
|
1428
|
+
const pkg = readPackageJson(cwd);
|
|
1429
|
+
maybeSuggestAudit(pkg);
|
|
1430
|
+
if (!pkg) {
|
|
1431
|
+
p.log.warn("No package.json found in this directory.");
|
|
1432
|
+
if (!isInteractive()) {
|
|
1433
|
+
p.cancel("Aborted. Run from your project root, or pass --cwd <path>.");
|
|
1434
|
+
process.exit(1);
|
|
1435
|
+
}
|
|
1436
|
+
const cont = await p.confirm({
|
|
1437
|
+
message: "Continue anyway? (Mushi will install into the current folder)",
|
|
1438
|
+
initialValue: false
|
|
1439
|
+
});
|
|
1440
|
+
if (p.isCancel(cont) || !cont) {
|
|
1441
|
+
p.cancel("Aborted. Run from your project root and try again.");
|
|
1442
|
+
process.exit(0);
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
const detected = detectFramework(cwd, pkg);
|
|
1446
|
+
const framework = await chooseFramework(detected, options);
|
|
1447
|
+
const consoleBase = await resolveConsoleUrl({ cwd });
|
|
1448
|
+
const endpoint = resolveCloudEndpoint(
|
|
1449
|
+
firstEndpoint(options.endpoint, process.env.MUSHI_API_ENDPOINT, loadConfig().endpoint)
|
|
1450
|
+
);
|
|
1451
|
+
options = { ...options, endpoint };
|
|
1452
|
+
const credentials = await acquireCredentials(options, consoleBase, endpoint);
|
|
1453
|
+
await verifyCredentials(credentials, options, consoleBase);
|
|
1454
|
+
const pm = detectPackageManager(cwd);
|
|
1455
|
+
const packagesToInstall = framework.needsWebPackage ? [framework.packageName, "mushi-mushi"] : [framework.packageName];
|
|
1456
|
+
if (!options.skipInstall) {
|
|
1457
|
+
await installPackages(pm, packagesToInstall, cwd);
|
|
1458
|
+
} else {
|
|
1459
|
+
p.log.info(`Skipped install. Run \`${installCommand(pm, packagesToInstall)}\` yourself.`);
|
|
1460
|
+
}
|
|
1461
|
+
const envFile = await writeEnvFile(
|
|
1462
|
+
cwd,
|
|
1463
|
+
credentials.sdkKey,
|
|
1464
|
+
credentials.projectId,
|
|
1465
|
+
framework,
|
|
1466
|
+
endpoint,
|
|
1467
|
+
Boolean(options.yes)
|
|
1468
|
+
);
|
|
1469
|
+
if (!NATIVE_FRAMEWORK_IDS.has(framework.id)) {
|
|
1470
|
+
p.note(
|
|
1471
|
+
hostingEnvHint(envVarsToWrite(credentials.sdkKey, credentials.projectId, framework, endpoint), envFile),
|
|
1472
|
+
"Before you deploy:"
|
|
1473
|
+
);
|
|
1474
|
+
}
|
|
1475
|
+
persistCliConfig(credentials, endpoint);
|
|
1476
|
+
emitWizardFunnelEvent(credentials, endpoint, "wizard_env_written", { framework: framework.id });
|
|
1477
|
+
const enableRewards = await maybeEnableRewards(options);
|
|
1478
|
+
await maybeInjectSnippet(cwd, framework, options);
|
|
1479
|
+
printNextSteps(framework, consoleBase, enableRewards);
|
|
1480
|
+
await maybeSendTestReport(credentials, { ...options, endpoint, consoleBase });
|
|
1481
|
+
await maybeOfferConnect(credentials, options, consoleBase);
|
|
1482
|
+
p.outro("Setup complete.");
|
|
1483
|
+
}
|
|
1484
|
+
async function runInitAudit(cwd) {
|
|
1485
|
+
p.intro("Mushi setup audit");
|
|
1486
|
+
const config = loadConfig();
|
|
1487
|
+
const result = await runDoctor(config, { cwd, hostApp: true, mcp: true });
|
|
1488
|
+
p.log.message(formatDoctorResult(result));
|
|
1489
|
+
if (result.ready) {
|
|
1490
|
+
p.outro("Audit complete \u2014 setup looks healthy.");
|
|
1491
|
+
} else {
|
|
1492
|
+
p.outro("Audit found issues \u2014 each FAIL line above has a \u2192 Fix hint. `mushi doctor --fix` applies the safe ones.");
|
|
1493
|
+
process.exitCode = 1;
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
function maybeSuggestAudit(pkg) {
|
|
1497
|
+
const deps = {
|
|
1498
|
+
...pkg?.dependencies,
|
|
1499
|
+
...pkg?.devDependencies
|
|
1500
|
+
};
|
|
1501
|
+
if (Object.keys(deps).some(isMushiSdkPackage)) {
|
|
1502
|
+
p.log.info(
|
|
1503
|
+
"A Mushi SDK is already installed here. To health-check the existing setup instead, run `npx mushi-mushi --audit`."
|
|
1504
|
+
);
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
function ensureInteractiveOrBailOut(options) {
|
|
1508
|
+
if (isInteractive()) return;
|
|
1509
|
+
if (options.yes) return;
|
|
1510
|
+
if (options.framework && options.projectId && options.apiKey) return;
|
|
1511
|
+
process.stderr.write(
|
|
1512
|
+
"mushi-mushi: non-interactive terminal detected.\nRe-run with --yes to set up without prompts: it reuses the credentials saved by\n`npx mushi-mushi login`, or prints a sign-in URL and waits while you approve it in a browser.\nExample: npx mushi-mushi --yes\nCI with no browser: npx mushi-mushi --yes --project-id <uuid> --api-key <ingest-only key>\n"
|
|
1513
|
+
);
|
|
1514
|
+
process.exit(1);
|
|
1515
|
+
}
|
|
1516
|
+
async function chooseFramework(detected, options) {
|
|
1517
|
+
if (options.framework) {
|
|
1518
|
+
const explicit = FRAMEWORKS[options.framework];
|
|
1519
|
+
if (!explicit) throw new Error(`Unknown framework: ${options.framework}`);
|
|
1520
|
+
p.log.step(`Using framework: ${explicit.label} (from --framework)`);
|
|
1521
|
+
return explicit;
|
|
1522
|
+
}
|
|
1523
|
+
if (options.yes) {
|
|
1524
|
+
p.log.step(`Detected ${detected.label} \u2192 installing ${detected.packageName}`);
|
|
1525
|
+
return detected;
|
|
1526
|
+
}
|
|
1527
|
+
const confirmed = await p.select({
|
|
1528
|
+
message: `Detected ${detected.label}. Use this?`,
|
|
1529
|
+
initialValue: detected.id,
|
|
1530
|
+
options: Object.values(FRAMEWORKS).map((fw) => ({
|
|
1531
|
+
value: fw.id,
|
|
1532
|
+
label: `${fw.id === detected.id ? "\u2713 " : " "}${fw.label}`,
|
|
1533
|
+
hint: fw.importPath
|
|
1534
|
+
}))
|
|
1535
|
+
});
|
|
1536
|
+
if (p.isCancel(confirmed)) {
|
|
1537
|
+
p.cancel("Aborted.");
|
|
1538
|
+
process.exit(0);
|
|
1539
|
+
}
|
|
1540
|
+
return FRAMEWORKS[confirmed];
|
|
1541
|
+
}
|
|
1542
|
+
async function acquireCredentials(options, consoleBase, endpoint) {
|
|
1543
|
+
const probe = (e, k, pid) => probeKeyScope(e, k, pid);
|
|
1544
|
+
if (options.projectId && options.apiKey) {
|
|
1545
|
+
const projectId = sanitizeSecret(options.projectId);
|
|
1546
|
+
const sdkKey = sanitizeSecret(options.apiKey);
|
|
1547
|
+
await assertUserKeyIsIngestOnly(sdkKey, projectId, endpoint, probe);
|
|
1548
|
+
return { projectId, sdkKey };
|
|
1549
|
+
}
|
|
1550
|
+
const existing = loadConfig();
|
|
1551
|
+
maybeShowTelemetryNotice(existing);
|
|
1552
|
+
let browserTried = false;
|
|
1553
|
+
if (!options.projectId && !options.apiKey && existing.projectId && existing.apiKey) {
|
|
1554
|
+
const reuse = options.yes ? true : await p.confirm({
|
|
1555
|
+
message: "Use the Mushi credentials saved from your last sign-in?",
|
|
1556
|
+
initialValue: true
|
|
1557
|
+
});
|
|
1558
|
+
if (p.isCancel(reuse)) {
|
|
1559
|
+
p.cancel("Aborted.");
|
|
1560
|
+
process.exit(0);
|
|
1561
|
+
}
|
|
1562
|
+
if (reuse) {
|
|
1563
|
+
const saved = await resolveSavedCredentials(
|
|
1564
|
+
{ projectId: existing.projectId, apiKey: existing.apiKey, sdkKey: existing.sdkKey },
|
|
1565
|
+
endpoint,
|
|
1566
|
+
probe
|
|
1567
|
+
);
|
|
1568
|
+
if (saved.kind === "ready") return saved.credentials;
|
|
1569
|
+
if (saved.kind === "needs-sdk-key") {
|
|
1570
|
+
p.log.info(
|
|
1571
|
+
"Your saved sign-in key can read bug reports, so it stays in the CLI config. Approve one browser sign-in to mint a separate ingest-only key for the app's env vars."
|
|
1572
|
+
);
|
|
1573
|
+
browserTried = true;
|
|
1574
|
+
const creds = await runBrowserSignIn(options, endpoint, consoleBase, {
|
|
1575
|
+
projectId: saved.projectId,
|
|
1576
|
+
cliKey: saved.cliKey
|
|
1577
|
+
});
|
|
1578
|
+
if (creds) return creds;
|
|
1579
|
+
} else {
|
|
1580
|
+
p.log.warn(`Saved credentials can't be reused (${saved.reason}) \u2014 signing in again.`);
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
if (browserTried) {
|
|
1585
|
+
p.log.warn(
|
|
1586
|
+
"Browser sign-in didn't complete \u2014 switching to manual entry. Run `npx mushi-mushi doctor --auth` to diagnose the sign-in path."
|
|
1587
|
+
);
|
|
1588
|
+
} else if (options.yes) {
|
|
1589
|
+
const creds = await runBrowserSignIn(options, endpoint, consoleBase);
|
|
1590
|
+
if (creds) return creds;
|
|
1591
|
+
p.log.warn(
|
|
1592
|
+
"Browser sign-in didn't complete \u2014 switching to manual entry. Run `npx mushi-mushi doctor --auth` to diagnose the sign-in path."
|
|
1593
|
+
);
|
|
1594
|
+
} else {
|
|
1595
|
+
const method = await p.select({
|
|
1596
|
+
message: "Connect this app to Mushi",
|
|
1597
|
+
initialValue: "browser",
|
|
1598
|
+
options: [
|
|
1599
|
+
{
|
|
1600
|
+
value: "browser",
|
|
1601
|
+
label: "Sign in with your browser",
|
|
1602
|
+
hint: "Recommended \u2014 no copy-paste, creates the project + key for you"
|
|
1603
|
+
},
|
|
1604
|
+
{
|
|
1605
|
+
value: "manual",
|
|
1606
|
+
label: "Paste a Project ID + API key",
|
|
1607
|
+
hint: "Self-hosted or expert setup \u2014 run npx mushi-mushi (not mushi setup)"
|
|
1608
|
+
}
|
|
1609
|
+
]
|
|
1610
|
+
});
|
|
1611
|
+
if (p.isCancel(method)) {
|
|
1612
|
+
p.cancel("Aborted.");
|
|
1613
|
+
process.exit(0);
|
|
1614
|
+
}
|
|
1615
|
+
if (method === "browser") {
|
|
1616
|
+
const creds = await runBrowserSignIn(options, endpoint, consoleBase);
|
|
1617
|
+
if (creds) return creds;
|
|
1618
|
+
p.log.warn(
|
|
1619
|
+
"Browser sign-in didn't complete \u2014 switching to manual entry. Run `npx mushi-mushi doctor --auth` to diagnose the sign-in path."
|
|
1620
|
+
);
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
return collectCredentialsManually(options, consoleBase, endpoint, probe);
|
|
1624
|
+
}
|
|
1625
|
+
async function assertUserKeyIsIngestOnly(key, projectId, endpoint, probe) {
|
|
1626
|
+
const result = await probe(endpoint, key, projectId);
|
|
1627
|
+
if (result.result === "mcp" || result.result === "unknown") {
|
|
1628
|
+
throw new Error(
|
|
1629
|
+
`Not writing this API key into your app's env vars: ${describeUnsafeSdkKey(result, endpoint)}. Use an ingest-only (report:write) key from the console, or leave out --api-key to sign in with the browser, which mints one.`
|
|
1630
|
+
);
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
async function resolveSavedCredentials(saved, endpoint, probe) {
|
|
1634
|
+
const projectId = sanitizeSecret(saved.projectId);
|
|
1635
|
+
const apiKey = sanitizeSecret(saved.apiKey);
|
|
1636
|
+
const savedSdkKey = savedSdkKeyFor(saved, projectId);
|
|
1637
|
+
if (savedSdkKey) {
|
|
1638
|
+
const sdkProbe = await probe(endpoint, savedSdkKey, projectId);
|
|
1639
|
+
if (sdkProbe.result === "ingest-only") {
|
|
1640
|
+
return { kind: "ready", credentials: { projectId, sdkKey: savedSdkKey, cliKey: apiKey } };
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
const cliProbe = await probe(endpoint, apiKey, projectId);
|
|
1644
|
+
if (cliProbe.result === "ingest-only") {
|
|
1645
|
+
return { kind: "ready", credentials: { projectId, sdkKey: apiKey } };
|
|
1646
|
+
}
|
|
1647
|
+
if (cliProbe.result === "mcp") {
|
|
1648
|
+
return { kind: "needs-sdk-key", projectId, cliKey: apiKey };
|
|
1649
|
+
}
|
|
1650
|
+
return { kind: "unusable", reason: describeUnsafeSdkKey(cliProbe, endpoint) };
|
|
1651
|
+
}
|
|
1652
|
+
async function mintWizardKeys(deps, args) {
|
|
1653
|
+
let projectId;
|
|
1654
|
+
let createdName;
|
|
1655
|
+
let sdkKey = null;
|
|
1656
|
+
if (args.target.kind === "new") {
|
|
1657
|
+
const created = await deps.createProject(args.endpoint, args.cliToken, args.target.name, {
|
|
1658
|
+
scopes: SDK_KEY_SCOPES
|
|
1659
|
+
});
|
|
1660
|
+
projectId = created.id;
|
|
1661
|
+
createdName = created.name;
|
|
1662
|
+
sdkKey = created.apiKey;
|
|
1663
|
+
} else {
|
|
1664
|
+
projectId = args.target.projectId;
|
|
1665
|
+
}
|
|
1666
|
+
if (!sdkKey) {
|
|
1667
|
+
sdkKey = await deps.mintProjectKey(args.endpoint, args.cliToken, projectId, {
|
|
1668
|
+
scopes: SDK_KEY_SCOPES,
|
|
1669
|
+
label: SDK_KEY_LABEL
|
|
1670
|
+
});
|
|
1671
|
+
}
|
|
1672
|
+
let cliKey;
|
|
1673
|
+
let cliKeyError;
|
|
1674
|
+
if (args.withCliKey) {
|
|
1675
|
+
try {
|
|
1676
|
+
cliKey = await deps.mintProjectKey(args.endpoint, args.cliToken, projectId, {
|
|
1677
|
+
scopes: CLI_KEY_SCOPES,
|
|
1678
|
+
label: CLI_KEY_LABEL
|
|
1679
|
+
});
|
|
1680
|
+
} catch (err) {
|
|
1681
|
+
cliKeyError = err instanceof Error ? err.message : String(err);
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
return { projectId, createdName, sdkKey, cliKey, cliKeyError };
|
|
1685
|
+
}
|
|
1686
|
+
async function runBrowserSignIn(options, endpoint, consoleBase, preset) {
|
|
1687
|
+
const startSpin = p.spinner();
|
|
1688
|
+
startSpin.start("Starting secure browser sign-in\u2026");
|
|
1689
|
+
let session;
|
|
1690
|
+
try {
|
|
1691
|
+
session = await startDeviceAuth(endpoint, ensureClientId());
|
|
1692
|
+
} catch (err) {
|
|
1693
|
+
startSpin.stop("Could not start browser sign-in.");
|
|
1694
|
+
p.log.warn(err instanceof Error ? err.message : String(err));
|
|
1695
|
+
return null;
|
|
1696
|
+
}
|
|
1697
|
+
startSpin.stop("Browser sign-in ready.");
|
|
1698
|
+
try {
|
|
1699
|
+
await openInBrowser(session.verification_uri);
|
|
1700
|
+
} catch {
|
|
1701
|
+
}
|
|
1702
|
+
printAuthBanner(session.user_code, session.verification_uri);
|
|
1703
|
+
const waitSpin = p.spinner();
|
|
1704
|
+
waitSpin.start("Waiting for you to approve in the browser\u2026");
|
|
1705
|
+
let cliToken;
|
|
1706
|
+
try {
|
|
1707
|
+
cliToken = await waitForCliToken(endpoint, session);
|
|
1708
|
+
} catch (err) {
|
|
1709
|
+
waitSpin.stop("Browser sign-in didn't complete.");
|
|
1710
|
+
p.log.warn(err instanceof Error ? err.message : String(err));
|
|
1711
|
+
return null;
|
|
1712
|
+
}
|
|
1713
|
+
waitSpin.stop("Approved.");
|
|
1714
|
+
const presetProjectId = preset?.projectId ?? (options.projectId ? sanitizeSecret(options.projectId) : void 0);
|
|
1715
|
+
let target;
|
|
1716
|
+
if (presetProjectId) {
|
|
1717
|
+
target = { kind: "existing", projectId: presetProjectId };
|
|
1718
|
+
} else {
|
|
1719
|
+
let projects = [];
|
|
1720
|
+
const fetchSpin = p.spinner();
|
|
1721
|
+
fetchSpin.start("Loading your projects\u2026");
|
|
1722
|
+
try {
|
|
1723
|
+
projects = await listProjects(endpoint, cliToken);
|
|
1724
|
+
fetchSpin.stop(
|
|
1725
|
+
projects.length > 0 ? `Found ${projects.length} project(s).` : "No projects yet."
|
|
1726
|
+
);
|
|
1727
|
+
} catch (err) {
|
|
1728
|
+
if (!isInteractive()) {
|
|
1729
|
+
fetchSpin.stop("Could not load projects.");
|
|
1730
|
+
p.log.warn(err instanceof Error ? err.message : String(err));
|
|
1731
|
+
return null;
|
|
1732
|
+
}
|
|
1733
|
+
fetchSpin.stop("Could not load projects \u2014 you can still create a new one.");
|
|
1734
|
+
p.log.warn(err instanceof Error ? err.message : String(err));
|
|
1735
|
+
}
|
|
1736
|
+
if (!isInteractive()) {
|
|
1737
|
+
const cwd = options.cwd ?? process.cwd();
|
|
1738
|
+
const choice = chooseProjectNonInteractive(
|
|
1739
|
+
projects,
|
|
1740
|
+
defaultProjectName(readPackageJson(cwd)?.name, cwd)
|
|
1741
|
+
);
|
|
1742
|
+
if (choice.kind === "existing") {
|
|
1743
|
+
p.log.info(`Using project "${choice.name}" (matches this app \u2014 pass --project-id to pick another).`);
|
|
1744
|
+
target = { kind: "existing", projectId: choice.id };
|
|
1745
|
+
} else {
|
|
1746
|
+
p.log.info(`Creating project "${choice.name}" (no project matches this app \u2014 pass --project-id to use an existing one).`);
|
|
1747
|
+
target = { kind: "new", name: choice.name };
|
|
1748
|
+
}
|
|
1749
|
+
} else {
|
|
1750
|
+
const NEW = "__new__";
|
|
1751
|
+
const choice = await p.select({
|
|
1752
|
+
message: "Choose a project",
|
|
1753
|
+
initialValue: projects[0]?.id ?? NEW,
|
|
1754
|
+
options: [
|
|
1755
|
+
...projects.map((pr) => ({ value: pr.id, label: pr.name, hint: pr.id.slice(0, 8) })),
|
|
1756
|
+
{ value: NEW, label: "Create a new project", hint: "mints an SDK key automatically" }
|
|
1757
|
+
]
|
|
1758
|
+
});
|
|
1759
|
+
if (p.isCancel(choice)) {
|
|
1760
|
+
p.cancel("Aborted.");
|
|
1761
|
+
process.exit(0);
|
|
1762
|
+
}
|
|
1763
|
+
if (choice === NEW) {
|
|
1764
|
+
const name = await p.text({
|
|
1765
|
+
message: "Project name",
|
|
1766
|
+
placeholder: "My app",
|
|
1767
|
+
validate: (v) => v && v.trim().length > 0 ? void 0 : "Required"
|
|
1768
|
+
});
|
|
1769
|
+
if (p.isCancel(name)) {
|
|
1770
|
+
p.cancel("Aborted.");
|
|
1771
|
+
process.exit(0);
|
|
1772
|
+
}
|
|
1773
|
+
target = { kind: "new", name: name.trim() };
|
|
1774
|
+
} else {
|
|
1775
|
+
target = { kind: "existing", projectId: choice };
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
const keySpin = p.spinner();
|
|
1780
|
+
keySpin.start(target.kind === "new" ? `Creating "${target.name}"\u2026` : "Minting keys\u2026");
|
|
1781
|
+
let minted;
|
|
1782
|
+
try {
|
|
1783
|
+
minted = await mintWizardKeys(
|
|
1784
|
+
{ createProject, mintProjectKey },
|
|
1785
|
+
{ endpoint, cliToken, target, withCliKey: !preset }
|
|
1786
|
+
);
|
|
1787
|
+
} catch (err) {
|
|
1788
|
+
keySpin.stop(target.kind === "new" ? "Could not create the project." : "Could not mint an API key.");
|
|
1789
|
+
p.log.warn(err instanceof Error ? err.message : String(err));
|
|
1790
|
+
if (target.kind === "existing") {
|
|
1791
|
+
p.log.warn(
|
|
1792
|
+
`You're signed in, but key minting failed. Generate one manually in the console Verify tab: ${consoleUrl(consoleBase, "/onboarding?tab=verify")}`
|
|
1793
|
+
);
|
|
1794
|
+
}
|
|
1795
|
+
return null;
|
|
1796
|
+
}
|
|
1797
|
+
keySpin.stop(
|
|
1798
|
+
minted.createdName ? `Created project "${minted.createdName}" with an ingest-only SDK key.` : "SDK key ready (ingest-only)."
|
|
1799
|
+
);
|
|
1800
|
+
if (minted.cliKeyError) {
|
|
1801
|
+
p.log.warn(
|
|
1802
|
+
`The CLI/MCP key could not be minted (${minted.cliKeyError}). The SDK install continues; run \`npx mushi-mushi login\` later for MCP and admin commands.`
|
|
1803
|
+
);
|
|
1804
|
+
}
|
|
1805
|
+
return {
|
|
1806
|
+
projectId: minted.projectId,
|
|
1807
|
+
sdkKey: minted.sdkKey,
|
|
1808
|
+
cliKey: preset?.cliKey ?? minted.cliKey
|
|
1809
|
+
};
|
|
1810
|
+
}
|
|
1811
|
+
async function collectCredentialsManually(options, consoleBase, endpoint, probe) {
|
|
1812
|
+
const existing = loadConfig();
|
|
1813
|
+
let savedProjectId = existing.projectId;
|
|
1814
|
+
let savedApiKey;
|
|
1815
|
+
if (!isInteractive() && !(options.projectId && options.apiKey)) {
|
|
1816
|
+
throw new Error(
|
|
1817
|
+
"Browser sign-in didn't complete and this terminal cannot prompt for a key. Re-run `npx mushi-mushi --yes` and approve the sign-in in the browser, or pass --project-id and an ingest-only --api-key."
|
|
1818
|
+
);
|
|
1819
|
+
}
|
|
1820
|
+
if (!options.projectId && !options.apiKey && savedProjectId && existing.apiKey) {
|
|
1821
|
+
const projectIdForCheck = sanitizeSecret(savedProjectId);
|
|
1822
|
+
const candidate = savedSdkKeyFor(existing, projectIdForCheck) ?? sanitizeSecret(existing.apiKey);
|
|
1823
|
+
p.log.info(
|
|
1824
|
+
`Found saved credentials from a previous sign-in (project ${projectIdForCheck.slice(0, 8)}\u2026).`
|
|
1825
|
+
);
|
|
1826
|
+
const checkSpin = p.spinner();
|
|
1827
|
+
checkSpin.start("Checking saved credentials\u2026");
|
|
1828
|
+
const check = await probe(endpoint, candidate, projectIdForCheck);
|
|
1829
|
+
if (check.result === "ingest-only") {
|
|
1830
|
+
checkSpin.stop("Saved ingest key still works.");
|
|
1831
|
+
savedApiKey = candidate;
|
|
1832
|
+
} else if (check.result === "mcp") {
|
|
1833
|
+
checkSpin.stop("Saved key can read reports, so it can't go into your app's env \u2014 paste an ingest-only key below.");
|
|
1834
|
+
} else if (check.result === "invalid") {
|
|
1835
|
+
checkSpin.stop("Saved credentials no longer authenticate \u2014 enter fresh ones below.");
|
|
1836
|
+
savedProjectId = void 0;
|
|
1837
|
+
} else {
|
|
1838
|
+
checkSpin.stop(`Could not check the saved key (${describeUnsafeSdkKey(check, endpoint)}) \u2014 enter one below.`);
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
const rawProjectId = options.projectId ?? savedProjectId ?? await promptText({
|
|
1842
|
+
message: "Project ID",
|
|
1843
|
+
placeholder: "e.g. bdafa28d-b153-482f-bd4f-42981f3fd3a4",
|
|
1844
|
+
hint: projectIdHint(consoleBase),
|
|
1845
|
+
validate: (v) => PROJECT_ID_PATTERN.test(v.trim()) ? void 0 : "Expected a UUID \u2014 copy it from the Projects page or the panel right after you create a project."
|
|
1846
|
+
});
|
|
1847
|
+
const rawApiKey = options.apiKey ?? savedApiKey ?? await promptText({
|
|
1848
|
+
message: "API key",
|
|
1849
|
+
placeholder: "mushi_xxxxxxxxxxxx",
|
|
1850
|
+
hint: apiKeyHint(consoleBase),
|
|
1851
|
+
validate: (v) => API_KEY_PATTERN.test(v) ? void 0 : "Expected format: mushi_ followed by 10+ alphanumeric characters"
|
|
1852
|
+
});
|
|
1853
|
+
const projectId = sanitizeSecret(rawProjectId);
|
|
1854
|
+
const apiKey = sanitizeSecret(rawApiKey);
|
|
1855
|
+
if (!PROJECT_ID_PATTERN.test(projectId)) {
|
|
1856
|
+
throw new Error(
|
|
1857
|
+
`Invalid project ID. Expected a UUID (e.g. bdafa28d-b153-482f-bd4f-42981f3fd3a4) or the proj_* prefixed form. Got: ${redact(projectId)} \u2014 copy it from ${projectIdHint(consoleBase)}`
|
|
1858
|
+
);
|
|
1859
|
+
}
|
|
1860
|
+
if (!API_KEY_PATTERN.test(apiKey)) {
|
|
1861
|
+
throw new Error(
|
|
1862
|
+
`Invalid API key. Expected format: mushi_[A-Za-z0-9_-]{10,}. Got: ${redact(apiKey)}`
|
|
1863
|
+
);
|
|
1864
|
+
}
|
|
1865
|
+
if (apiKey !== savedApiKey) {
|
|
1866
|
+
await assertUserKeyIsIngestOnly(apiKey, projectId, endpoint, probe);
|
|
1867
|
+
}
|
|
1868
|
+
return { projectId, sdkKey: apiKey };
|
|
1869
|
+
}
|
|
1870
|
+
async function verifyCredentials(credentials, options, consoleBase) {
|
|
1871
|
+
const endpoint = resolveCloudEndpoint(options.endpoint);
|
|
1872
|
+
const spinner2 = p.spinner();
|
|
1873
|
+
spinner2.start("Verifying credentials\u2026");
|
|
1874
|
+
const result = await apiCall("/v1/sync/whoami", {
|
|
1875
|
+
apiKey: credentials.sdkKey,
|
|
1876
|
+
projectId: credentials.projectId,
|
|
1877
|
+
endpoint
|
|
1878
|
+
});
|
|
1879
|
+
if (!result.ok && (result.error.code === "NETWORK_ERROR" || result.error.code === "TIMEOUT")) {
|
|
1880
|
+
spinner2.stop(`Could not reach ${endpoint}.`);
|
|
1881
|
+
p.log.error(result.error.message);
|
|
1882
|
+
p.log.warn("Setup did NOT complete: nothing was installed and no env vars were written.");
|
|
1883
|
+
p.log.info(
|
|
1884
|
+
"Check your network, proxy or VPN, or pass --endpoint <url> if you run a self-hosted backend, then re-run `npx mushi-mushi`."
|
|
1885
|
+
);
|
|
1886
|
+
throw new Error(`Could not reach the Mushi API at ${endpoint} \u2014 nothing was changed.`);
|
|
1887
|
+
}
|
|
1888
|
+
if (!result.ok) {
|
|
1889
|
+
spinner2.stop("Credentials could not be verified.");
|
|
1890
|
+
p.log.error(result.error?.message ?? "Authentication failed.");
|
|
1891
|
+
p.log.warn("Setup did NOT complete: nothing was installed and no env vars were written.");
|
|
1892
|
+
p.log.info(
|
|
1893
|
+
[
|
|
1894
|
+
"To recover:",
|
|
1895
|
+
' \u2022 Re-run `npx mushi-mushi` and choose "Sign in with your browser", or',
|
|
1896
|
+
` \u2022 Double-check the Project ID / API key in the console: ${cliSetupDeepLink(consoleBase)}`
|
|
1897
|
+
].join("\n")
|
|
1898
|
+
);
|
|
1899
|
+
throw new Error("Credential verification failed \u2014 fix Project ID / API key and re-run.");
|
|
1900
|
+
}
|
|
1901
|
+
if (result.data.project_id && result.data.project_id !== credentials.projectId) {
|
|
1902
|
+
p.log.warn(
|
|
1903
|
+
`Project ID ${redact(credentials.projectId)} doesn't match this API key's project \u2014 using the key's actual project (${result.data.project_name}) instead.`
|
|
1904
|
+
);
|
|
1905
|
+
credentials.projectId = result.data.project_id;
|
|
1906
|
+
}
|
|
1907
|
+
spinner2.stop(`Connected to ${result.data.project_name}`);
|
|
1908
|
+
}
|
|
1909
|
+
function sanitizeSecret(raw) {
|
|
1910
|
+
return raw.trim().replace(/^['"]|['"]$/g, "").replace(/[\r\n\0]/g, "");
|
|
1911
|
+
}
|
|
1912
|
+
function redact(value) {
|
|
1913
|
+
if (value.length <= 8) return "***";
|
|
1914
|
+
return `${value.slice(0, 4)}\u2026${value.slice(-2)}`;
|
|
1915
|
+
}
|
|
1916
|
+
async function promptText(opts) {
|
|
1917
|
+
if (opts.hint) p.log.info(opts.hint);
|
|
1918
|
+
const value = await p.text({
|
|
1919
|
+
message: opts.message,
|
|
1920
|
+
placeholder: opts.placeholder,
|
|
1921
|
+
// @clack/prompts v1 widened the validate input to `string | undefined`
|
|
1922
|
+
// (the previous v0.x API guaranteed a string). Guard the empty case
|
|
1923
|
+
// explicitly so the rest of the pipeline keeps its `string` invariant.
|
|
1924
|
+
validate: (v) => {
|
|
1925
|
+
const clean = sanitizeSecret(v ?? "");
|
|
1926
|
+
if (clean.length === 0) return "Required";
|
|
1927
|
+
return opts.validate ? opts.validate(clean) : void 0;
|
|
1928
|
+
}
|
|
1929
|
+
});
|
|
1930
|
+
if (p.isCancel(value)) {
|
|
1931
|
+
p.cancel("Aborted.");
|
|
1932
|
+
process.exit(0);
|
|
1933
|
+
}
|
|
1934
|
+
return value;
|
|
1935
|
+
}
|
|
1936
|
+
async function installPackages(pm, packages, cwd) {
|
|
1937
|
+
const command = installCommand(pm, packages);
|
|
1938
|
+
const spinner2 = p.spinner();
|
|
1939
|
+
spinner2.start(`Installing ${packages.join(", ")} via ${pm}\u2026`);
|
|
1940
|
+
try {
|
|
1941
|
+
await runCommand(pm, packages, cwd);
|
|
1942
|
+
spinner2.stop(`Installed ${packages.join(", ")}`);
|
|
1943
|
+
} catch (err) {
|
|
1944
|
+
spinner2.stop(`Install failed \u2014 run \`${command}\` manually.`);
|
|
1945
|
+
p.log.error(err instanceof Error ? err.name + ": " + err.message : String(err));
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
function runCommand(pm, packages, cwd) {
|
|
1949
|
+
const verb = pm === "npm" ? "install" : "add";
|
|
1950
|
+
const command = process.platform === "win32" ? `${pm}.cmd` : pm;
|
|
1951
|
+
return new Promise((resolve2, reject) => {
|
|
1952
|
+
const child = spawn(command, [verb, ...packages], {
|
|
1953
|
+
stdio: "inherit",
|
|
1954
|
+
shell: false,
|
|
1955
|
+
cwd,
|
|
1956
|
+
env: process.env
|
|
1957
|
+
});
|
|
1958
|
+
child.on("error", reject);
|
|
1959
|
+
child.on("exit", (code) => {
|
|
1960
|
+
if (code === 0) resolve2();
|
|
1961
|
+
else reject(new Error(`${pm} exited with code ${code ?? "null"}`));
|
|
1962
|
+
});
|
|
1963
|
+
});
|
|
1964
|
+
}
|
|
1965
|
+
async function writeEnvFile(cwd, apiKey, projectId, framework, endpoint, overwrite) {
|
|
1966
|
+
const target = ENV_FILES.find((f) => existsSync2(join2(cwd, f))) ?? ENV_FILES[0];
|
|
1967
|
+
const targetPath = join2(cwd, target);
|
|
1968
|
+
const newVars = envVarsToWrite(apiKey, projectId, framework, endpoint);
|
|
1969
|
+
let existing = "";
|
|
1970
|
+
try {
|
|
1971
|
+
existing = readFileSync2(targetPath, "utf-8");
|
|
1972
|
+
} catch {
|
|
1973
|
+
existing = "";
|
|
1974
|
+
}
|
|
1975
|
+
if (existing.includes("MUSHI_PROJECT_ID")) {
|
|
1976
|
+
let shouldOverwrite = overwrite;
|
|
1977
|
+
if (!shouldOverwrite) {
|
|
1978
|
+
const answer = await p.confirm({
|
|
1979
|
+
message: `Existing MUSHI_* vars found in ${target}. Update with new credentials?`,
|
|
1980
|
+
initialValue: true
|
|
1981
|
+
});
|
|
1982
|
+
if (p.isCancel(answer)) {
|
|
1983
|
+
p.log.info(`Kept existing env vars in ${target}.`);
|
|
1984
|
+
return target;
|
|
1985
|
+
}
|
|
1986
|
+
shouldOverwrite = Boolean(answer);
|
|
1987
|
+
}
|
|
1988
|
+
if (!shouldOverwrite) {
|
|
1989
|
+
p.log.info(`Kept existing env vars in ${target}. Re-run and confirm to overwrite.`);
|
|
1990
|
+
return target;
|
|
1991
|
+
}
|
|
1992
|
+
const MUSHI_LINE_RE = /^(NEXT_PUBLIC_|NUXT_PUBLIC_|VITE_|EXPO_PUBLIC_)?MUSHI_[A-Z_]+=.*/gm;
|
|
1993
|
+
const stripped = existing.replace(MUSHI_LINE_RE, "").replace(/\n{3,}/g, "\n\n").trimEnd();
|
|
1994
|
+
const prefix2 = stripped.length > 0 ? "\n" : "";
|
|
1995
|
+
writeFileSync(targetPath, `${stripped}${prefix2}
|
|
1996
|
+
# Mushi Mushi
|
|
1997
|
+
${newVars}
|
|
1998
|
+
`);
|
|
1999
|
+
p.log.success(`Updated MUSHI_* env vars in ${target}`);
|
|
2000
|
+
warnIfMissingFromGitignore(cwd, target);
|
|
2001
|
+
return target;
|
|
2002
|
+
}
|
|
2003
|
+
const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
|
|
2004
|
+
appendFileSync(targetPath, `${prefix}
|
|
2005
|
+
# Mushi Mushi
|
|
2006
|
+
${newVars}
|
|
2007
|
+
`);
|
|
2008
|
+
p.log.success(`Wrote env vars to ${target}`);
|
|
2009
|
+
warnIfMissingFromGitignore(cwd, target);
|
|
2010
|
+
return target;
|
|
2011
|
+
}
|
|
2012
|
+
function isEnvFileCoveredByGitignore(gitignoreContent, envFile) {
|
|
2013
|
+
const lines = gitignoreContent.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
|
|
2014
|
+
let covered = false;
|
|
2015
|
+
for (const line of lines) {
|
|
2016
|
+
if (line.startsWith("!")) {
|
|
2017
|
+
if (matchesGitignorePattern(line.slice(1), envFile)) covered = false;
|
|
2018
|
+
continue;
|
|
2019
|
+
}
|
|
2020
|
+
if (matchesGitignorePattern(line, envFile)) covered = true;
|
|
2021
|
+
}
|
|
2022
|
+
return covered;
|
|
2023
|
+
}
|
|
2024
|
+
function matchesGitignorePattern(pattern, filename) {
|
|
2025
|
+
if (pattern.endsWith("/")) return false;
|
|
2026
|
+
const normalized = pattern.startsWith("/") ? pattern.slice(1) : pattern;
|
|
2027
|
+
const regexSource = normalized.split("").map((ch) => ch === "*" ? "[^/]*" : escapeRegexChar(ch)).join("");
|
|
2028
|
+
return new RegExp(`^${regexSource}$`).test(filename);
|
|
2029
|
+
}
|
|
2030
|
+
function escapeRegexChar(ch) {
|
|
2031
|
+
return /[-/\\^$+?.()|[\]{}]/.test(ch) ? `\\${ch}` : ch;
|
|
2032
|
+
}
|
|
2033
|
+
function warnIfMissingFromGitignore(cwd, envFile) {
|
|
2034
|
+
const gitignorePath = join2(cwd, ".gitignore");
|
|
2035
|
+
if (!existsSync2(gitignorePath)) {
|
|
2036
|
+
p.log.warn(`No .gitignore found \u2014 make sure ${envFile} is not committed.`);
|
|
2037
|
+
return;
|
|
2038
|
+
}
|
|
2039
|
+
const content = readFileSync2(gitignorePath, "utf-8");
|
|
2040
|
+
if (!isEnvFileCoveredByGitignore(content, envFile)) {
|
|
2041
|
+
p.log.warn(`${envFile} is not in .gitignore \u2014 add it before committing.`);
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
2044
|
+
function planCliConfigUpdate(existing, credentials, endpoint) {
|
|
2045
|
+
const keepSavedKey = existing.projectId === credentials.projectId && Boolean(existing.apiKey);
|
|
2046
|
+
const apiKey = credentials.cliKey ?? (keepSavedKey ? existing.apiKey : credentials.sdkKey);
|
|
2047
|
+
return {
|
|
2048
|
+
...existing,
|
|
2049
|
+
apiKey,
|
|
2050
|
+
projectId: credentials.projectId,
|
|
2051
|
+
endpoint,
|
|
2052
|
+
sdkKey: { projectId: credentials.projectId, key: credentials.sdkKey }
|
|
2053
|
+
};
|
|
2054
|
+
}
|
|
2055
|
+
function persistCliConfig(credentials, endpoint) {
|
|
2056
|
+
const existing = loadConfig();
|
|
2057
|
+
const next = planCliConfigUpdate(existing, credentials, endpoint);
|
|
2058
|
+
saveConfig(next);
|
|
2059
|
+
if (next.apiKey && next.apiKey !== existing.apiKey) {
|
|
2060
|
+
trySaveKeyToKeychain(next.apiKey, resolveProfileName());
|
|
2061
|
+
}
|
|
2062
|
+
}
|
|
2063
|
+
function emitWizardFunnelEvent(credentials, endpoint, event, metadata = {}) {
|
|
2064
|
+
if (process.env.MUSHI_NO_TELEMETRY) return;
|
|
2065
|
+
void fetch(`${endpoint.replace(/\/$/, "")}/v1/cli/funnel`, {
|
|
2066
|
+
method: "POST",
|
|
2067
|
+
headers: {
|
|
2068
|
+
"Content-Type": "application/json",
|
|
2069
|
+
"X-Mushi-Api-Key": credentials.sdkKey,
|
|
2070
|
+
"X-Mushi-Project": credentials.projectId
|
|
2071
|
+
},
|
|
2072
|
+
body: JSON.stringify({ event, source: "cli", metadata }),
|
|
2073
|
+
signal: AbortSignal.timeout(4e3)
|
|
2074
|
+
}).catch(() => {
|
|
2075
|
+
});
|
|
2076
|
+
}
|
|
2077
|
+
async function maybeInjectSnippet(cwd, framework, options) {
|
|
2078
|
+
if (options.yes || !process.stdin.isTTY) return;
|
|
2079
|
+
const { ENTRY_CANDIDATES, injectSnippet, MUSHI_MARKER_START } = await import("./snippet-inject-AVGVHTUJ.js");
|
|
2080
|
+
const candidates = ENTRY_CANDIDATES[framework.id];
|
|
2081
|
+
if (!candidates) return;
|
|
2082
|
+
const { readFile, writeFile } = await import("fs/promises");
|
|
2083
|
+
const nodePath = await import("path");
|
|
2084
|
+
for (const rel of candidates) {
|
|
2085
|
+
const abs = nodePath.join(cwd, rel);
|
|
2086
|
+
let source;
|
|
2087
|
+
try {
|
|
2088
|
+
source = await readFile(abs, "utf8");
|
|
2089
|
+
} catch {
|
|
2090
|
+
continue;
|
|
2091
|
+
}
|
|
2092
|
+
const alreadyInjected = source.includes(MUSHI_MARKER_START);
|
|
2093
|
+
const confirmed = await p.confirm({
|
|
2094
|
+
message: alreadyInjected ? `Refresh the Mushi init block in ${rel}?` : `Add the Mushi init snippet to ${rel}? (wrapped in markers; re-runs update in place)`
|
|
2095
|
+
});
|
|
2096
|
+
if (p.isCancel(confirmed) || !confirmed) return;
|
|
2097
|
+
await writeFile(abs, injectSnippet(source, framework.snippet()), "utf8");
|
|
2098
|
+
p.log.success(`${alreadyInjected ? "Updated" : "Added"} Mushi init block in ${rel}`);
|
|
2099
|
+
return;
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
function printNextSteps(framework, consoleBase, enableRewards = false) {
|
|
2103
|
+
p.note(framework.snippet(), "Add this to your app:");
|
|
2104
|
+
if (enableRewards) {
|
|
2105
|
+
const badgeSnippet = framework.id === "react" ? `// Add to your user menu or profile UI:
|
|
2106
|
+
import { MushiRewardsBadge } from 'mushi-mushi/react';
|
|
2107
|
+
|
|
2108
|
+
// Inside your component:
|
|
2109
|
+
<MushiRewardsBadge showPoints />` : `// Add to your user menu:
|
|
2110
|
+
// import { MushiRewardsBadge } from 'mushi-mushi/react';
|
|
2111
|
+
// <MushiRewardsBadge showPoints />`;
|
|
2112
|
+
p.note(badgeSnippet, "Rewards badge snippet:");
|
|
2113
|
+
p.log.info(`Enable rewards in your project settings at ${consoleUrl(consoleBase, "/rewards")}`);
|
|
2114
|
+
p.log.info("Users will earn points for bug reports, screen navigation, and app activity.");
|
|
2115
|
+
}
|
|
2116
|
+
p.note(
|
|
2117
|
+
[
|
|
2118
|
+
" [ ] 1. Paste the init snippet above into your app entry file",
|
|
2119
|
+
" [ ] 2. Start your dev server",
|
|
2120
|
+
" [ ] 3. Wire your editor: npx mushi-mushi setup --ide cursor (or --ide claude)",
|
|
2121
|
+
` [ ] 4. Open the Test it tab to send a test report: ${consoleUrl(consoleBase, "/onboarding?tab=verify")}`
|
|
2122
|
+
].join("\n"),
|
|
2123
|
+
"Next steps:"
|
|
2124
|
+
);
|
|
2125
|
+
}
|
|
2126
|
+
async function maybeOfferConnect(credentials, options, _consoleBase) {
|
|
2127
|
+
if (options.yes) return;
|
|
2128
|
+
const answer = await p.confirm({
|
|
2129
|
+
message: "Run `mushi connect --write-env --wire-ide --wait` now? (SDK env + Cursor MCP + heartbeat check)",
|
|
2130
|
+
initialValue: false
|
|
2131
|
+
});
|
|
2132
|
+
if (p.isCancel(answer) || !answer) return;
|
|
2133
|
+
const endpoint = resolveCloudEndpoint(options.endpoint);
|
|
2134
|
+
try {
|
|
2135
|
+
const { runConnect } = await import("./connect-BSMHOKUQ.js");
|
|
2136
|
+
const saved = loadConfig();
|
|
2137
|
+
const result = await runConnect(
|
|
2138
|
+
{
|
|
2139
|
+
apiKey: saved.apiKey ?? credentials.sdkKey,
|
|
2140
|
+
sdkKey: credentials.sdkKey,
|
|
2141
|
+
projectId: credentials.projectId,
|
|
2142
|
+
endpoint,
|
|
2143
|
+
cwd: options.cwd,
|
|
2144
|
+
writeEnv: true,
|
|
2145
|
+
wireIde: true,
|
|
2146
|
+
wait: true
|
|
2147
|
+
},
|
|
2148
|
+
saved
|
|
2149
|
+
);
|
|
2150
|
+
for (const line of result.messages) p.log.message(line);
|
|
2151
|
+
} catch (err) {
|
|
2152
|
+
p.log.warn(err instanceof Error ? err.message : String(err));
|
|
2153
|
+
p.log.info(
|
|
2154
|
+
`You can run it yourself: npx mushi-mushi connect --project-id ${credentials.projectId} --endpoint ${endpoint} --write-env --wire-ide --wait`
|
|
2155
|
+
);
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
async function maybeEnableRewards(options) {
|
|
2159
|
+
if (options.yes) return false;
|
|
2160
|
+
const answer = await p.confirm({
|
|
2161
|
+
message: "Enable Mushi Rewards? (users earn points for bug reports + app activity)",
|
|
2162
|
+
initialValue: false
|
|
2163
|
+
});
|
|
2164
|
+
if (p.isCancel(answer)) return false;
|
|
2165
|
+
return Boolean(answer);
|
|
2166
|
+
}
|
|
2167
|
+
async function maybeSendTestReport(credentials, options) {
|
|
2168
|
+
if (options.sendTestReport === false) return;
|
|
2169
|
+
let shouldSend;
|
|
2170
|
+
if (options.sendTestReport === true || options.yes) {
|
|
2171
|
+
shouldSend = true;
|
|
2172
|
+
} else {
|
|
2173
|
+
const answer = await p.confirm({
|
|
2174
|
+
message: "Send a test report now to verify the pipeline?",
|
|
2175
|
+
initialValue: true
|
|
2176
|
+
});
|
|
2177
|
+
if (p.isCancel(answer)) return;
|
|
2178
|
+
shouldSend = answer;
|
|
2179
|
+
}
|
|
2180
|
+
if (!shouldSend) return;
|
|
2181
|
+
const endpoint = normalizeEndpoint(resolveCloudEndpoint(options.endpoint));
|
|
2182
|
+
const spinner2 = p.spinner();
|
|
2183
|
+
spinner2.start("Sending test report\u2026");
|
|
2184
|
+
const controller = new AbortController();
|
|
2185
|
+
const timer = setTimeout(() => controller.abort(), TEST_REPORT_FETCH_TIMEOUT_MS);
|
|
2186
|
+
try {
|
|
2187
|
+
const res = await fetch(`${endpoint}/v1/reports`, {
|
|
2188
|
+
method: "POST",
|
|
2189
|
+
signal: controller.signal,
|
|
2190
|
+
headers: {
|
|
2191
|
+
"Content-Type": "application/json",
|
|
2192
|
+
"X-Mushi-Api-Key": credentials.sdkKey,
|
|
2193
|
+
"X-Mushi-Project": credentials.projectId
|
|
2194
|
+
},
|
|
2195
|
+
body: JSON.stringify({
|
|
2196
|
+
projectId: credentials.projectId,
|
|
2197
|
+
description: "Test report from the mushi-mushi setup wizard",
|
|
2198
|
+
category: "other",
|
|
2199
|
+
// Never the project's first real report or its activation (first-report.ts).
|
|
2200
|
+
metadata: { source: "cli_wizard" },
|
|
2201
|
+
reporterToken: `wizard-${randomUUID()}`,
|
|
2202
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2203
|
+
environment: {
|
|
2204
|
+
url: "cli://wizard",
|
|
2205
|
+
userAgent: `mushi-wizard/${process.platform}-${process.arch}`,
|
|
2206
|
+
platform: process.platform,
|
|
2207
|
+
language: "en",
|
|
2208
|
+
viewport: { width: 0, height: 0 },
|
|
2209
|
+
referrer: "",
|
|
2210
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2211
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
|
|
2212
|
+
}
|
|
2213
|
+
})
|
|
2214
|
+
});
|
|
2215
|
+
if (!res.ok) {
|
|
2216
|
+
spinner2.stop(`Test report rejected (HTTP ${res.status}).`);
|
|
2217
|
+
p.log.warn(
|
|
2218
|
+
res.status === 401 || res.status === 403 ? "Credentials did not authenticate \u2014 double-check the project ID and API key." : "Skipping test report. You can retry with `mushi test`."
|
|
2219
|
+
);
|
|
2220
|
+
return;
|
|
2221
|
+
}
|
|
2222
|
+
spinner2.stop("Test report sent.");
|
|
2223
|
+
let reportId;
|
|
2224
|
+
try {
|
|
2225
|
+
const body = await res.json();
|
|
2226
|
+
reportId = body.data?.reportId;
|
|
2227
|
+
} catch {
|
|
2228
|
+
}
|
|
2229
|
+
const consoleBase = options.consoleBase ?? resolveConsoleUrlSync(options.cwd);
|
|
2230
|
+
p.log.success(`View it at ${reportsUrl(consoleBase, reportId)}`);
|
|
2231
|
+
} catch (err) {
|
|
2232
|
+
const aborted = err instanceof Error && err.name === "AbortError";
|
|
2233
|
+
spinner2.stop(aborted ? "Timed out reaching the Mushi API." : "Could not reach the Mushi API.");
|
|
2234
|
+
p.log.warn(err instanceof Error ? err.message : String(err));
|
|
2235
|
+
} finally {
|
|
2236
|
+
clearTimeout(timer);
|
|
2237
|
+
}
|
|
2238
|
+
}
|
|
2239
|
+
async function printFreshnessHint() {
|
|
2240
|
+
const result = await checkFreshness("mushi-mushi", MUSHI_CLI_VERSION);
|
|
2241
|
+
if (!result || !result.isOutdated) return;
|
|
2242
|
+
p.log.info(
|
|
2243
|
+
`A newer version of mushi-mushi is available: ${result.current} \u2192 ${result.latest}. Run \`npx mushi-mushi@latest\` to get the freshest wizard.`
|
|
2244
|
+
);
|
|
2245
|
+
}
|
|
2246
|
+
function warnIfWorkspaceRoot(cwd) {
|
|
2247
|
+
let hint;
|
|
2248
|
+
try {
|
|
2249
|
+
hint = detectWorkspaceHint(cwd);
|
|
2250
|
+
} catch {
|
|
2251
|
+
return;
|
|
2252
|
+
}
|
|
2253
|
+
if (!hint || hint.apps.length === 0) return;
|
|
2254
|
+
const hasFrameworkAtCwd = hint.apps.some(
|
|
2255
|
+
(app) => isSameDirectory(cwd, resolveWorkspaceAppPath(hint.root, app.relativePath))
|
|
2256
|
+
);
|
|
2257
|
+
if (hasFrameworkAtCwd) return;
|
|
2258
|
+
const apps = hint.apps.slice(0, 5).map((app) => ` \u2022 ${app.relativePath} (${app.framework})`).join("\n");
|
|
2259
|
+
p.log.warn(
|
|
2260
|
+
`You appear to be at a workspace root (source: ${hint.source}). Mushi will install into the current directory, which has no framework dep. You probably meant one of these sub-packages:
|
|
2261
|
+
${apps}
|
|
2262
|
+
Run \`mushi init --cwd <path>\` \u2014 or re-run the wizard from inside that package.`
|
|
2263
|
+
);
|
|
2264
|
+
}
|
|
2265
|
+
function resolveWorkspaceAppPath(root, relativePath) {
|
|
2266
|
+
return `${root}/${relativePath}`.replace(/\\/g, "/");
|
|
2267
|
+
}
|
|
2268
|
+
function isSameDirectory(a, b) {
|
|
2269
|
+
return a.replace(/\\/g, "/").replace(/\/+$/, "") === b.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
2270
|
+
}
|
|
2271
|
+
|
|
2272
|
+
export {
|
|
2273
|
+
runInit,
|
|
2274
|
+
resolveSavedCredentials,
|
|
2275
|
+
mintWizardKeys,
|
|
2276
|
+
sanitizeSecret,
|
|
2277
|
+
isEnvFileCoveredByGitignore,
|
|
2278
|
+
planCliConfigUpdate
|
|
2279
|
+
};
|