@mushi-mushi/cli 0.4.0 → 0.5.1

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/index.js CHANGED
@@ -4,12 +4,14 @@
4
4
  import { Command } from "commander";
5
5
 
6
6
  // src/config.ts
7
- import { readFileSync, writeFileSync, existsSync } from "fs";
7
+ import { chmodSync, readFileSync, statSync, writeFileSync, existsSync } from "fs";
8
8
  import { join } from "path";
9
9
  import { homedir } from "os";
10
10
  var CONFIG_PATH = join(homedir(), ".mushirc");
11
+ var SECURE_FILE_MODE = 384;
11
12
  function loadConfig(path = CONFIG_PATH) {
12
13
  if (!existsSync(path)) return {};
14
+ tightenPermissions(path);
13
15
  try {
14
16
  return JSON.parse(readFileSync(path, "utf-8"));
15
17
  } catch {
@@ -17,14 +19,24 @@ function loadConfig(path = CONFIG_PATH) {
17
19
  }
18
20
  }
19
21
  function saveConfig(config, path = CONFIG_PATH) {
20
- writeFileSync(path, JSON.stringify(config, null, 2));
22
+ writeFileSync(path, JSON.stringify(config, null, 2), { mode: SECURE_FILE_MODE });
23
+ tightenPermissions(path);
24
+ }
25
+ function tightenPermissions(path) {
26
+ if (process.platform === "win32") return;
27
+ try {
28
+ const current = statSync(path).mode & 511;
29
+ if (current !== SECURE_FILE_MODE) chmodSync(path, SECURE_FILE_MODE);
30
+ } catch {
31
+ }
21
32
  }
22
33
 
23
34
  // src/init.ts
24
35
  import * as p from "@clack/prompts";
25
36
  import { spawn } from "child_process";
26
- import { appendFileSync, existsSync as existsSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
27
- import { join as join3 } from "path";
37
+ import { randomUUID } from "crypto";
38
+ import { appendFileSync, existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
39
+ import { join as join4 } from "path";
28
40
 
29
41
  // src/detect.ts
30
42
  import { readFileSync as readFileSync2, existsSync as existsSync2 } from "fs";
@@ -256,11 +268,198 @@ function collectDeps(pkg) {
256
268
  ]);
257
269
  }
258
270
 
271
+ // src/endpoint.ts
272
+ var DEFAULT_ENDPOINT = "https://api.mushimushi.dev";
273
+ var TEST_REPORT_TIMEOUT_MS = 1e4;
274
+ var TEST_REPORT_FETCH_TIMEOUT_MS = TEST_REPORT_TIMEOUT_MS;
275
+ function assertEndpoint(url) {
276
+ let parsed;
277
+ try {
278
+ parsed = new URL(url);
279
+ } catch {
280
+ throw new Error(`Invalid endpoint URL: ${url}`);
281
+ }
282
+ const host = parsed.hostname;
283
+ const isLocal = host === "localhost" || host === "127.0.0.1" || host === "::1" || host.endsWith(".local");
284
+ if (parsed.protocol !== "https:" && !isLocal) {
285
+ throw new Error(`Endpoint must use https:// (got ${parsed.protocol}//${host}).`);
286
+ }
287
+ return parsed.origin + (parsed.pathname === "/" ? "" : parsed.pathname);
288
+ }
289
+ function normalizeEndpoint(url) {
290
+ const input = url ?? DEFAULT_ENDPOINT;
291
+ let end = input.length;
292
+ while (end > 0 && input.charCodeAt(end - 1) === 47) end--;
293
+ return input.slice(0, end);
294
+ }
295
+
296
+ // src/freshness.ts
297
+ var REGISTRY = "https://registry.npmjs.org";
298
+ var DEFAULT_TIMEOUT_MS = 2e3;
299
+ async function checkFreshness(packageName, currentVersion, opts = {}) {
300
+ if (process.env.MUSHI_NO_UPDATE_CHECK === "1") return null;
301
+ const registry = opts.registry ?? REGISTRY;
302
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
303
+ const controller = new AbortController();
304
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
305
+ try {
306
+ const res = await fetch(
307
+ `${registry}/${encodeURIComponent(packageName)}/latest`,
308
+ {
309
+ signal: controller.signal,
310
+ headers: { Accept: "application/json" }
311
+ }
312
+ );
313
+ if (!res.ok) return null;
314
+ const body = await res.json();
315
+ const latest = typeof body.version === "string" ? body.version : null;
316
+ if (!latest) return null;
317
+ return {
318
+ current: currentVersion,
319
+ latest,
320
+ isOutdated: isNewerStableVersion(latest, currentVersion)
321
+ };
322
+ } catch {
323
+ return null;
324
+ } finally {
325
+ clearTimeout(timer);
326
+ }
327
+ }
328
+ function isNewerStableVersion(latest, current) {
329
+ const latestCore = stripPreRelease(latest);
330
+ if (hasPreReleaseTag(latest)) return false;
331
+ const [la, lb, lc] = parse(latestCore);
332
+ const [ca, cb, cc] = parse(stripPreRelease(current));
333
+ if (la !== ca) return la > ca;
334
+ if (lb !== cb) return lb > cb;
335
+ return lc > cc;
336
+ }
337
+ function stripPreRelease(version) {
338
+ const idx = version.indexOf("-");
339
+ return idx === -1 ? version : version.slice(0, idx);
340
+ }
341
+ function hasPreReleaseTag(version) {
342
+ return version.includes("-");
343
+ }
344
+ function parse(version) {
345
+ const parts = version.split(".").map((part) => Number(part));
346
+ return [
347
+ Number.isFinite(parts[0]) ? parts[0] : 0,
348
+ Number.isFinite(parts[1]) ? parts[1] : 0,
349
+ Number.isFinite(parts[2]) ? parts[2] : 0
350
+ ];
351
+ }
352
+
353
+ // src/monorepo.ts
354
+ import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync, statSync as statSync2 } from "fs";
355
+ import { dirname, join as join3, resolve } from "path";
356
+ var WORKSPACE_GLOB_CANDIDATES = ["apps/*", "packages/*", "examples/*"];
357
+ var FRAMEWORK_DEPS = {
358
+ next: "Next.js",
359
+ nuxt: "Nuxt",
360
+ "@sveltejs/kit": "SvelteKit",
361
+ "@angular/core": "Angular",
362
+ expo: "Expo",
363
+ "react-native": "React Native",
364
+ "@capacitor/core": "Capacitor",
365
+ svelte: "Svelte",
366
+ vue: "Vue",
367
+ react: "React"
368
+ };
369
+ function detectWorkspaceHint(cwd) {
370
+ const root = findWorkspaceRoot(cwd);
371
+ if (!root) return null;
372
+ const rootPkg = readPackageJsonSafely(join3(root, "package.json"));
373
+ if (rootPkg && getFrameworkFromPkg(rootPkg)) return null;
374
+ const source = existsSync3(join3(root, "pnpm-workspace.yaml")) ? "pnpm-workspace" : root === cwd ? "package-json" : "parent";
375
+ const apps = collectAppsFromGlobs(root);
376
+ if (apps.length === 0) return null;
377
+ return { root, apps, source };
378
+ }
379
+ function findWorkspaceRoot(start) {
380
+ let dir = resolve(start);
381
+ for (let i = 0; i < 8; i++) {
382
+ if (isWorkspaceRoot(dir)) return dir;
383
+ const parent = dirname(dir);
384
+ if (parent === dir) break;
385
+ dir = parent;
386
+ }
387
+ return null;
388
+ }
389
+ function isWorkspaceRoot(dir) {
390
+ if (existsSync3(join3(dir, "pnpm-workspace.yaml"))) return true;
391
+ const pkg = readPackageJsonSafely(join3(dir, "package.json"));
392
+ if (!pkg) return false;
393
+ return Boolean(pkg.workspaces);
394
+ }
395
+ function collectAppsFromGlobs(root) {
396
+ const results = [];
397
+ for (const glob of WORKSPACE_GLOB_CANDIDATES) {
398
+ const prefix = glob.replace("/*", "");
399
+ const parentDir = join3(root, prefix);
400
+ if (!existsSync3(parentDir)) continue;
401
+ let entries;
402
+ try {
403
+ entries = readdirSync(parentDir);
404
+ } catch {
405
+ continue;
406
+ }
407
+ for (const entry of entries) {
408
+ const pkgPath = join3(parentDir, entry, "package.json");
409
+ if (!isFileSafe(pkgPath)) continue;
410
+ const pkg = readPackageJsonSafely(pkgPath);
411
+ if (!pkg) continue;
412
+ const framework = getFrameworkFromPkg(pkg);
413
+ if (!framework) continue;
414
+ results.push({
415
+ name: pkg.name ?? `${prefix}/${entry}`,
416
+ relativePath: `${prefix}/${entry}`,
417
+ framework
418
+ });
419
+ }
420
+ }
421
+ return results;
422
+ }
423
+ function readPackageJsonSafely(path) {
424
+ if (!isFileSafe(path)) return null;
425
+ try {
426
+ return JSON.parse(readFileSync3(path, "utf-8"));
427
+ } catch {
428
+ return null;
429
+ }
430
+ }
431
+ function isFileSafe(path) {
432
+ try {
433
+ return existsSync3(path) && statSync2(path).isFile();
434
+ } catch {
435
+ return false;
436
+ }
437
+ }
438
+ function getFrameworkFromPkg(pkg) {
439
+ const deps = {
440
+ ...pkg.dependencies ?? {},
441
+ ...pkg.devDependencies ?? {},
442
+ ...pkg.peerDependencies ?? {}
443
+ };
444
+ for (const dep of Object.keys(FRAMEWORK_DEPS)) {
445
+ if (dep in deps) return FRAMEWORK_DEPS[dep];
446
+ }
447
+ return void 0;
448
+ }
449
+
450
+ // src/version.ts
451
+ var MUSHI_CLI_VERSION = true ? "0.5.1" : "0.0.0-dev";
452
+
259
453
  // src/init.ts
