@zharp/cli 0.1.0 → 0.2.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/cli.js CHANGED
@@ -3,7 +3,7 @@
3
3
 
4
4
  // src/cli.ts
5
5
  var import_node_util = require("util");
6
- var import_node_fs4 = require("fs");
6
+ var import_node_fs8 = require("fs");
7
7
 
8
8
  // src/api.ts
9
9
  var import_node_zlib = require("zlib");
@@ -30,7 +30,7 @@ function resolveConnection(options) {
30
30
  function artifactsUrl(connection) {
31
31
  return `${connection.url}/api/v1/applications/${encodeURIComponent(String(connection.app))}/artifacts`;
32
32
  }
33
- var sleep = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
33
+ var sleep = (ms) => new Promise((resolve5) => setTimeout(resolve5, ms));
34
34
  async function uploadArtifact(connection, artifact, options = {}) {
35
35
  const doFetch = options.fetch ?? fetch;
36
36
  const retries = options.retries ?? 3;
@@ -447,11 +447,14 @@ async function uploadDsyms(path, connection, options = {}) {
447
447
  }
448
448
 
449
449
  // src/sourcemaps.ts
450
- var import_node_fs3 = require("fs");
451
- var import_node_path3 = require("path");
450
+ var import_node_fs4 = require("fs");
451
+ var import_node_path4 = require("path");
452
452
 
453
453
  // src/debug-id.ts
454
454
  var import_node_crypto = require("crypto");
455
+ var import_node_fs3 = require("fs");
456
+ var import_node_path3 = require("path");
457
+ var import_node_url = require("url");
455
458
  var DEBUG_ID_COMMENT = "//# debugId=";
456
459
  var DEBUG_ID_PATTERN = /^\/\/# debugId=([0-9a-fA-F-]{36})\s*$/m;
457
460
  var SOURCE_MAPPING_URL = /^\/\/[#@] sourceMappingURL=(.*?)\s*$/;
@@ -520,22 +523,83 @@ function withoutSourceMappingUrl(code) {
520
523
  if (end > 0 && SOURCE_MAPPING_URL.test(lines[end - 1].trim())) return lines.slice(0, end - 1).join(eol) + eol;
521
524
  return code;
522
525
  }
523
- function injectMap(mapText, debugId) {
526
+ function injectMap(mapText, debugId, mapPath) {
524
527
  const map = JSON.parse(mapText);
525
528
  if (!map || typeof map !== "object") throw new Error("not a source map");
529
+ const filled = mapPath ? fillSourcesContent(map, mapPath) : 0;
526
530
  const hasSourcesContent = Array.isArray(map.sourcesContent) && map.sourcesContent.some((s) => typeof s === "string");
527
- if (map.debugId === debugId && map.debug_id === debugId) return { text: mapText, changed: false, hasSourcesContent };
531
+ if (!filled && map.debugId === debugId && map.debug_id === debugId) return { text: mapText, changed: false, hasSourcesContent };
528
532
  map.debugId = debugId;
529
533
  map.debug_id = debugId;
530
534
  return { text: JSON.stringify(map), changed: true, hasSourcesContent };
531
535
  }
536
+ var MAX_SOURCE_BYTES = 1e6;
537
+ function sourcePathCandidates(source, mapPath, sourceRoot = "") {
538
+ const mapDir = (0, import_node_path3.dirname)(mapPath);
539
+ let stripped = source;
540
+ let projectRelative = false;
541
+ if (/^turbopack:\/\/\/\[project\]\//.test(source)) {
542
+ stripped = source.replace(/^turbopack:\/\/\/\[project\]\//, "");
543
+ projectRelative = true;
544
+ } else if (/^webpack:\/\//.test(source)) {
545
+ stripped = source.replace(/^webpack:\/\/[^/]*\//, "").replace(/^\.\//, "");
546
+ projectRelative = true;
547
+ } else if (/^file:\/\//.test(source)) {
548
+ try {
549
+ return [(0, import_node_url.fileURLToPath)(source)];
550
+ } catch {
551
+ return [];
552
+ }
553
+ } else if (/^[a-z][\w+.-]*:\/\//i.test(source)) {
554
+ return [];
555
+ }
556
+ if ((0, import_node_path3.isAbsolute)(stripped)) return [stripped];
557
+ const out = [(0, import_node_path3.resolve)(mapDir, sourceRoot, stripped)];
558
+ if (projectRelative) {
559
+ for (let dir = mapDir, i = 0; i < 12; i++) {
560
+ if ((0, import_node_fs3.existsSync)((0, import_node_path3.join)(dir, "package.json"))) {
561
+ out.unshift((0, import_node_path3.join)(dir, stripped));
562
+ break;
563
+ }
564
+ const up = (0, import_node_path3.dirname)(dir);
565
+ if (up === dir) break;
566
+ dir = up;
567
+ }
568
+ }
569
+ return out;
570
+ }
571
+ function fillSourcesContent(map, mapPath) {
572
+ if (!Array.isArray(map.sources)) return 0;
573
+ const contents = Array.isArray(map.sourcesContent) ? [...map.sourcesContent] : [];
574
+ let filled = 0;
575
+ map.sources.forEach((source, i) => {
576
+ if (typeof contents[i] === "string" || typeof source !== "string") return;
577
+ if (/node_modules|^\[externals\]|\(ignored\)|^webpack\/runtime/.test(source)) return;
578
+ for (const path of sourcePathCandidates(source, mapPath, typeof map.sourceRoot === "string" ? map.sourceRoot : "")) {
579
+ if (/[\\/]node_modules[\\/]/.test(path)) continue;
580
+ try {
581
+ const stat = (0, import_node_fs3.statSync)(path);
582
+ if (!stat.isFile() || stat.size > MAX_SOURCE_BYTES) continue;
583
+ contents[i] = (0, import_node_fs3.readFileSync)(path, "utf8");
584
+ filled++;
585
+ break;
586
+ } catch {
587
+ }
588
+ }
589
+ });
590
+ if (filled) {
591
+ while (contents.length < map.sources.length) contents.push(null);
592
+ map.sourcesContent = contents.map((c) => typeof c === "string" ? c : null);
593
+ }
594
+ return filled;
595
+ }
532
596
 
533
597
  // src/sourcemaps.ts
534
598
  var JS_FILE = /\.(?:js|mjs|cjs)$/;
535
599
  function mapFor(file, code) {
536
600
  const sibling = `${file}.map`;
537
- if ((0, import_node_fs3.existsSync)(sibling)) return sibling;
538
- const url = sourceMappingUrl(code ?? (0, import_node_fs3.readFileSync)(file, "utf8"));
601
+ if ((0, import_node_fs4.existsSync)(sibling)) return sibling;
602
+ const url = sourceMappingUrl(code ?? (0, import_node_fs4.readFileSync)(file, "utf8"));
539
603
  if (!url || /^[a-z][a-z0-9+.-]*:/i.test(url)) return void 0;
540
604
  let path;
541
605
  try {
@@ -543,16 +607,16 @@ function mapFor(file, code) {
543
607
  } catch {
544
608
  return void 0;
545
609
  }
546
- const full = (0, import_node_path3.isAbsolute)(path) ? path : (0, import_node_path3.resolve)((0, import_node_path3.dirname)(file), path);
547
- return (0, import_node_fs3.existsSync)(full) ? full : void 0;
610
+ const full = (0, import_node_path4.isAbsolute)(path) ? path : (0, import_node_path4.resolve)((0, import_node_path4.dirname)(file), path);
611
+ return (0, import_node_fs4.existsSync)(full) ? full : void 0;
548
612
  }
549
613
  function findSourceFiles(dir, options = {}) {
550
- const root = (0, import_node_path3.resolve)(dir);
614
+ const root = (0, import_node_path4.resolve)(dir);
551
615
  const keep = pathFilter(options.include, options.exclude);
552
- const candidates = options.files ? options.files.map((f) => (0, import_node_path3.resolve)(f)) : walk(root);
616
+ const candidates = options.files ? options.files.map((f) => (0, import_node_path4.resolve)(f)) : walk(root);
553
617
  const out = [];
554
618
  for (const file of candidates) {
555
- if (!JS_FILE.test(file) || !(0, import_node_fs3.existsSync)(file)) continue;
619
+ if (!JS_FILE.test(file) || !(0, import_node_fs4.existsSync)(file)) continue;
556
620
  const name = relativePath(root, file);
557
621
  if (!keep(name)) continue;
558
622
  const map = mapFor(file);
@@ -566,18 +630,18 @@ function injectDirectory(dir, options = {}) {
566
630
  const out = [];
567
631
  const noSourcesContent = [];
568
632
  for (const source of files) {
569
- const code = (0, import_node_fs3.readFileSync)(source.file, "utf8");
633
+ const code = (0, import_node_fs4.readFileSync)(source.file, "utf8");
570
634
  const injected = injectCode(code, { stripSourceMappingUrl: options.stripSourceMappingUrl });
571
635
  let map;
572
636
  try {
573
- map = injectMap((0, import_node_fs3.readFileSync)(source.map, "utf8"), injected.debugId);
637
+ map = injectMap((0, import_node_fs4.readFileSync)(source.map, "utf8"), injected.debugId, source.map);
574
638
  } catch (error) {
575
639
  logger.warn(`Skipped ${source.name}: ${source.mapName} is not a readable source map (${error.message}).`);
576
640
  continue;
577
641
  }
578
642
  if (!options.dryRun) {
579
- if (injected.changed) (0, import_node_fs3.writeFileSync)(source.file, injected.code);
580
- if (map.changed) (0, import_node_fs3.writeFileSync)(source.map, map.text);
643
+ if (injected.changed) (0, import_node_fs4.writeFileSync)(source.file, injected.code);
644
+ if (map.changed) (0, import_node_fs4.writeFileSync)(source.map, map.text);
581
645
  }
582
646
  if (!map.hasSourcesContent) noSourcesContent.push(source.mapName);
583
647
  const changed = injected.changed || map.changed;
@@ -598,13 +662,13 @@ async function uploadSourcemaps(dir, connection, options = {}) {
598
662
  const result = { files: 0, artifacts: 0, bytes: 0, deleted: [], skipped: [] };
599
663
  const work = [];
600
664
  for (const source of files) {
601
- const code = (0, import_node_fs3.readFileSync)(source.file);
665
+ const code = (0, import_node_fs4.readFileSync)(source.file);
602
666
  const debugId = existingDebugId(code.toString("utf8"));
603
667
  if (!debugId) {
604
668
  result.skipped.push(source.name);
605
669
  continue;
606
670
  }
607
- work.push({ source, debugId, code, map: (0, import_node_fs3.readFileSync)(source.map) });
671
+ work.push({ source, debugId, code, map: (0, import_node_fs4.readFileSync)(source.map) });
608
672
  }
609
673
  if (result.skipped.length) {
610
674
  logger.warn(`${result.skipped.length} file(s) have a source map but no debug ID \u2014 run \`zharp sourcemaps inject\` first: ${result.skipped.slice(0, 3).join(", ")}${result.skipped.length > 3 ? ", \u2026" : ""}`);
@@ -641,13 +705,13 @@ async function uploadSourcemaps(dir, connection, options = {}) {
641
705
  function deleteSourcemaps(files, options = {}) {
642
706
  const deleted = [];
643
707
  for (const source of files) {
644
- if (options.stripSourceMappingUrl && (0, import_node_fs3.existsSync)(source.file)) {
645
- const code = (0, import_node_fs3.readFileSync)(source.file, "utf8");
708
+ if (options.stripSourceMappingUrl && (0, import_node_fs4.existsSync)(source.file)) {
709
+ const code = (0, import_node_fs4.readFileSync)(source.file, "utf8");
646
710
  const stripped = withoutSourceMappingUrl(code);
647
- if (stripped !== code) (0, import_node_fs3.writeFileSync)(source.file, stripped);
711
+ if (stripped !== code) (0, import_node_fs4.writeFileSync)(source.file, stripped);
648
712
  }
649
- if ((0, import_node_fs3.existsSync)(source.map)) {
650
- (0, import_node_fs3.unlinkSync)(source.map);
713
+ if ((0, import_node_fs4.existsSync)(source.map)) {
714
+ (0, import_node_fs4.unlinkSync)(source.map);
651
715
  deleted.push(source.mapName);
652
716
  }
653
717
  }
@@ -655,12 +719,610 @@ function deleteSourcemaps(files, options = {}) {
655
719
  }
656
720
 
657
721
  // src/version.ts
658
- var VERSION = "0.1.0";
722
+ var VERSION = "0.2.1";
723
+
724
+ // src/init/index.ts
725
+ var import_node_child_process2 = require("child_process");
726
+ var import_node_fs7 = require("fs");
727
+ var import_promises = require("readline/promises");
728
+ var import_node_path7 = require("path");
729
+
730
+ // src/init/connect.ts
731
+ var import_node_child_process = require("child_process");
732
+ var import_node_os = require("os");
733
+ var OS_NAMES = { win32: "Windows", darwin: "macOS", linux: "Linux" };
734
+ function openBrowser(url) {
735
+ if (process.env.ZHARP_NO_BROWSER || process.env.CI || process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return;
736
+ try {
737
+ const command = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
738
+ const args = process.platform === "win32" ? ["/c", "start", '""', url.replace(/&/g, "^&")] : [url];
739
+ (0, import_node_child_process.spawn)(command, args, { stdio: "ignore", detached: true }).on("error", () => {
740
+ }).unref();
741
+ } catch {
742
+ }
743
+ }
744
+ var SetupFailed = class extends Error {
745
+ };
746
+ async function connect(api, project, hooks) {
747
+ const http = hooks.fetch ?? fetch;
748
+ const sleep2 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
749
+ const base = `${api.replace(/\/+$/, "")}/api/v1/cli-setup`;
750
+ const opened = await http(`${base}/sessions`, {
751
+ method: "POST",
752
+ headers: { "content-type": "application/json", "user-agent": `zharp-cli/${VERSION}` },
753
+ body: JSON.stringify({ name: project.name, framework: project.label, platform: project.platform, os: OS_NAMES[(0, import_node_os.platform)()] ?? `${(0, import_node_os.platform)()} ${(0, import_node_os.release)()}`, cliVersion: VERSION })
754
+ }).catch((error) => {
755
+ throw new SetupFailed(`Could not reach Zharp at ${api} (${error?.cause?.code ?? error?.message ?? error}).`);
756
+ });
757
+ if (!opened.ok) throw new SetupFailed(`Zharp refused to start a setup (${opened.status}).`);
758
+ const session = (await opened.json()).data;
759
+ hooks.showCode(session.userCode, session.verificationUrl);
760
+ (hooks.openBrowser ?? openBrowser)(session.verificationUrl);
761
+ const until = Date.now() + session.expiresIn * 1e3;
762
+ while (Date.now() < until) {
763
+ await sleep2(Math.max(1, session.interval) * 1e3);
764
+ hooks.waiting?.();
765
+ const res = await http(`${base}/collect`, {
766
+ method: "POST",
767
+ headers: { "content-type": "application/json", "user-agent": `zharp-cli/${VERSION}` },
768
+ body: JSON.stringify({ deviceToken: session.deviceToken })
769
+ }).catch(() => null);
770
+ if (!res) continue;
771
+ const body = await res.json().catch(() => ({}));
772
+ if (res.status === 200 && body?.data?.status === "approved") return body.data;
773
+ if (res.status === 200) continue;
774
+ throw new SetupFailed(body?.message ?? `The setup stopped (${res.status}).`);
775
+ }
776
+ throw new SetupFailed("The code expired before it was approved. Run it again.");
777
+ }
778
+
779
+ // src/init/detect.ts
780
+ var import_node_fs5 = require("fs");
781
+ var import_node_path5 = require("path");
782
+ var read = (path) => {
783
+ try {
784
+ return (0, import_node_fs5.readFileSync)(path, "utf8");
785
+ } catch {
786
+ return null;
787
+ }
788
+ };
789
+ function majorOf(range) {
790
+ const m = /(\d+)/.exec(range ?? "");
791
+ return m ? ` ${m[1]}` : "";
792
+ }
793
+ function packageManagerOf(dir) {
794
+ if ((0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "pnpm-lock.yaml"))) return "pnpm";
795
+ if ((0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "yarn.lock"))) return "yarn";
796
+ if ((0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "bun.lockb")) || (0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "bun.lock"))) return "bun";
797
+ return "npm";
798
+ }
799
+ function detect(dir) {
800
+ const pkgText = read((0, import_node_path5.join)(dir, "package.json"));
801
+ const pkg = pkgText ? (() => {
802
+ try {
803
+ return JSON.parse(pkgText);
804
+ } catch {
805
+ return null;
806
+ }
807
+ })() : null;
808
+ const deps = { ...pkg?.dependencies ?? {}, ...pkg?.devDependencies ?? {} };
809
+ const name = typeof pkg?.name === "string" && pkg.name.replace(/^@[^/]+\//, "") || (0, import_node_path5.basename)(dir);
810
+ const base = { dir, name, packageManager: packageManagerOf(dir), typescript: !!deps.typescript || (0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "tsconfig.json")), packageJson: pkg ?? void 0 };
811
+ if (deps.next) {
812
+ const appDir = (0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "src", "app")) ? "src/app" : (0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "app")) ? "app" : void 0;
813
+ return { ...base, framework: "nextjs", label: `Next.js${majorOf(deps.next)}`, platform: "browser", appDir };
814
+ }
815
+ if (deps["@nestjs/core"]) return { ...base, framework: "nestjs", label: `NestJS${majorOf(deps["@nestjs/core"])}`, platform: "node" };
816
+ if (deps.vite && deps.react) return { ...base, framework: "vite-react", label: "React (Vite)", platform: "browser" };
817
+ if (deps.express) return { ...base, framework: "express", label: `Express${majorOf(deps.express)}`, platform: "node" };
818
+ const py = [read((0, import_node_path5.join)(dir, "requirements.txt")), read((0, import_node_path5.join)(dir, "pyproject.toml")), read((0, import_node_path5.join)(dir, "Pipfile"))].filter(Boolean).join("\n").toLowerCase();
819
+ if (py) {
820
+ const pyName = (0, import_node_path5.basename)(dir);
821
+ if (/\bdjango\b/.test(py)) return { ...base, name: pyName, framework: "django", label: "Django", platform: "python" };
822
+ if (/\bfastapi\b/.test(py)) return { ...base, name: pyName, framework: "fastapi", label: "FastAPI", platform: "python" };
823
+ if (/\bflask\b/.test(py)) return { ...base, name: pyName, framework: "flask", label: "Flask", platform: "python" };
824
+ }
825
+ const composer = read((0, import_node_path5.join)(dir, "composer.json"));
826
+ if (composer && /laravel\/framework/.test(composer)) return { ...base, name: (0, import_node_path5.basename)(dir), framework: "laravel", label: "Laravel", platform: "php" };
827
+ if ((0, import_node_fs5.existsSync)((0, import_node_path5.join)(dir, "go.mod"))) return { ...base, name: (0, import_node_path5.basename)(dir), framework: "go", label: "Go", platform: "go" };
828
+ if (pkg) return { ...base, framework: "node", label: "Node.js", platform: "node" };
829
+ return { ...base, framework: "unknown", label: "an unknown project", platform: "otel" };
830
+ }
831
+
832
+ // src/init/recipes.ts
833
+ var import_node_fs6 = require("fs");
834
+ var import_node_path6 = require("path");
835
+ var DEFAULT_API = "https://api.zharp.io";
836
+ var read2 = (dir, path) => {
837
+ try {
838
+ return (0, import_node_fs6.readFileSync)((0, import_node_path6.join)(dir, path), "utf8");
839
+ } catch {
840
+ return null;
841
+ }
842
+ };
843
+ var first = (dir, paths) => paths.find((p) => (0, import_node_fs6.existsSync)((0, import_node_path6.join)(dir, p))) ?? null;
844
+ var mentionsZharp = (text) => !!text && /@zharp\//.test(text);
845
+ function styled(text, line) {
846
+ const imports = [...text.matchAll(/^import .*$/gm)].map((m) => m[0].trimEnd());
847
+ const bare = imports.length > 0 && imports.every((l) => !l.endsWith(";"));
848
+ const double = imports.filter((l) => /from "/.test(l)).length > imports.filter((l) => /from '/.test(l)).length;
849
+ const quoted = double ? line.replace(/'([^'"]*)'/g, '"$1"') : line;
850
+ return bare ? quoted.replace(/;$/, "") : quoted;
851
+ }
852
+ function endpointOf(api) {
853
+ const clean = api.replace(/\/+$/, "");
854
+ return clean === DEFAULT_API ? null : `${clean}/api/v1/otlp`;
855
+ }
856
+ function wrapNextConfig(text, appId, esm) {
857
+ if (/withZharp/.test(text)) return null;
858
+ const exportDefault = /export\s+default\s+([\s\S]+?);?\s*$/.exec(text);
859
+ if (esm && exportDefault) {
860
+ const value = exportDefault[1].trim().replace(/;$/, "");
861
+ const head = text.slice(0, exportDefault.index);
862
+ return `import { withZharp } from '@zharp/nextjs';
863
+ ${head}export default withZharp(${value}, { app: ${appId} });
864
+ `;
865
+ }
866
+ const moduleExports = /module\.exports\s*=\s*([\s\S]+?);?\s*$/.exec(text);
867
+ if (!esm && moduleExports) {
868
+ const value = moduleExports[1].trim().replace(/;$/, "");
869
+ const head = text.slice(0, moduleExports.index);
870
+ return `const { withZharp } = require('@zharp/nextjs');
871
+ ${head}module.exports = withZharp(${value}, { app: ${appId} });
872
+ `;
873
+ }
874
+ return null;
875
+ }
876
+ function addToLayout(text, importPath) {
877
+ if (/ZharpClient/.test(text)) return null;
878
+ const body = /<body\b[^>]*>/.exec(text);
879
+ if (!body) return null;
880
+ const at = body.index + body[0].length;
881
+ const bodyIndent = /[ \t]*$/.exec(text.slice(0, body.index))[0];
882
+ const inner = `${bodyIndent} `;
883
+ const rest = text.slice(at);
884
+ const after = /^\s*\n/.test(rest) ? rest : `
885
+ ${inner}${rest.replace(/^[ \t]+/, "")}`;
886
+ const withComponent = `${text.slice(0, at)}
887
+ ${inner}<ZharpClient />${after}`;
888
+ const imports = [...withComponent.matchAll(/^import .*$/gm)];
889
+ const line = styled(text, `import { ZharpClient } from '${importPath}';`);
890
+ if (!imports.length) return `${line}
891
+ ${withComponent}`;
892
+ const last = imports[imports.length - 1];
893
+ const end = last.index + last[0].length;
894
+ return `${withComponent.slice(0, end)}
895
+ ${line}${withComponent.slice(end)}`;
896
+ }
897
+ function nextjs(project, c, api) {
898
+ const dir = project.dir;
899
+ const ts = project.typescript;
900
+ const plan = { install: ["@zharp/browser", "@zharp/node"], devInstall: ["@zharp/nextjs"], changes: [], manual: [], notes: [], env: { file: ".env.local", vars: {} } };
901
+ const endpoint = endpointOf(api);
902
+ const instrumentationPath = `${project.appDir?.startsWith("src/") ? "src/" : ""}instrumentation.${ts ? "ts" : "js"}`;
903
+ const instrumentation = [
904
+ "export async function register() {",
905
+ " if (process.env.NEXT_RUNTIME === 'nodejs') {",
906
+ " const { Zharp } = await import('@zharp/node');",
907
+ ` Zharp.init({ service: '${c.application.serviceName}' });`,
908
+ " }",
909
+ "}",
910
+ "",
911
+ "// Errors Next.js answers with an error page: reported with their route.",
912
+ `export async function onRequestError(...args${ts ? ": Parameters<typeof import('@zharp/node').Zharp.onRequestError>" : ""}) {`,
913
+ " if (process.env.NEXT_RUNTIME === 'nodejs') {",
914
+ " const { Zharp } = await import('@zharp/node');",
915
+ " Zharp.onRequestError(...args);",
916
+ " }",
917
+ "}",
918
+ ""
919
+ ].join("\n");
920
+ const existingInstrumentation = first(dir, ["instrumentation.ts", "instrumentation.js", "src/instrumentation.ts", "src/instrumentation.js"]);
921
+ if (!existingInstrumentation) plan.changes.push({ path: instrumentationPath, kind: "create", content: instrumentation, note: "starts Zharp on the server" });
922
+ else if (!mentionsZharp(read2(dir, existingInstrumentation))) plan.manual.push({ path: existingInstrumentation, why: "it already exists \u2014 add Zharp to it", snippet: instrumentation });
923
+ const configPath = first(dir, ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.cjs"]);
924
+ if (!configPath) {
925
+ plan.changes.push({ path: ts ? "next.config.ts" : "next.config.mjs", kind: "create", content: `import { withZharp } from '@zharp/nextjs';
926
+
927
+ export default withZharp({}, { app: ${c.application.id} });
928
+ `, note: "source maps uploaded on build" });
929
+ } else {
930
+ const text = read2(dir, configPath) ?? "";
931
+ const esm = /\.(ts|mjs)$/.test(configPath) || /^\s*(import|export)\s/m.test(text);
932
+ const wrapped = mentionsZharp(text) ? null : wrapNextConfig(text, c.application.id, esm);
933
+ if (wrapped) plan.changes.push({ path: configPath, kind: "edit", content: wrapped, note: "wrapped with withZharp" });
934
+ else if (!mentionsZharp(text)) plan.manual.push({ path: configPath, why: "its export isn't a plain value \u2014 wrap it yourself", snippet: `import { withZharp } from '@zharp/nextjs';
935
+
936
+ export default withZharp(nextConfig, { app: ${c.application.id} });` });
937
+ }
938
+ if (project.appDir) {
939
+ const ext = ts ? "tsx" : "jsx";
940
+ const clientPath = `${project.appDir}/zharp-client.${ext}`;
941
+ const client = [
942
+ "'use client';",
943
+ "import { Zharp } from '@zharp/browser';",
944
+ "",
945
+ "if (typeof window !== 'undefined' && !Zharp.isActive) {",
946
+ ` Zharp.init({ key: process.env.NEXT_PUBLIC_ZHARP_KEY${ts ? "!" : ""}${endpoint ? ", endpoint: process.env.NEXT_PUBLIC_ZHARP_ENDPOINT" : ""}, service: '${c.application.serviceName}' });`,
947
+ "}",
948
+ "",
949
+ "/** Starts Zharp in the browser; rendered once, in the root layout. */",
950
+ "export function ZharpClient() {",
951
+ " return null;",
952
+ "}",
953
+ ""
954
+ ].join("\n");
955
+ if (!(0, import_node_fs6.existsSync)((0, import_node_path6.join)(dir, clientPath))) plan.changes.push({ path: clientPath, kind: "create", content: client, note: `starts Zharp in the browser` });
956
+ const layoutPath = first(dir, [`${project.appDir}/layout.tsx`, `${project.appDir}/layout.jsx`, `${project.appDir}/layout.js`]);
957
+ const layout = layoutPath ? read2(dir, layoutPath) : null;
958
+ const edited = layout ? addToLayout(layout, "./zharp-client") : null;
959
+ if (layoutPath && edited) plan.changes.push({ path: layoutPath, kind: "edit", content: edited, note: "renders <ZharpClient />" });
960
+ else if (layoutPath && !/ZharpClient/.test(layout ?? "")) plan.manual.push({ path: layoutPath, why: "add the component inside <body>", snippet: "import { ZharpClient } from './zharp-client';\n\u2026\n<body>\n <ZharpClient />" });
961
+ } else {
962
+ plan.manual.push({ path: "pages/_app", why: "pages router: start Zharp in your _app", snippet: "import { Zharp } from '@zharp/browser';\n\nif (typeof window !== 'undefined') Zharp.init({ key: process.env.NEXT_PUBLIC_ZHARP_KEY });" });
963
+ }
964
+ plan.env.vars = {
965
+ NEXT_PUBLIC_ZHARP_KEY: c.application.ingestKey,
966
+ ZHARP_KEY: c.application.ingestKey,
967
+ ZHARP_AUTH_TOKEN: c.uploadKey,
968
+ ...endpoint ? { NEXT_PUBLIC_ZHARP_ENDPOINT: endpoint, ZHARP_ENDPOINT: endpoint, ZHARP_URL: api.replace(/\/+$/, "") } : {}
969
+ };
970
+ plan.notes.push("Add ZHARP_AUTH_TOKEN (and the keys) to your CI and hosting, so production builds upload their source maps.");
971
+ return plan;
972
+ }
973
+ function addVitePlugin(text, appId) {
974
+ if (/@zharp\/vite-plugin/.test(text)) return null;
975
+ const plugins = /plugins\s*:\s*\[/.exec(text);
976
+ if (!plugins) return null;
977
+ let depth = 0;
978
+ let close = -1;
979
+ for (let i = plugins.index + plugins[0].length; i < text.length; i++) {
980
+ const ch = text[i];
981
+ if (ch === "[" || ch === "(" || ch === "{") depth++;
982
+ else if (ch === "]" || ch === ")" || ch === "}") {
983
+ if (depth === 0 && ch === "]") {
984
+ close = i;
985
+ break;
986
+ }
987
+ depth--;
988
+ }
989
+ }
990
+ if (close < 0) return null;
991
+ const inside = text.slice(plugins.index + plugins[0].length, close).trimEnd();
992
+ const sep2 = inside.length === 0 ? "" : inside.endsWith(",") ? " " : ", ";
993
+ const withPlugin = `${text.slice(0, plugins.index + plugins[0].length)}${inside}${sep2}zharp({ app: ${appId} })${text.slice(close)}`;
994
+ const imports = [...withPlugin.matchAll(/^import .*$/gm)];
995
+ const line = styled(text, "import { zharp } from '@zharp/vite-plugin';");
996
+ if (!imports.length) return `${line}
997
+ ${withPlugin}`;
998
+ const last = imports[imports.length - 1];
999
+ const end = last.index + last[0].length;
1000
+ return `${withPlugin.slice(0, end)}
1001
+ ${line}${withPlugin.slice(end)}`;
1002
+ }
1003
+ function addToViteMain(text, serviceName, withEndpoint) {
1004
+ if (/@zharp\/browser/.test(text)) return null;
1005
+ const call = /createRoot\(([^()]*(?:\([^()]*\)[^()]*)*)\)/.exec(text);
1006
+ let next = text;
1007
+ if (call && !call[1].includes(",")) {
1008
+ next = `${text.slice(0, call.index)}createRoot(${call[1]}, {
1009
+ onUncaughtError: Zharp.reactErrorHandler(),
1010
+ onCaughtError: Zharp.reactErrorHandler(),
1011
+ })${text.slice(call.index + call[0].length)}`;
1012
+ }
1013
+ const imports = [...next.matchAll(/^import .*$/gm)];
1014
+ const start = styled(text, `Zharp.init({ key: import.meta.env.VITE_ZHARP_KEY${withEndpoint ? ", endpoint: import.meta.env.VITE_ZHARP_ENDPOINT" : ""}, service: '${serviceName}' });`);
1015
+ const init = `
1016
+ ${start}
1017
+ `;
1018
+ const line = styled(text, "import { Zharp } from '@zharp/browser';");
1019
+ if (!imports.length) return `${line}
1020
+ ${init}
1021
+ ${next}`;
1022
+ const last = imports[imports.length - 1];
1023
+ const end = last.index + last[0].length;
1024
+ return `${next.slice(0, end)}
1025
+ ${line}
1026
+ ${init}${next.slice(end).replace(/^\n+/, "\n")}`;
1027
+ }
1028
+ function viteReact(project, c, api) {
1029
+ const dir = project.dir;
1030
+ const endpoint = endpointOf(api);
1031
+ const plan = { install: ["@zharp/browser"], devInstall: ["@zharp/vite-plugin"], changes: [], manual: [], notes: [], env: { file: ".env.local", vars: {} } };
1032
+ const configPath = first(dir, ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"]);
1033
+ const config = configPath ? read2(dir, configPath) : null;
1034
+ const editedConfig = config ? addVitePlugin(config, c.application.id) : null;
1035
+ if (configPath && editedConfig) plan.changes.push({ path: configPath, kind: "edit", content: editedConfig, note: "source maps uploaded on build" });
1036
+ else if (!mentionsZharp(config)) plan.manual.push({ path: configPath ?? "vite.config.ts", why: "add the plugin to plugins", snippet: `import { zharp } from '@zharp/vite-plugin';
1037
+ \u2026
1038
+ plugins: [react(), zharp({ app: ${c.application.id} })]` });
1039
+ const mainPath = first(dir, ["src/main.tsx", "src/main.jsx", "src/main.ts", "src/main.js", "src/index.tsx", "src/index.jsx"]);
1040
+ const main2 = mainPath ? read2(dir, mainPath) : null;
1041
+ const editedMain = main2 ? addToViteMain(main2, c.application.serviceName, !!endpoint) : null;
1042
+ if (mainPath && editedMain) plan.changes.push({ path: mainPath, kind: "edit", content: editedMain, note: "starts Zharp; React errors with their component stack" });
1043
+ else if (!mentionsZharp(main2)) plan.manual.push({ path: mainPath ?? "src/main.tsx", why: "start Zharp before React renders", snippet: "import { Zharp } from '@zharp/browser';\n\nZharp.init({ key: import.meta.env.VITE_ZHARP_KEY });\n\ncreateRoot(el, { onUncaughtError: Zharp.reactErrorHandler(), onCaughtError: Zharp.reactErrorHandler() })" });
1044
+ plan.env.vars = {
1045
+ VITE_ZHARP_KEY: c.application.ingestKey,
1046
+ ZHARP_AUTH_TOKEN: c.uploadKey,
1047
+ ...endpoint ? { VITE_ZHARP_ENDPOINT: endpoint, ZHARP_URL: api.replace(/\/+$/, "") } : {}
1048
+ };
1049
+ plan.notes.push("Add ZHARP_AUTH_TOKEN and VITE_ZHARP_KEY to your CI, so production builds upload their source maps.");
1050
+ return plan;
1051
+ }
1052
+ function nestjs(project, c, api) {
1053
+ const dir = project.dir;
1054
+ const endpoint = endpointOf(api);
1055
+ const plan = { install: ["@zharp/node"], devInstall: [], changes: [], manual: [], notes: [], env: { file: ".env", vars: {} } };
1056
+ const ext = project.typescript ? "ts" : "js";
1057
+ const instrumentPath = `src/instrument.${ext}`;
1058
+ const instrument = [
1059
+ "import { Zharp } from '@zharp/node';",
1060
+ "",
1061
+ "// Before anything else: http, the database drivers and NestJS are instrumented as they load.",
1062
+ "try { process.loadEnvFile?.('.env'); } catch { /* no .env: the environment has the keys */ }",
1063
+ `Zharp.init({ service: '${c.application.serviceName}' });`,
1064
+ ""
1065
+ ].join("\n");
1066
+ if (!(0, import_node_fs6.existsSync)((0, import_node_path6.join)(dir, instrumentPath))) plan.changes.push({ path: instrumentPath, kind: "create", content: instrument, note: "starts Zharp before the app loads" });
1067
+ const mainPath = first(dir, [`src/main.${ext}`]);
1068
+ const main2 = mainPath ? read2(dir, mainPath) : null;
1069
+ const esm = project.packageJson?.type === "module" || /from '\.{1,2}\/[^']+\.js'/.test(main2 ?? "");
1070
+ if (esm) {
1071
+ const pkgText = read2(dir, "package.json");
1072
+ const scripts = { ...project.packageJson?.scripts ?? {} };
1073
+ const preload = "--import ./dist/instrument.js";
1074
+ let changed = false;
1075
+ for (const [name, command] of Object.entries(scripts)) {
1076
+ if (command.includes(preload)) continue;
1077
+ if (/^nest start\b/.test(command) && !/--exec\b/.test(command)) {
1078
+ scripts[name] = `${command} --exec "node ${preload}"`;
1079
+ changed = true;
1080
+ } else if (/^node (?:--[^\s]+ )*dist\/main(?:\.js)?\s*$/.test(command)) {
1081
+ scripts[name] = command.replace(/^node /, `node ${preload} `);
1082
+ changed = true;
1083
+ }
1084
+ }
1085
+ if (changed && pkgText) {
1086
+ let text = pkgText;
1087
+ for (const [name, command] of Object.entries(scripts)) {
1088
+ const before = (project.packageJson?.scripts ?? {})[name];
1089
+ if (before === command) continue;
1090
+ const line = new RegExp(`("${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}"\\s*:\\s*)${JSON.stringify(before).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
1091
+ text = text.replace(line, (_, key) => `${key}${JSON.stringify(command)}`);
1092
+ }
1093
+ plan.changes.push({ path: "package.json", kind: "edit", content: text, note: "start scripts preload Zharp (--import)" });
1094
+ }
1095
+ plan.manual.push({ path: "your start command", why: "ES modules: wherever the app is started outside these scripts (a Dockerfile, a process manager), preload Zharp", snippet: `node ${preload} dist/main.js` });
1096
+ } else if (mainPath && main2 && !main2.includes("./instrument")) {
1097
+ plan.changes.push({ path: mainPath, kind: "edit", content: `${styled(main2, "import './instrument';")}
1098
+ ${main2}`, note: "loads it first" });
1099
+ } else if (!mainPath) {
1100
+ plan.manual.push({ path: "src/main.ts", why: "import it first in your entry file", snippet: "import './instrument';" });
1101
+ }
1102
+ plan.env.vars = { ZHARP_KEY: c.application.ingestKey, ...endpoint ? { ZHARP_ENDPOINT: endpoint } : {} };
1103
+ plan.notes.push("Set ZHARP_KEY where the app runs in production.");
1104
+ return plan;
1105
+ }
1106
+ function planFor(project, c, api) {
1107
+ switch (project.framework) {
1108
+ case "nextjs":
1109
+ return nextjs(project, c, api);
1110
+ case "vite-react":
1111
+ return viteReact(project, c, api);
1112
+ case "nestjs":
1113
+ return nestjs(project, c, api);
1114
+ default:
1115
+ return null;
1116
+ }
1117
+ }
1118
+ var GUIDES = {
1119
+ express: "https://zharp.io/docs/sdks/node",
1120
+ node: "https://zharp.io/docs/sdks/node",
1121
+ django: "https://zharp.io/docs/sdks/python",
1122
+ fastapi: "https://zharp.io/docs/sdks/python",
1123
+ flask: "https://zharp.io/docs/sdks/python",
1124
+ laravel: "https://zharp.io/docs/sdks/php",
1125
+ go: "https://zharp.io/docs/sdks/go"
1126
+ };
1127
+
1128
+ // src/init/index.ts
1129
+ var green = (s) => `\x1B[32m${s}\x1B[39m`;
1130
+ var dim = (s) => `\x1B[2m${s}\x1B[22m`;
1131
+ var bold = (s) => `\x1B[1m${s}\x1B[22m`;
1132
+ var yellow = (s) => `\x1B[33m${s}\x1B[39m`;
1133
+ var bar = dim("\u2502");
1134
+ function say(line = "") {
1135
+ process.stdout.write(`${line}
1136
+ `);
1137
+ }
1138
+ function mergeEnv(existing, vars) {
1139
+ const lines = existing ? existing.replace(/\s+$/, "").split(/\r?\n/) : [];
1140
+ const seen = /* @__PURE__ */ new Set();
1141
+ const out = lines.map((line) => {
1142
+ const name = /^\s*(?:export\s+)?([A-Z0-9_]+)\s*=/.exec(line)?.[1];
1143
+ if (name && name in vars) {
1144
+ seen.add(name);
1145
+ return `${name}=${vars[name]}`;
1146
+ }
1147
+ return line;
1148
+ });
1149
+ const added = Object.entries(vars).filter(([k]) => !seen.has(k));
1150
+ if (added.length) {
1151
+ if (out.length) out.push("");
1152
+ out.push("# Zharp (npm init zharp@latest)");
1153
+ for (const [k, v] of added) out.push(`${k}=${v}`);
1154
+ }
1155
+ return `${out.join("\n")}
1156
+ `;
1157
+ }
1158
+ function ignoredByGit(gitignore, file) {
1159
+ return gitignore.split(/\r?\n/).map((l) => l.trim()).some((l) => l === file || l === `/${file}` || l === ".env*" || l === ".env*.local" && file.endsWith(".local") || l === "*.local" && file.endsWith(".local") || l === ".env.*" && file !== ".env");
1160
+ }
1161
+ function installCommand(project, packages, dev, tarballs) {
1162
+ const specs = tarballs ? packages.map((p) => (0, import_node_path7.join)(tarballs, `${p.replace("@", "").replace("/", "-")}.tgz`)) : packages;
1163
+ switch (project.packageManager) {
1164
+ case "pnpm":
1165
+ return ["pnpm", ["add", ...dev ? ["-D"] : [], ...specs]];
1166
+ case "yarn":
1167
+ return ["yarn", ["add", ...dev ? ["-D"] : [], ...specs]];
1168
+ case "bun":
1169
+ return ["bun", ["add", ...dev ? ["-d"] : [], ...specs]];
1170
+ default:
1171
+ return ["npm", ["install", ...dev ? ["--save-dev"] : [], ...specs]];
1172
+ }
1173
+ }
1174
+ async function ask(question) {
1175
+ const rl = (0, import_promises.createInterface)({ input: process.stdin, output: process.stdout });
1176
+ try {
1177
+ return (await rl.question(question)).trim().toLowerCase();
1178
+ } finally {
1179
+ rl.close();
1180
+ }
1181
+ }
1182
+ async function sendTestError(api, c) {
1183
+ const now = `${Date.now()}000000`;
1184
+ const attr = (key, value) => ({ key, value: { stringValue: value } });
1185
+ const body = {
1186
+ resourceLogs: [{
1187
+ resource: { attributes: [attr("service.name", c.application.serviceName), attr("telemetry.sdk.name", "zharp-cli")] },
1188
+ scopeLogs: [{
1189
+ logRecords: [{
1190
+ timeUnixNano: now,
1191
+ severityNumber: 17,
1192
+ severityText: "ERROR",
1193
+ body: { stringValue: "ZharpSetupTest: Zharp is connected \u2014 this is the test error npm init zharp@latest sent" },
1194
+ attributes: [
1195
+ attr("exception.type", "ZharpSetupTest"),
1196
+ attr("exception.message", "Zharp is connected \u2014 this is the test error npm init zharp@latest sent"),
1197
+ attr("exception.stacktrace", "ZharpSetupTest: Zharp is connected \u2014 this is the test error npm init zharp@latest sent\n at zharp init"),
1198
+ attr("zharp.handled", "true")
1199
+ ]
1200
+ }]
1201
+ }]
1202
+ }]
1203
+ };
1204
+ try {
1205
+ const res = await fetch(`${api.replace(/\/+$/, "")}/api/v1/otlp/v1/logs`, {
1206
+ method: "POST",
1207
+ headers: { "content-type": "application/json", authorization: `Bearer ${c.application.ingestKey}` },
1208
+ body: JSON.stringify(body)
1209
+ });
1210
+ return res.ok;
1211
+ } catch {
1212
+ return false;
1213
+ }
1214
+ }
1215
+ function showPlan(plan, c) {
1216
+ say(`${green("\u25C6")} ${bold("These changes will be made:")}`);
1217
+ const deps = [...plan.install, ...plan.devInstall];
1218
+ if (deps.length) say(`${bar} ${green("+")} install ${deps.join(" ")}`);
1219
+ for (const ch of plan.changes) say(`${bar} ${ch.kind === "create" ? green("+") : yellow("~")} ${bold(ch.path)} ${dim(ch.kind === "create" ? `(new) ${ch.note}` : ch.note)}`);
1220
+ say(`${bar} ${green("+")} ${bold(plan.env.file)} ${dim(Object.keys(plan.env.vars).join(", "))}`);
1221
+ for (const m of plan.manual) say(`${bar} ${yellow("!")} ${m.path}: ${dim(`left as it is \u2014 ${m.why}`)}`);
1222
+ void c;
1223
+ }
1224
+ async function runInit(options) {
1225
+ const dir = (0, import_node_path7.resolve)(options.dir ?? process.cwd());
1226
+ const api = (options.url ?? process.env.ZHARP_URL ?? DEFAULT_API).replace(/\/+$/, "");
1227
+ const project = detect(dir);
1228
+ say();
1229
+ say(`${green("\u25C6")} ${bold("Zharp setup")}`);
1230
+ say(`${bar} Found ${bold(project.label)} in ${dim(dir)}`);
1231
+ say(bar);
1232
+ let connected;
1233
+ try {
1234
+ connected = await connect(api, project, {
1235
+ showCode(code, url) {
1236
+ say(`${bar} Open ${url} and check this code:`);
1237
+ say(bar);
1238
+ say(`${bar} ${bold(code)}`);
1239
+ say(bar);
1240
+ say(`${bar} ${dim("Waiting for you to approve it in the browser\u2026")}`);
1241
+ }
1242
+ });
1243
+ } catch (error) {
1244
+ say(`${yellow("\u25A0")} ${error instanceof SetupFailed ? error.message : String(error)}`);
1245
+ return 1;
1246
+ }
1247
+ say(`${green("\u25C7")} Connected to ${bold(`${connected.workspace.name} / ${connected.application.name}`)}`);
1248
+ say(bar);
1249
+ const plan = planFor(project, connected, api);
1250
+ if (!plan) {
1251
+ say(`${green("\u25C6")} ${bold(`${project.label}: add the SDK with these keys`)}`);
1252
+ say(`${bar} ZHARP_KEY=${connected.application.ingestKey}`);
1253
+ say(`${bar} ${dim("Upload key (source maps): ZHARP_AUTH_TOKEN=")}${connected.uploadKey}`);
1254
+ const guide = GUIDES[project.framework];
1255
+ say(`${bar} ${dim(`How: ${guide ?? "https://zharp.io/docs"}`)}`);
1256
+ return 0;
1257
+ }
1258
+ showPlan(plan, connected);
1259
+ say(bar);
1260
+ if (options.dryRun) {
1261
+ say(`${green("\u25C7")} Dry run: nothing was changed.`);
1262
+ return 0;
1263
+ }
1264
+ if (!options.yes) {
1265
+ for (; ; ) {
1266
+ const answer = await ask(`${green("\u25C6")} Apply? ${dim("[Y]es / [n]o / show the [d]iff")} `);
1267
+ if (answer === "d" || answer === "diff") {
1268
+ for (const ch of plan.changes) {
1269
+ say(`
1270
+ ${bold(`\u2500\u2500 ${ch.path} ${ch.kind === "create" ? "(new)" : "(edited)"}`)}`);
1271
+ say(ch.content);
1272
+ }
1273
+ continue;
1274
+ }
1275
+ if (answer === "n" || answer === "no") {
1276
+ say(`${yellow("\u25A0")} Nothing was changed. The app is set up in Zharp: ${connected.appUrl}`);
1277
+ return 0;
1278
+ }
1279
+ break;
1280
+ }
1281
+ }
1282
+ for (const ch of plan.changes) {
1283
+ const path = (0, import_node_path7.join)(dir, ch.path);
1284
+ (0, import_node_fs7.mkdirSync)((0, import_node_path7.dirname)(path), { recursive: true });
1285
+ (0, import_node_fs7.writeFileSync)(path, ch.content);
1286
+ }
1287
+ const envPath = (0, import_node_path7.join)(dir, plan.env.file);
1288
+ (0, import_node_fs7.writeFileSync)(envPath, mergeEnv((0, import_node_fs7.existsSync)(envPath) ? (0, import_node_fs7.readFileSync)(envPath, "utf8") : "", plan.env.vars));
1289
+ const gitignorePath = (0, import_node_path7.join)(dir, ".gitignore");
1290
+ if ((0, import_node_fs7.existsSync)((0, import_node_path7.join)(dir, ".git")) || (0, import_node_fs7.existsSync)(gitignorePath)) {
1291
+ const gitignore = (0, import_node_fs7.existsSync)(gitignorePath) ? (0, import_node_fs7.readFileSync)(gitignorePath, "utf8") : "";
1292
+ if (!ignoredByGit(gitignore, plan.env.file)) (0, import_node_fs7.writeFileSync)(gitignorePath, `${gitignore.replace(/\s*$/, "\n")}${plan.env.file}
1293
+ `);
1294
+ }
1295
+ say(`${green("\u25C7")} Files written`);
1296
+ for (const [packages, dev] of [[plan.install, false], [plan.devInstall, true]]) {
1297
+ if (!packages.length) continue;
1298
+ const [command, args] = installCommand(project, [...packages], dev, options.tarballs);
1299
+ say(`${bar} ${dim(`${command} ${args.join(" ")}`)}`);
1300
+ const result = process.platform === "win32" ? (0, import_node_child_process2.spawnSync)([command, ...args].map((a) => /[\s"&|<>^]/.test(a) ? `"${a.replace(/"/g, '\\"')}"` : a).join(" "), { cwd: dir, stdio: "inherit", shell: true }) : (0, import_node_child_process2.spawnSync)(command, args, { cwd: dir, stdio: "inherit" });
1301
+ if (result.status !== 0) {
1302
+ say(`${yellow("\u25A0")} The install failed. Run it yourself: ${command} ${args.join(" ")}`);
1303
+ return 1;
1304
+ }
1305
+ }
1306
+ say(`${green("\u25C7")} Packages installed`);
1307
+ for (const m of plan.manual) {
1308
+ say(bar);
1309
+ say(`${yellow("!")} ${bold(m.path)} \u2014 ${m.why}:`);
1310
+ for (const line of m.snippet.split("\n")) say(`${bar} ${line}`);
1311
+ }
1312
+ for (const note of plan.notes) say(`${bar} ${yellow("!")} ${note}`);
1313
+ const sent = await sendTestError(api, connected);
1314
+ say(bar);
1315
+ say(sent ? `${green("\u25C7")} Done. Sent a test error \u2014 see it at ${connected.appUrl}` : `${green("\u25C7")} Done. Open ${connected.appUrl} \u2014 errors show up as your app sends them.`);
1316
+ return 0;
1317
+ }
659
1318
 
660
1319
  // src/cli.ts
661
1320
  var HELP = `zharp ${VERSION} \u2014 readable stack traces for Zharp
662
1321
 
663
1322
  Usage:
1323
+ zharp init Connect this project to Zharp and set it up
1324
+ (also: npm init zharp@latest)
1325
+ [--yes] [--dry-run] (signs in through the browser)
664
1326
  zharp sourcemaps inject <dir> Add debug IDs to JS files and their maps
665
1327
  zharp sourcemaps upload <dir> --app <id> Upload JS files and their maps
666
1328
  [--release <r>] [--delete-after]
@@ -701,6 +1363,8 @@ async function main(argv) {
701
1363
  exclude: { type: "string", multiple: true },
702
1364
  "delete-after": { type: "boolean" },
703
1365
  "dry-run": { type: "boolean" },
1366
+ yes: { type: "boolean", short: "y" },
1367
+ tarballs: { type: "string" },
704
1368
  url: { type: "string" },
705
1369
  help: { type: "boolean", short: "h" },
706
1370
  version: { type: "boolean", short: "v" }
@@ -715,15 +1379,19 @@ async function main(argv) {
715
1379
  console.log(HELP);
716
1380
  return;
717
1381
  }
1382
+ if (group === "init") {
1383
+ process.exitCode = await runInit({ url: values.url, yes: values.yes === true, dryRun: values["dry-run"] === true, tarballs: values.tarballs, dir: command });
1384
+ return;
1385
+ }
718
1386
  const logger = consoleLogger();
719
1387
  const dryRun = values["dry-run"] === true;
720
- const release = values.release ?? process.env.ZHARP_RELEASE;
1388
+ const release2 = values.release ?? process.env.ZHARP_RELEASE;
721
1389
  const needTarget = (what) => {
722
1390
  if (!target) fail(`${group} ${command} needs ${what}. See \`zharp --help\`.`);
723
- if (!(0, import_node_fs4.existsSync)(target)) fail(`${target} does not exist.`);
1391
+ if (!(0, import_node_fs8.existsSync)(target)) fail(`${target} does not exist.`);
724
1392
  return target;
725
1393
  };
726
- const connect = () => dryRun ? null : resolveConnection({ app: values.app, url: values.url });
1394
+ const connect2 = () => dryRun ? null : resolveConnection({ app: values.app, url: values.url });
727
1395
  switch (`${group} ${command}`) {
728
1396
  case "sourcemaps inject": {
729
1397
  const dir = needTarget("a directory");
@@ -733,9 +1401,9 @@ async function main(argv) {
733
1401
  }
734
1402
  case "sourcemaps upload": {
735
1403
  const dir = needTarget("a directory");
736
- const connection = connect();
1404
+ const connection = connect2();
737
1405
  const result = await uploadSourcemaps(dir, connection, {
738
- release,
1406
+ release: release2,
739
1407
  include: values.include,
740
1408
  exclude: values.exclude,
741
1409
  deleteAfter: values["delete-after"] === true,
@@ -748,15 +1416,15 @@ async function main(argv) {
748
1416
  case "proguard upload": {
749
1417
  const file = needTarget("the mapping.txt file");
750
1418
  if (!values.uuid) fail("proguard upload needs --uuid <uuid>: the build UUID the Zharp Gradle plugin put into the app.");
751
- await uploadProguard(file, values.uuid, connect(), { release, dryRun, logger });
1419
+ await uploadProguard(file, values.uuid, connect2(), { release: release2, dryRun, logger });
752
1420
  return;
753
1421
  }
754
1422
  case "dart-symbols upload": {
755
- await uploadDartSymbols(needTarget("the --split-debug-info directory"), connect(), { release, dryRun, logger, obfuscationMap: values["obfuscation-map"] });
1423
+ await uploadDartSymbols(needTarget("the --split-debug-info directory"), connect2(), { release: release2, dryRun, logger, obfuscationMap: values["obfuscation-map"] });
756
1424
  return;
757
1425
  }
758
1426
  case "dsym upload": {
759
- await uploadDsyms(needTarget("a .dSYM bundle or a folder of them"), connect(), { release, dryRun, logger });
1427
+ await uploadDsyms(needTarget("a .dSYM bundle or a folder of them"), connect2(), { release: release2, dryRun, logger });
760
1428
  return;
761
1429
  }
762
1430
  default: