@zharp/cli 0.3.0 → 0.4.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/cli.js CHANGED
@@ -905,7 +905,7 @@ function deleteSourcemaps(files, options = {}) {
905
905
  }
906
906
 
907
907
  // src/version.ts
908
- var VERSION = "0.3.0";
908
+ var VERSION = "0.4.0";
909
909
 
910
910
  // src/init/index.ts
911
911
  var import_node_child_process3 = require("child_process");
@@ -936,7 +936,7 @@ async function connect(api, project, hooks) {
936
936
  const opened = await http(`${base}/sessions`, {
937
937
  method: "POST",
938
938
  headers: { "content-type": "application/json", "user-agent": `zharp-cli/${VERSION}` },
939
- 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 })
939
+ body: JSON.stringify({ name: project.name, framework: project.label, catalog: project.catalog, platform: project.platform, os: OS_NAMES[(0, import_node_os.platform)()] ?? `${(0, import_node_os.platform)()} ${(0, import_node_os.release)()}`, cliVersion: VERSION })
940
940
  }).catch((error) => {
941
941
  throw new SetupFailed(`Could not reach Zharp at ${api} (${error?.cause?.code ?? error?.message ?? error}).`);
942
942
  });
@@ -965,6 +965,29 @@ async function connect(api, project, hooks) {
965
965
  // src/init/detect.ts
966
966
  var import_node_fs8 = require("fs");
967
967
  var import_node_path7 = require("path");
968
+ var PYTHON_FRAMEWORKS = [
969
+ { id: "chalice", requirement: /\bchalice\b/, catalog: "Chalice" },
970
+ { id: "sanic", requirement: /\bsanic\b/, catalog: "Sanic" },
971
+ { id: "quart", requirement: /\bquart\b/, catalog: "Quart" },
972
+ { id: "starlette", requirement: /\bstarlette\b/, catalog: "Starlette" },
973
+ { id: "falcon", requirement: /\bfalcon\b/, catalog: "Falcon" },
974
+ { id: "tornado", requirement: /\btornado\b/, catalog: "Tornado" },
975
+ { id: "pyramid", requirement: /\bpyramid\b/, catalog: "Pyramid" },
976
+ { id: "aiohttp", requirement: /\baiohttp\b/, catalog: "AIOHTTP" },
977
+ { id: "bottle", requirement: /\bbottle\b/, catalog: "Bottle" },
978
+ { id: "celery", requirement: /\bcelery\b/, catalog: "Celery" },
979
+ { id: "rq", requirement: /^\s*rq\b|["']rq\b/m, catalog: "RQ (Redis Queue)" }
980
+ ];
981
+ var GO_ROUTERS = [
982
+ { id: "gin", module: /github\.com\/gin-gonic\/gin\b/, catalog: "Gin" },
983
+ { id: "echo", module: /github\.com\/labstack\/echo\b/, catalog: "Echo" },
984
+ { id: "fiber", module: /github\.com\/gofiber\/fiber\/v2\b/, catalog: "Fiber" },
985
+ { id: "iris", module: /github\.com\/kataras\/iris\/v12\b/, catalog: "Iris" },
986
+ { id: "fasthttp", module: /github\.com\/valyala\/fasthttp\b/, catalog: "FastHTTP" },
987
+ // Negroni first: a Negroni app often routes with gorilla/mux (both are set up).
988
+ { id: "negroni", module: /github\.com\/urfave\/negroni\b/, catalog: "Negroni" },
989
+ { id: "gorilla", module: /github\.com\/gorilla\/mux\b/, catalog: "Go" }
990
+ ];
968
991
  var read = (path) => {
969
992
  try {
970
993
  return (0, import_node_fs8.readFileSync)(path, "utf8");
@@ -994,31 +1017,38 @@ function detect(dir) {
994
1017
  const deps = { ...pkg?.dependencies ?? {}, ...pkg?.devDependencies ?? {} };
995
1018
  const name = typeof pkg?.name === "string" && pkg.name.replace(/^@[^/]+\//, "") || (0, import_node_path7.basename)(dir);
996
1019
  const base = { dir, name, packageManager: packageManagerOf(dir), typescript: !!deps.typescript || (0, import_node_fs8.existsSync)((0, import_node_path7.join)(dir, "tsconfig.json")), packageJson: pkg ?? void 0 };
997
- if (deps.expo) return { ...base, framework: "expo", label: `Expo${majorOf(deps.expo).replace(/^ (\d+)$/, " SDK $1")}`, platform: "react-native" };
998
- if (deps["react-native"]) return { ...base, framework: "react-native", label: `React Native${/(\d+\.\d+)/.exec(deps["react-native"])?.[1] ? ` ${/(\d+\.\d+)/.exec(deps["react-native"])[1]}` : ""}`, platform: "react-native" };
1020
+ if (deps.expo) return { ...base, framework: "expo", label: `Expo${majorOf(deps.expo).replace(/^ (\d+)$/, " SDK $1")}`, catalog: "React Native", platform: "react-native" };
1021
+ if (deps["react-native"]) return { ...base, framework: "react-native", label: `React Native${/(\d+\.\d+)/.exec(deps["react-native"])?.[1] ? ` ${/(\d+\.\d+)/.exec(deps["react-native"])[1]}` : ""}`, catalog: "React Native", platform: "react-native" };
999
1022
  if (deps.next) {
1000
1023
  const appDir = (0, import_node_fs8.existsSync)((0, import_node_path7.join)(dir, "src", "app")) ? "src/app" : (0, import_node_fs8.existsSync)((0, import_node_path7.join)(dir, "app")) ? "app" : void 0;
1001
- return { ...base, framework: "nextjs", label: `Next.js${majorOf(deps.next)}`, platform: "browser", appDir };
1002
- }
1003
- if (deps["@nestjs/core"]) return { ...base, framework: "nestjs", label: `NestJS${majorOf(deps["@nestjs/core"])}`, platform: "node" };
1004
- if (deps.vite && deps.react) return { ...base, framework: "vite-react", label: "React (Vite)", platform: "browser" };
1005
- if (deps.express) return { ...base, framework: "express", label: `Express${majorOf(deps.express)}`, platform: "node" };
1024
+ return { ...base, framework: "nextjs", label: `Next.js${majorOf(deps.next)}`, catalog: "Next.js", platform: "browser", appDir };
1025
+ }
1026
+ if (deps["@nestjs/core"]) return { ...base, framework: "nestjs", label: `NestJS${majorOf(deps["@nestjs/core"])}`, catalog: "NestJS", platform: "node" };
1027
+ if (deps.vite && deps.react) return { ...base, framework: "vite-react", label: "React (Vite)", catalog: "React", platform: "browser" };
1028
+ if (deps.express) return { ...base, framework: "express", label: `Express${majorOf(deps.express)}`, catalog: "Express", platform: "node" };
1029
+ if (deps.fastify) return { ...base, framework: "fastify", label: `Fastify${majorOf(deps.fastify)}`, catalog: "Fastify", platform: "node" };
1030
+ if (deps.koa) return { ...base, framework: "koa", label: `Koa${majorOf(deps.koa)}`, catalog: "Koa", platform: "node" };
1031
+ if (deps["@hapi/hapi"]) return { ...base, framework: "hapi", label: `Hapi${majorOf(deps["@hapi/hapi"])}`, catalog: "Hapi", platform: "node" };
1032
+ if (deps.connect) return { ...base, framework: "connect", label: "Connect", catalog: "Connect", platform: "node" };
1006
1033
  const py = [read((0, import_node_path7.join)(dir, "requirements.txt")), read((0, import_node_path7.join)(dir, "pyproject.toml")), read((0, import_node_path7.join)(dir, "Pipfile"))].filter(Boolean).join("\n").toLowerCase();
1007
1034
  if (py) {
1008
1035
  const pyName = (0, import_node_path7.basename)(dir);
1009
- if (/\bdjango\b/.test(py)) return { ...base, name: pyName, framework: "django", label: "Django", platform: "python" };
1010
- if (/\bfastapi\b/.test(py)) return { ...base, name: pyName, framework: "fastapi", label: "FastAPI", platform: "python" };
1011
- if (/\bflask\b/.test(py)) return { ...base, name: pyName, framework: "flask", label: "Flask", platform: "python" };
1036
+ if (/\bdjango\b/.test(py)) return { ...base, name: pyName, framework: "django", label: "Django", catalog: "Django", platform: "python" };
1037
+ if (/\bfastapi\b/.test(py)) return { ...base, name: pyName, framework: "fastapi", label: "FastAPI", catalog: "FastAPI", platform: "python" };
1038
+ if (/\bflask\b/.test(py)) return { ...base, name: pyName, framework: "flask", label: "Flask", catalog: "Flask", platform: "python" };
1039
+ const more = PYTHON_FRAMEWORKS.find((f) => f.requirement.test(py));
1040
+ if (more) return { ...base, name: pyName, framework: more.id, label: more.catalog, catalog: more.catalog, platform: "python" };
1012
1041
  }
1013
1042
  const composer = read((0, import_node_path7.join)(dir, "composer.json"));
1014
- if (composer && /laravel\/framework/.test(composer)) return { ...base, name: (0, import_node_path7.basename)(dir), framework: "laravel", label: "Laravel", platform: "php" };
1043
+ if (composer && /laravel\/framework/.test(composer)) return { ...base, name: (0, import_node_path7.basename)(dir), framework: "laravel", label: "Laravel", catalog: "Laravel", platform: "php" };
1015
1044
  const goMod = read((0, import_node_path7.join)(dir, "go.mod"));
1016
1045
  if (goMod !== null) {
1017
- const router = /github\.com\/gin-gonic\/gin/.test(goMod) ? " (Gin)" : /github\.com\/labstack\/echo/.test(goMod) ? " (Echo)" : "";
1046
+ const router = GO_ROUTERS.find((r) => r.module.test(goMod));
1018
1047
  const moduleName = /^module\s+(\S+)/m.exec(goMod)?.[1]?.split("/").pop();
1019
- return { ...base, name: moduleName || (0, import_node_path7.basename)(dir), framework: "go", label: `Go${router}`, platform: "go" };
1048
+ const label = router ? `Go (${router.id === "gorilla" ? "gorilla/mux" : router.catalog})` : "Go";
1049
+ return { ...base, name: moduleName || (0, import_node_path7.basename)(dir), framework: "go", label, catalog: router?.catalog ?? "Go", goRouter: router?.id, platform: "go" };
1020
1050
  }
1021
- if (pkg) return { ...base, framework: "node", label: "Node.js", platform: "node" };
1051
+ if (pkg) return { ...base, framework: "node", label: "Node.js", catalog: "Node.js", platform: "node" };
1022
1052
  return { ...base, framework: "unknown", label: "an unknown project", platform: "otel" };
1023
1053
  }
1024
1054
 
@@ -1094,7 +1124,7 @@ function express(project, c, api) {
1094
1124
  const instrumentName = ts ? "instrument.ts" : esm ? entry.endsWith(".mjs") ? "instrument.mjs" : "instrument.js" : entry.endsWith(".cjs") ? "instrument.cjs" : "instrument.js";
1095
1125
  const instrumentPath = `${dirOf}${instrumentName}`;
1096
1126
  const body = [
1097
- "// Before anything else: http, express and the database drivers are instrumented as they load.",
1127
+ "// Before anything else: http, the framework and the database drivers are instrumented as they load.",
1098
1128
  "try { process.loadEnvFile?.('.env'); } catch { /* no .env: the environment has the key */ }",
1099
1129
  `Zharp.init({ service: '${c.application.serviceName}' });`,
1100
1130
  ""
@@ -1124,15 +1154,30 @@ function express(project, c, api) {
1124
1154
  ${main2}`, note: "loads it first" });
1125
1155
  return plan;
1126
1156
  }
1127
- function pythonInit(c, api) {
1157
+ function pythonInit(c, api, logs = false) {
1128
1158
  const endpoint = otlpOf(api);
1129
1159
  return [
1130
1160
  "import zharp",
1131
1161
  "",
1132
1162
  "# The app's key can only send data to this app, so it is safe in code.",
1133
- `zharp.init(key="${c.application.ingestKey}", service="${c.application.serviceName}"${endpoint ? `, endpoint="${api.replace(/\/+$/, "")}/api/v1/otlp"` : ""})`
1163
+ `zharp.init(key="${c.application.ingestKey}", service="${c.application.serviceName}"${endpoint ? `, endpoint="${api.replace(/\/+$/, "")}/api/v1/otlp"` : ""}${logs ? ", logs=True" : ""})`
1134
1164
  ].join("\n");
1135
1165
  }
1166
+ var PYTHON_APP = {
1167
+ fastapi: { marker: /\bFastAPI\(/, where: "the file that creates FastAPI()" },
1168
+ flask: { marker: /\bFlask\(\s*__name__/, where: "the file that creates Flask(__name__)" },
1169
+ chalice: { marker: /\bChalice\(/, where: "app.py, before Chalice(...)" },
1170
+ sanic: { marker: /\bSanic\(/, where: "the file that creates Sanic(...)" },
1171
+ quart: { marker: /\bQuart\(/, where: "the file that creates Quart(__name__)" },
1172
+ starlette: { marker: /\bStarlette\(/, where: "the file that creates Starlette(...)" },
1173
+ falcon: { marker: /\bfalcon\.(?:asgi\.)?(?:App|API)\(/, where: "the file that creates falcon.App()" },
1174
+ tornado: { marker: /\b(?:tornado\.web\.)?Application\(/, where: "the file that creates the tornado Application" },
1175
+ pyramid: { marker: /\bConfigurator\(/, where: "the file that creates the Configurator" },
1176
+ aiohttp: { marker: /\bweb\.Application\(/, where: "the file that creates web.Application()" },
1177
+ bottle: { marker: /\bBottle\(|\bbottle\.run\(|^\s*run\(/m, where: "the file that creates the Bottle app" },
1178
+ celery: { marker: /\bCelery\(/, where: "the module that creates your Celery app" },
1179
+ rq: { marker: /\bWorker\(|\bQueue\(/, where: "the module your RQ worker imports" }
1180
+ };
1136
1181
  function afterPythonImports(text, block) {
1137
1182
  if (/^\s*import zharp\b/m.test(text)) return null;
1138
1183
  const lines = text.split("\n");
@@ -1181,12 +1226,12 @@ function python(project, c, api) {
1181
1226
  plan.changes.push(...installed2.changes);
1182
1227
  plan.commands = installed2.commands;
1183
1228
  plan.manual.push(...installed2.manual);
1184
- const block = pythonInit(c, api);
1229
+ const block = pythonInit(c, api, project.framework === "chalice");
1185
1230
  let targets = [];
1186
1231
  if (project.framework === "django") {
1187
1232
  targets = [first(project.dir, ["manage.py"]), ...findFiles(project.dir, "wsgi.py"), ...findFiles(project.dir, "asgi.py")].filter((p) => !!p);
1188
1233
  } else {
1189
- const marker = project.framework === "fastapi" ? /\bFastAPI\(/ : /\bFlask\(\s*__name__/;
1234
+ const { marker } = PYTHON_APP[project.framework];
1190
1235
  const files = findFiles(project.dir, ".py").filter((f) => marker.test(read2(project.dir, f) ?? ""));
1191
1236
  const preferred = files.find((f) => /(^|\/)(main|app|server|wsgi|__init__)\.py$/.test(f)) ?? files[0];
1192
1237
  if (preferred) targets = [preferred];
@@ -1197,7 +1242,7 @@ function python(project, c, api) {
1197
1242
  if (edited) plan.changes.push({ path, kind: "edit", content: edited, note: "starts Zharp" });
1198
1243
  }
1199
1244
  if (!targets.length) {
1200
- const where = project.framework === "django" ? "manage.py, wsgi.py and asgi.py" : project.framework === "fastapi" ? "the file that creates FastAPI()" : "the file that creates Flask(__name__)";
1245
+ const where = project.framework === "django" ? "manage.py, wsgi.py and asgi.py" : PYTHON_APP[project.framework].where;
1201
1246
  plan.manual.push({ path: where, why: "start Zharp at the top, after the imports", snippet: block });
1202
1247
  }
1203
1248
  return plan;
@@ -1221,21 +1266,37 @@ function editGoMain(text, c, api, routers) {
1221
1266
  const stdlib = [];
1222
1267
  if (!/^\s*"context"$/m.test(imports)) stdlib.push(' "context"');
1223
1268
  const add = [` zharp "${GO_MODULE}"`];
1224
- let routerLine = "";
1225
1269
  let next = text;
1270
+ const addAfter = (after, line) => {
1271
+ next = next.replace(after[0], `${after[0]}${after[1]}${line}
1272
+ `);
1273
+ };
1226
1274
  const gin = routers.gin ? /^(\s*)(\w+) := gin\.(?:Default|New)\(\)\n/m.exec(next) : null;
1227
1275
  const echo = routers.echo ? /^(\s*)(\w+) := echo\.New\(\)\n/m.exec(next) : null;
1276
+ const fiber = routers.fiber ? /^(\s*)(\w+) := fiber\.New\([^\n]*\)\n/m.exec(next) : null;
1277
+ const iris = routers.iris ? /^(\s*)(\w+) := iris\.(?:New|Default)\(\)\n/m.exec(next) : null;
1228
1278
  if (gin) {
1229
1279
  add.push(` "${GO_MODULE}/zharpgin"`);
1230
- routerLine = `${gin[1]}${gin[2]}.Use(zharpgin.Middleware())
1231
- `;
1232
- next = next.replace(gin[0], gin[0] + routerLine);
1280
+ addAfter(gin, `${gin[2]}.Use(zharpgin.Middleware())`);
1233
1281
  } else if (echo) {
1234
1282
  add.push(` "${GO_MODULE}/zharpecho"`);
1235
- routerLine = `${echo[1]}${echo[2]}.Use(zharpecho.Middleware())
1236
- `;
1237
- next = next.replace(echo[0], echo[0] + routerLine);
1283
+ addAfter(echo, `${echo[2]}.Use(zharpecho.Middleware())`);
1284
+ } else if (fiber) {
1285
+ add.push(` "${GO_MODULE}/zharpfiber"`);
1286
+ const recover = new RegExp(String.raw`^([ \t]*)${fiber[2]}\.Use\(recover\.New\([^\n]*\)\)\n`, "m").exec(next);
1287
+ addAfter(recover ?? fiber, `${fiber[2]}.Use(zharpfiber.Middleware())`);
1288
+ } else if (iris) {
1289
+ add.push(` "${GO_MODULE}/zharpiris"`);
1290
+ addAfter(iris, `${iris[2]}.UseRouter(zharpiris.Middleware())`);
1291
+ } else if (routers.fasthttp && /fasthttp\.ListenAndServe\(/.test(next)) {
1292
+ add.push(` "${GO_MODULE}/zharpfasthttp"`);
1293
+ next = next.replace(/fasthttp\.ListenAndServe\(([^,]+),\s*([\w.]+)\)/, (_, addr, handler) => `fasthttp.ListenAndServe(${addr}, zharpfasthttp.Handler(${handler}))`);
1238
1294
  } else {
1295
+ const gorilla = routers.gorilla ? /^(\s*)(\w+) := mux\.NewRouter\(\)\n/m.exec(next) : null;
1296
+ if (gorilla) {
1297
+ add.push(` "${GO_MODULE}/zharpmux"`);
1298
+ addAfter(gorilla, `${gorilla[2]}.Use(zharpmux.Middleware())`);
1299
+ }
1239
1300
  next = next.replace(/http\.ListenAndServe\(([^,]+),\s*(nil|[\w.]+)\)/, (_, addr, handler) => `http.ListenAndServe(${addr}, zharp.Handler(${handler === "nil" ? "http.DefaultServeMux" : handler}))`);
1240
1301
  }
1241
1302
  const endpoint = otlpOf(api);
@@ -1264,17 +1325,21 @@ function groupedImports(body, stdlib, modules) {
1264
1325
  function go(project, c, api) {
1265
1326
  const plan = emptyPlan(null);
1266
1327
  const goMod = read2(project.dir, "go.mod") ?? "";
1267
- const routers = { gin: /github\.com\/gin-gonic\/gin/.test(goMod), echo: /github\.com\/labstack\/echo/.test(goMod) };
1328
+ const routers = Object.fromEntries(GO_ROUTERS.map((r) => [r.id, r.module.test(goMod)]));
1268
1329
  plan.commands = [{ label: `go get ${GO_MODULE}`, argv: ["go", "get", `${GO_MODULE}@latest`] }];
1269
- if (routers.gin) plan.commands.push({ label: "go get \u2026/zharpgin", argv: ["go", "get", `${GO_MODULE}/zharpgin@latest`] });
1270
- else if (routers.echo) plan.commands.push({ label: "go get \u2026/zharpecho", argv: ["go", "get", `${GO_MODULE}/zharpecho@latest`] });
1271
1330
  const mainPath = first(project.dir, ["main.go", "cmd/server/main.go", "cmd/api/main.go", "cmd/main.go"]) ?? findFiles(project.dir, "main.go").find((f) => /func main\(\)/.test(read2(project.dir, f) ?? "")) ?? null;
1272
1331
  const text = mainPath ? read2(project.dir, mainPath) : null;
1273
1332
  const edited = text ? editGoMain(text, c, api, routers) : null;
1274
1333
  if (mainPath && edited) {
1275
- plan.changes.push({ path: mainPath, kind: "edit", content: edited, note: `starts Zharp${routers.gin ? "; traces Gin" : routers.echo ? "; traces Echo" : ""}` });
1334
+ const module2 = /"github\.com\/zharp-io\/zharp-go-lib\/(zharp\w+)"/.exec(edited)?.[1];
1335
+ if (module2) plan.commands.push({ label: `go get \u2026/${module2}`, argv: ["go", "get", `${GO_MODULE}/${module2}@latest`] });
1336
+ const traced = { zharpgin: "Gin", zharpecho: "Echo", zharpfiber: "Fiber", zharpiris: "Iris", zharpfasthttp: "fasthttp", zharpmux: "gorilla/mux" }[module2 ?? ""];
1337
+ plan.changes.push({ path: mainPath, kind: "edit", content: edited, note: `starts Zharp${traced ? `; traces ${traced}` : edited.includes("zharp.Handler(") ? "; traces requests" : ""}` });
1276
1338
  plan.commands.push({ label: "go mod tidy", argv: ["go", "mod", "tidy"] });
1277
1339
  plan.commands.push({ label: `gofmt -w ${mainPath}`, argv: ["gofmt", "-w", mainPath] });
1340
+ if (!/zharp\.Handler\(|zharp\w+\.(Middleware|Handler)\(/.test(edited)) {
1341
+ plan.manual.push({ path: mainPath, why: "trace incoming requests: wrap the handler your server runs", snippet: routers.negroni ? 'http.ListenAndServe(":3000", zharp.Handler(n)) // instead of n.Run(":3000")' : 'http.ListenAndServe(":8080", zharp.Handler(mux))' });
1342
+ }
1278
1343
  } else if (!text?.includes(GO_MODULE)) {
1279
1344
  plan.manual.push({ path: mainPath ?? "main.go", why: "start Zharp first in main()", snippet: `shutdown := zharp.Init(zharp.Config{Key: "${c.application.ingestKey}"})
1280
1345
  defer shutdown(context.Background())` });
@@ -1284,6 +1349,10 @@ defer shutdown(context.Background())` });
1284
1349
  function morePlanFor(project, c, api) {
1285
1350
  switch (project.framework) {
1286
1351
  case "express":
1352
+ case "koa":
1353
+ case "hapi":
1354
+ case "fastify":
1355
+ case "connect":
1287
1356
  return express(project, c, api);
1288
1357
  case "django":
1289
1358
  case "fastapi":
@@ -1294,7 +1363,7 @@ function morePlanFor(project, c, api) {
1294
1363
  case "go":
1295
1364
  return go(project, c, api);
1296
1365
  default:
1297
- return null;
1366
+ return PYTHON_FRAMEWORKS.some((f) => f.id === project.framework) ? python(project, c, api) : null;
1298
1367
  }
1299
1368
  }
1300
1369