260
454
  var ENV_FILES = [".env.local", ".env"];
455
+ var PROJECT_ID_PATTERN = /^proj_[A-Za-z0-9_-]{10,}$/;
456
+ var API_KEY_PATTERN = /^mushi_[A-Za-z0-9_-]{10,}$/;
261
457
  async function runInit(options = {}) {
262
458
  const cwd = options.cwd ?? process.cwd();
459
+ ensureInteractiveOrBailOut(options);
263
460
  p.intro("\u{1F41B} Mushi Mushi setup wizard");
461
+ await printFreshnessHint();
462
+ warnIfWorkspaceRoot(cwd);
264
463
  const pkg = readPackageJson(cwd);
265
464
  if (!pkg) {
266
465
  p.log.warn("No package.json found in this directory.");
@@ -279,15 +478,28 @@ async function runInit(options = {}) {
279
478
  const pm = detectPackageManager(cwd);
280
479
  const packagesToInstall = framework.needsWebPackage ? [framework.packageName, "@mushi-mushi/web"] : [framework.packageName];
281
480
  if (!options.skipInstall) {
282
- await installPackages(pm, packagesToInstall);
481
+ await installPackages(pm, packagesToInstall, cwd);
283
482
  } else {
284
483
  p.log.info(`Skipped install. Run \`${installCommand(pm, packagesToInstall)}\` yourself.`);
285
484
  }
286
485
  writeEnvFile(cwd, credentials.apiKey, credentials.projectId, framework);
287
486
  persistCliConfig(credentials.apiKey, credentials.projectId);
288
487
  printNextSteps(framework, credentials.apiKey, credentials.projectId);
488
+ await maybeSendTestReport(credentials, options);
289
489
  p.outro("Setup complete. Happy bug squashing \u{1F41B}");
290
490
  }
491
+ function ensureInteractiveOrBailOut(options) {
492
+ const isTTY = Boolean(process.stdin.isTTY && process.stdout.isTTY);
493
+ if (isTTY) return;
494
+ const hasAllFlags = Boolean(
495
+ (options.framework || options.yes) && options.projectId && options.apiKey
496
+ );
497
+ if (hasAllFlags) return;
498
+ process.stderr.write(
499
+ "mushi-mushi: non-interactive terminal detected.\nPass all of --yes (or --framework), --project-id, and --api-key to run unattended.\nExample: npx mushi-mushi --yes --project-id proj_xxx --api-key mushi_xxx\n"
500
+ );
501
+ process.exit(1);
502
+ }
291
503
  async function chooseFramework(detected, options) {
292
504
  if (options.framework) {
293
505
  const explicit = FRAMEWORKS[options.framework];
@@ -316,23 +528,48 @@ async function chooseFramework(detected, options) {
316
528
  }
317
529
  async function collectCredentials(options) {
318
530
  const existing = loadConfig();
319
- const projectId = options.projectId ?? existing.projectId ?? await promptText({
531
+ const rawProjectId = options.projectId ?? existing.projectId ?? await promptText({
320
532
  message: "Project ID",
321
533
  placeholder: "proj_xxxxxxxxxxxx",
322
- hint: "Find this at https://kensaur.us/mushi-mushi/projects"
534
+ hint: "Find this at https://kensaur.us/mushi-mushi/projects",
535
+ validate: (v) => PROJECT_ID_PATTERN.test(v) ? void 0 : "Expected format: proj_ followed by 10+ alphanumeric characters"
323
536
  });
324
- const apiKey = options.apiKey ?? existing.apiKey ?? await promptText({
537
+ const rawApiKey = options.apiKey ?? existing.apiKey ?? await promptText({
325
538
  message: "API key",
326
539
  placeholder: "mushi_xxxxxxxxxxxx",
327
- hint: "Treat this like a password \u2014 it goes in your env file, not in source."
540
+ hint: "Treat this like a password \u2014 it goes in your env file, not in source.",
541
+ validate: (v) => API_KEY_PATTERN.test(v) ? void 0 : "Expected format: mushi_ followed by 10+ alphanumeric characters"
328
542
  });
543
+ const projectId = sanitizeSecret(rawProjectId);
544
+ const apiKey = sanitizeSecret(rawApiKey);
545
+ if (!PROJECT_ID_PATTERN.test(projectId)) {
546
+ throw new Error(
547
+ `Invalid project ID. Expected format: proj_[A-Za-z0-9_-]{10,}. Got: ${redact(projectId)}`
548
+ );
549
+ }
550
+ if (!API_KEY_PATTERN.test(apiKey)) {
551
+ throw new Error(
552
+ `Invalid API key. Expected format: mushi_[A-Za-z0-9_-]{10,}. Got: ${redact(apiKey)}`
553
+ );
554
+ }
329
555
  return { projectId, apiKey };
330
556
  }
557
+ function sanitizeSecret(raw) {
558
+ return raw.trim().replace(/^['"]|['"]$/g, "").replace(/[\r\n\0]/g, "");
559
+ }
560
+ function redact(value) {
561
+ if (value.length <= 8) return "***";
562
+ return `${value.slice(0, 4)}\u2026${value.slice(-2)}`;
563
+ }
331
564
  async function promptText(opts) {
332
565
  const value = await p.text({
333
566
  message: opts.message,
334
567
  placeholder: opts.placeholder,
335
- validate: (v) => v.length === 0 ? "Required" : void 0
568
+ validate: (v) => {
569
+ const clean = sanitizeSecret(v);
570
+ if (clean.length === 0) return "Required";
571
+ return opts.validate ? opts.validate(clean) : void 0;
572
+ }
336
573
  });
337
574
  if (p.isCancel(value)) {
338
575
  p.cancel("Aborted.");
@@ -341,34 +578,40 @@ async function promptText(opts) {
341
578
  if (opts.hint) p.log.info(opts.hint);
342
579
  return value;
343
580
  }
344
- async function installPackages(pm, packages) {
581
+ async function installPackages(pm, packages, cwd) {
345
582
  const command = installCommand(pm, packages);
346
583
  const spinner2 = p.spinner();
347
584
  spinner2.start(`Installing ${packages.join(", ")} via ${pm}\u2026`);
348
585
  try {
349
- await runCommand(pm, packages);
586
+ await runCommand(pm, packages, cwd);
350
587
  spinner2.stop(`Installed ${packages.join(", ")}`);
351
588
  } catch (err) {
352
589
  spinner2.stop(`Install failed \u2014 run \`${command}\` manually.`);
353
- p.log.error(err instanceof Error ? err.message : String(err));
590
+ p.log.error(err instanceof Error ? err.name + ": " + err.message : String(err));
354
591
  }
355
592
  }
356
- function runCommand(pm, packages) {
357
- return new Promise((resolve, reject) => {
358
- const verb = pm === "npm" ? "install" : "add";
359
- const child = spawn(pm, [verb, ...packages], { stdio: "inherit", shell: true });
593
+ function runCommand(pm, packages, cwd) {
594
+ const verb = pm === "npm" ? "install" : "add";
595
+ const command = process.platform === "win32" ? `${pm}.cmd` : pm;
596
+ return new Promise((resolve2, reject) => {
597
+ const child = spawn(command, [verb, ...packages], {
598
+ stdio: "inherit",
599
+ shell: false,
600
+ cwd,
601
+ env: process.env
602
+ });
360
603
  child.on("error", reject);
361
604
  child.on("exit", (code) => {
362
- if (code === 0) resolve();
363
- else reject(new Error(`${pm} exited with code ${code}`));
605
+ if (code === 0) resolve2();
606
+ else reject(new Error(`${pm} exited with code ${code ?? "null"}`));
364
607
  });
365
608
  });
366
609
  }
367
610
  function writeEnvFile(cwd, apiKey, projectId, framework) {
368
- const target = ENV_FILES.find((f) => existsSync3(join3(cwd, f))) ?? ENV_FILES[0];
369
- const targetPath = join3(cwd, target);
611
+ const target = ENV_FILES.find((f) => existsSync4(join4(cwd, f))) ?? ENV_FILES[0];
612
+ const targetPath = join4(cwd, target);
370
613
  const newVars = envVarsToWrite(apiKey, projectId, framework);
371
- const existing = existsSync3(targetPath) ? readFileSync3(targetPath, "utf-8") : "";
614
+ const existing = existsSync4(targetPath) ? readFileSync4(targetPath, "utf-8") : "";
372
615
  if (existing.includes("MUSHI_PROJECT_ID")) {
373
616
  p.log.warn(`Existing MUSHI_* vars found in ${target} \u2014 leaving them untouched.`);
374
617
  return;
@@ -378,20 +621,38 @@ function writeEnvFile(cwd, apiKey, projectId, framework) {
378
621
  # Mushi Mushi
379
622
  ${newVars}
380
623
  `);
381
- if (!existing) {
382
- writeFileSync2(targetPath, readFileSync3(targetPath, "utf-8"));
383
- }
384
624
  p.log.success(`Wrote env vars to ${target}`);
385
625
  warnIfMissingFromGitignore(cwd, target);
386
626
  }
627
+ function isEnvFileCoveredByGitignore(gitignoreContent, envFile) {
628
+ const lines = gitignoreContent.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
629
+ let covered = false;
630
+ for (const line of lines) {
631
+ if (line.startsWith("!")) {
632
+ if (matchesGitignorePattern(line.slice(1), envFile)) covered = false;
633
+ continue;
634
+ }
635
+ if (matchesGitignorePattern(line, envFile)) covered = true;
636
+ }
637
+ return covered;
638
+ }
639
+ function matchesGitignorePattern(pattern, filename) {
640
+ if (pattern.endsWith("/")) return false;
641
+ const normalized = pattern.startsWith("/") ? pattern.slice(1) : pattern;
642
+ const regexSource = normalized.split("").map((ch) => ch === "*" ? "[^/]*" : escapeRegexChar(ch)).join("");
643
+ return new RegExp(`^${regexSource}$`).test(filename);
644
+ }
645
+ function escapeRegexChar(ch) {
646
+ return /[-/\\^$+?.()|[\]{}]/.test(ch) ? `\\${ch}` : ch;
647
+ }
387
648
  function warnIfMissingFromGitignore(cwd, envFile) {
388
- const gitignorePath = join3(cwd, ".gitignore");
389
- if (!existsSync3(gitignorePath)) {
649
+ const gitignorePath = join4(cwd, ".gitignore");
650
+ if (!existsSync4(gitignorePath)) {
390
651
  p.log.warn(`No .gitignore found \u2014 make sure ${envFile} is not committed.`);
391
652
  return;
392
653
  }
393
- const content = readFileSync3(gitignorePath, "utf-8");
394
- if (!content.split("\n").some((line) => line.trim() === envFile || line.trim() === ".env*")) {
654
+ const content = readFileSync4(gitignorePath, "utf-8");
655
+ if (!isEnvFileCoveredByGitignore(content, envFile)) {
395
656
  p.log.warn(`${envFile} is not in .gitignore \u2014 add it before committing.`);
396
657
  }
397
658
  }
@@ -406,10 +667,105 @@ function printNextSteps(framework, apiKey, projectId) {
406
667
  p.log.message(" \u2022 Look for the \u{1F41B} button in the bottom-right corner (or shake on mobile)");
407
668
  p.log.message(" \u2022 Submit a test report \u2014 it should appear at https://kensaur.us/mushi-mushi/reports");
408
669
  }
670
+ async function maybeSendTestReport(credentials, options) {
671
+ if (options.sendTestReport === false) return;
672
+ let shouldSend;
673
+ if (options.sendTestReport === true || options.yes) {
674
+ shouldSend = true;
675
+ } else {
676
+ const answer = await p.confirm({
677
+ message: "Send a test report now to verify the pipeline?",
678
+ initialValue: true
679
+ });
680
+ if (p.isCancel(answer)) return;
681
+ shouldSend = answer;
682
+ }
683
+ if (!shouldSend) return;
684
+ const spinner2 = p.spinner();
685
+ spinner2.start("Sending test report\u2026");
686
+ const endpoint = normalizeEndpoint(options.endpoint);
687
+ const controller = new AbortController();
688
+ const timer = setTimeout(() => controller.abort(), TEST_REPORT_FETCH_TIMEOUT_MS);
689
+ try {
690
+ const res = await fetch(`${endpoint}/v1/reports`, {
691
+ method: "POST",
692
+ signal: controller.signal,
693
+ headers: {
694
+ "Content-Type": "application/json",
695
+ "X-Mushi-Api-Key": credentials.apiKey,
696
+ "X-Mushi-Project": credentials.projectId
697
+ },
698
+ body: JSON.stringify({
699
+ projectId: credentials.projectId,
700
+ description: "Test report from the mushi-mushi setup wizard",
701
+ category: "other",
702
+ reporterToken: `wizard-${randomUUID()}`,
703
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
704
+ environment: {
705
+ url: "cli://wizard",
706
+ userAgent: `mushi-wizard/${process.platform}-${process.arch}`,
707
+ platform: process.platform,
708
+ language: "en",
709
+ viewport: { width: 0, height: 0 },
710
+ referrer: "",
711
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
712
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
713
+ }
714
+ })
715
+ });
716
+ if (!res.ok) {
717
+ spinner2.stop(`Test report rejected (HTTP ${res.status}).`);
718
+ p.log.warn(
719
+ 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`."
720
+ );
721
+ return;
722
+ }
723
+ spinner2.stop("Test report sent.");
724
+ p.log.success("View it at https://kensaur.us/mushi-mushi/reports");
725
+ } catch (err) {
726
+ const aborted = err instanceof Error && err.name === "AbortError";
727
+ spinner2.stop(aborted ? "Timed out reaching the Mushi API." : "Could not reach the Mushi API.");
728
+ p.log.warn(err instanceof Error ? err.message : String(err));
729
+ } finally {
730
+ clearTimeout(timer);
731
+ }
732
+ }
733
+ async function printFreshnessHint() {
734
+ const result = await checkFreshness("mushi-mushi", MUSHI_CLI_VERSION);
735
+ if (!result || !result.isOutdated) return;
736
+ p.log.info(
737
+ `A newer version of mushi-mushi is available: ${result.current} \u2192 ${result.latest}. Run \`npx mushi-mushi@latest\` to get the freshest wizard.`
738
+ );
739
+ }
740
+ function warnIfWorkspaceRoot(cwd) {
741
+ let hint;
742
+ try {
743
+ hint = detectWorkspaceHint(cwd);
744
+ } catch {
745
+ return;
746
+ }
747
+ if (!hint || hint.apps.length === 0) return;
748
+ const hasFrameworkAtCwd = hint.apps.some(
749
+ (app) => isSameDirectory(cwd, resolveWorkspaceAppPath(hint.root, app.relativePath))
750
+ );
751
+ if (hasFrameworkAtCwd) return;
752
+ const apps = hint.apps.slice(0, 5).map((app) => ` \u2022 ${app.relativePath} (${app.framework})`).join("\n");
753
+ p.log.warn(
754
+ `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:
755
+ ${apps}
756
+ Run \`mushi init --cwd <path>\` \u2014 or re-run the wizard from inside that package.`
757
+ );
758
+ }
759
+ function resolveWorkspaceAppPath(root, relativePath) {
760
+ return `${root}/${relativePath}`.replace(/\\/g, "/");
761
+ }
762
+ function isSameDirectory(a, b) {
763
+ return a.replace(/\\/g, "/").replace(/\/+$/, "") === b.replace(/\\/g, "/").replace(/\/+$/, "");
764
+ }
409
765
 
410
766
  // src/index.ts
411
767
  async function apiCall(path, config, options = {}) {
412
- const endpoint = config.endpoint ?? "https://api.mushimushi.dev";
768
+ const endpoint = config.endpoint ?? DEFAULT_ENDPOINT;
413
769
  const res = await fetch(`${endpoint}${path}`, {
414
770
  ...options,
415
771
  headers: {
@@ -422,23 +778,26 @@ async function apiCall(path, config, options = {}) {
422
778
  });
423
779
  return res.json();
424
780
  }
425
- var program = new Command().name("mushi").description("Mushi Mushi CLI \u2014 set up the SDK, manage bug reports, monitor pipeline").version("0.3.0");
426
- program.command("init").description("Set up the Mushi Mushi SDK in this project (auto-detects framework)").option("--project-id <id>", "Skip the prompt by passing the project ID").option("--api-key <key>", "Skip the prompt by passing the API key").option("--framework <id>", "Force a framework (next, react, vue, nuxt, svelte, sveltekit, angular, expo, react-native, capacitor, vanilla)").option("--skip-install", "Don't auto-install the SDK package \u2014 print the command instead").option("-y, --yes", "Accept detected framework without prompting").action(async (opts) => {
781
+ var program = new Command().name("mushi").description("Mushi Mushi CLI \u2014 set up the SDK, manage bug reports, monitor pipeline").version(MUSHI_CLI_VERSION);
782
+ program.command("init").description("Set up the Mushi Mushi SDK in this project (auto-detects framework)").option("--project-id <id>", "Skip the prompt by passing the project ID").option("--api-key <key>", "Skip the prompt by passing the API key").option("--framework <id>", "Force a framework (next, react, vue, nuxt, svelte, sveltekit, angular, expo, react-native, capacitor, vanilla)").option("--skip-install", "Don't auto-install the SDK package \u2014 print the command instead").option("-y, --yes", "Accept detected framework without prompting").option("--cwd <path>", "Run the wizard in a different directory").option("--endpoint <url>", "Override the Mushi API endpoint (self-hosted)").option("--skip-test-report", 'Skip the end-of-wizard "send a test report" prompt').action(async (opts) => {
427
783
  await runInit({
428
784
  projectId: opts.projectId,
429
785
  apiKey: opts.apiKey,
430
786
  framework: opts.framework,
431
787
  skipInstall: opts.skipInstall,
432
- yes: opts.yes
788
+ yes: opts.yes,
789
+ cwd: opts.cwd,
790
+ endpoint: opts.endpoint,
791
+ sendTestReport: opts.skipTestReport ? false : void 0
433
792
  });
434
793
  });
435
794
  program.command("login").description("Store API key for authentication").requiredOption("--api-key <key>", "API key").option("--endpoint <url>", "API endpoint URL").option("--project-id <id>", "Default project ID").action((opts) => {
436
795
  const config = loadConfig();
437
796
  config.apiKey = opts.apiKey;
438
- if (opts.endpoint) config.endpoint = opts.endpoint;
797
+ if (opts.endpoint) config.endpoint = assertEndpoint(opts.endpoint);
439
798
  if (opts.projectId) config.projectId = opts.projectId;
440
799
  saveConfig(config);
441
- console.log("Saved credentials to ~/.mushirc");
800
+ console.log("Saved credentials to ~/.mushirc (mode 0o600)");
442
801
  });
443
802
  program.command("status").description("Show project stats").action(async () => {
444
803
  const config = loadConfig();
@@ -493,10 +852,10 @@ reports.command("triage <id>").description("Update report status/severity").opti
493
852
  program.command("config").description("View or update CLI config").argument("[key]", "Config key to set").argument("[value]", "Value").action((key, value) => {
494
853
  const config = loadConfig();
495
854
  if (key && value) {
496
- ;
497
- config[key] = value;
855
+ const safeValue = key === "endpoint" ? assertEndpoint(value) : value;
856
+ config[key] = safeValue;
498
857
  saveConfig(config);
499
- console.log(`Set ${key} = ${value}`);
858
+ console.log(`Set ${key} = ${safeValue}`);
500
859
  } else {
501
860
  console.log(JSON.stringify(config, null, 2));
502
861
  }
package/dist/init.d.ts CHANGED
@@ -16,7 +16,24 @@ interface InitOptions {
16
16
  framework?: FrameworkId;
17
17
  skipInstall?: boolean;
18
18
  yes?: boolean;
19
+ endpoint?: string;
20
+ sendTestReport?: boolean;
19
21
  }
20
22
  declare function runInit(options?: InitOptions): Promise<void>;
23
+ /**
24
+ * Strip whitespace, quotes, and any control characters a user might paste by
25
+ * accident. Prevents env-file injection via newlines in a pasted secret.
26
+ * Exported for test coverage of the env-file-injection defense.
27
+ */
28
+ declare function sanitizeSecret(raw: string): string;
29
+ /**
30
+ * Return true when any line in the user's `.gitignore` actually matches the
31
+ * env file we just wrote. Subtle point: `.env` in gitignore does NOT cover
32
+ * `.env.local` — gitignore matches by filename, not prefix. We build a tiny
33
+ * glob matcher (only `*` as wildcard, gitignore's common case) and test each
34
+ * non-comment line. `!`-prefixed negations are treated as "not covered" to
35
+ * stay on the safe side — better a false warning than a silent leak.
36
+ */
37
+ declare function isEnvFileCoveredByGitignore(gitignoreContent: string, envFile: string): boolean;
21
38
 
22
- export { type InitOptions, runInit };
39
+ export { type InitOptions, isEnvFileCoveredByGitignore, runInit, sanitizeSecret };