@apotech-os/cli 2.0.0 → 2.1.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/README.md CHANGED
@@ -49,10 +49,21 @@ the browser entirely and paste a key you created by hand:
49
49
  apotech-os login --remote production --with-key
50
50
  ```
51
51
 
52
- Environment variables work too, and take no `--remote`:
52
+ Environment variables work too:
53
53
 
54
- - `WOPILO_API_URL` — server API root. No `/api` prefix is added automatically.
55
- - `WOPILO_API_KEY` — Bearer token.
54
+ - `WOPILO_API_URL` — server API root, used when no `--remote` is given. No
55
+ `/api` prefix is added automatically.
56
+ - `WOPILO_API_KEY` — Bearer token. Used when no `--remote` is given, and as a
57
+ fallback when the named remote has no key stored in `credentials.json`. A
58
+ stored key always wins over the env var.
59
+
60
+ That fallback is the headless (CI) recipe — no browser, no prompt, no
61
+ hand-written credentials file:
62
+
63
+ ```sh
64
+ apotech-os remote add --url https://your-server.example.com --as production
65
+ WOPILO_API_KEY=$SECRET apotech-os deploy --remote production
66
+ ```
56
67
 
57
68
  ## Commands
58
69
 
package/dist/index.js CHANGED
@@ -8075,6 +8075,7 @@ var import_esbuild = require("esbuild");
8075
8075
  var import_fs3 = require("fs");
8076
8076
  var import_path = require("path");
8077
8077
  var import_os2 = require("os");
8078
+ var import_url = require("url");
8078
8079
 
8079
8080
  // ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
8080
8081
  var external_exports = {};
@@ -23487,7 +23488,7 @@ Ensure the file exists and exports a default AppManifest.`
23487
23488
  const diagnostic = result.errors.map((e) => e.text).join("\n");
23488
23489
  throw new ManifestBuildError("esbuild reported errors", diagnostic);
23489
23490
  }
23490
- const mod = await import(`${outFile}?t=${Date.now()}`);
23491
+ const mod = await import(`${(0, import_url.pathToFileURL)(outFile).href}?t=${Date.now()}`);
23491
23492
  if (mod.default === void 0) {
23492
23493
  throw new ManifestBuildError(
23493
23494
  "Missing default export",
@@ -23764,6 +23765,15 @@ var ApiError = class extends Error {
23764
23765
  status;
23765
23766
  body;
23766
23767
  };
23768
+ function reportApiError(err) {
23769
+ if (!(err instanceof ApiError)) throw err;
23770
+ if (err.status === 503 && extractCode(err.body) === "LOGS_NOT_CONFIGURED") {
23771
+ console.error("Error: the server has no log file configured (APP_LOGS_FILE).");
23772
+ } else {
23773
+ console.error(`Server error (${err.status}): ${err.message}`);
23774
+ }
23775
+ process.exit(1);
23776
+ }
23767
23777
  async function syncManifest(opts) {
23768
23778
  const url2 = `${opts.baseUrl.replace(/\/$/, "")}/platform/apps/sync`;
23769
23779
  const headers = {
@@ -23809,6 +23819,61 @@ async function installApp(opts) {
23809
23819
  }
23810
23820
  return body;
23811
23821
  }
23822
+ async function fetchLogs(opts) {
23823
+ const params = new URLSearchParams();
23824
+ if (opts.app) params.set("app", opts.app);
23825
+ if (opts.function) params.set("function", opts.function);
23826
+ if (opts.run) params.set("run", opts.run);
23827
+ if (opts.level) params.set("level", opts.level);
23828
+ if (opts.from) params.set("from", opts.from);
23829
+ if (opts.until) params.set("until", opts.until);
23830
+ if (opts.afterSeq !== void 0) params.set("afterSeq", String(opts.afterSeq));
23831
+ if (opts.limit !== void 0) params.set("limit", String(opts.limit));
23832
+ return getJson(opts.baseUrl, "/platform/logs", params, opts.apiKey);
23833
+ }
23834
+ var FUNCTION_RUN_STATUSES = [
23835
+ "RUNNING",
23836
+ "COMPLETED",
23837
+ "FAILED",
23838
+ "CANCELLED",
23839
+ "QUEUED",
23840
+ "SKIPPED"
23841
+ ];
23842
+ async function fetchRuns(opts) {
23843
+ const params = new URLSearchParams();
23844
+ if (opts.appSlug) params.set("appSlug", opts.appSlug);
23845
+ if (opts.functionName) params.set("functionName", opts.functionName);
23846
+ if (opts.status) params.set("status", opts.status);
23847
+ if (opts.limit !== void 0) params.set("limit", String(opts.limit));
23848
+ if (opts.cursor) params.set("cursor", opts.cursor);
23849
+ if (opts.order) params.set("order", opts.order);
23850
+ if (opts.from) params.set("from", opts.from);
23851
+ if (opts.until) params.set("until", opts.until);
23852
+ if (opts.source) params.set("source", opts.source);
23853
+ return getJson(opts.baseUrl, "/runs", params, opts.apiKey);
23854
+ }
23855
+ async function fetchRunDetail(opts) {
23856
+ return getJson(
23857
+ opts.baseUrl,
23858
+ `/runs/${encodeURIComponent(opts.runId)}`,
23859
+ void 0,
23860
+ opts.apiKey
23861
+ );
23862
+ }
23863
+ async function getJson(baseUrl, path, params, apiKey) {
23864
+ const query = params?.toString();
23865
+ const url2 = `${baseUrl.replace(/\/$/, "")}${path}${query ? `?${query}` : ""}`;
23866
+ const headers = {};
23867
+ if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
23868
+ const res = await fetch(url2, { headers });
23869
+ const body = await res.json().catch(() => ({ message: res.statusText }));
23870
+ if (!res.ok) {
23871
+ const code = extractCode(body);
23872
+ const message = extractMessage(body) ?? `HTTP ${res.status}`;
23873
+ throw new ApiError(code ? `[${code}] ${message}` : message, res.status, body);
23874
+ }
23875
+ return body;
23876
+ }
23812
23877
  function extractMessage(body) {
23813
23878
  if (body && typeof body === "object" && "message" in body) {
23814
23879
  return String(body["message"]);
@@ -23911,7 +23976,7 @@ function getApiKey(remoteName) {
23911
23976
  }
23912
23977
  var DEFAULT_REMOTE_URL = process.env["WOPILO_API_URL"] ?? "https://wopilo.plateform.apotechstudio.com/";
23913
23978
  function resolveApiKey(remoteName) {
23914
- if (remoteName) return getApiKey(remoteName);
23979
+ if (remoteName) return getApiKey(remoteName) ?? process.env["WOPILO_API_KEY"] ?? void 0;
23915
23980
  return process.env["WOPILO_API_KEY"] ?? void 0;
23916
23981
  }
23917
23982
 
@@ -24582,6 +24647,262 @@ function buildInstallCommand() {
24582
24647
  });
24583
24648
  }
24584
24649
 
24650
+ // src/duration.ts
24651
+ var RELATIVE_DURATION = /^(\d+)(m|h|d)$/;
24652
+ var UNIT_TO_MS = {
24653
+ m: 6e4,
24654
+ h: 36e5,
24655
+ d: 864e5
24656
+ };
24657
+ function parseSince(value) {
24658
+ const match = RELATIVE_DURATION.exec(value);
24659
+ if (!match) return value;
24660
+ const amount = Number(match[1]);
24661
+ const unit = match[2];
24662
+ return new Date(Date.now() - amount * UNIT_TO_MS[unit]).toISOString();
24663
+ }
24664
+
24665
+ // src/log-format.ts
24666
+ var SHORT_RUN_ID_LENGTH = 8;
24667
+ function formatLocalTimestamp(iso) {
24668
+ const d = new Date(iso);
24669
+ const pad = (n) => String(n).padStart(2, "0");
24670
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
24671
+ }
24672
+ function formatFieldValue(value) {
24673
+ return typeof value === "object" && value !== null ? JSON.stringify(value) : String(value);
24674
+ }
24675
+ function formatFields(fields) {
24676
+ if (!fields) return "";
24677
+ return Object.entries(fields).map(([key, value]) => `${key}=${formatFieldValue(value)}`).join(" ");
24678
+ }
24679
+ function formatLogLine(line) {
24680
+ const columns = [
24681
+ formatLocalTimestamp(line.at),
24682
+ `${line.appSlug}/${line.functionName}`,
24683
+ line.runId ? `#${line.runId.slice(0, SHORT_RUN_ID_LENGTH)}` : "",
24684
+ line.level.toUpperCase().padEnd(5),
24685
+ line.message,
24686
+ formatFields(line.fields)
24687
+ ];
24688
+ return columns.filter((c) => c !== "").join(" ");
24689
+ }
24690
+
24691
+ // src/commands/logs.ts
24692
+ var LEVELS = ["debug", "info", "warn", "error"];
24693
+ var FOLLOW_MIN_INTERVAL_MS = 1e3;
24694
+ var FOLLOW_MAX_INTERVAL_MS = 5e3;
24695
+ var FOLLOW_BACKOFF_FACTOR = 1.5;
24696
+ function parseLevel(value) {
24697
+ if (!LEVELS.includes(value)) {
24698
+ throw new Error(`Invalid --level "${value}" \u2014 expected one of: ${LEVELS.join(", ")}.`);
24699
+ }
24700
+ return value;
24701
+ }
24702
+ function buildFetchOptions(appSlug, opts, baseUrl, apiKey) {
24703
+ return {
24704
+ baseUrl,
24705
+ apiKey,
24706
+ app: appSlug,
24707
+ function: opts.function,
24708
+ run: opts.run,
24709
+ level: parseLevel(opts.level),
24710
+ from: opts.since ? parseSince(opts.since) : void 0,
24711
+ limit: Number(opts.limit)
24712
+ };
24713
+ }
24714
+ function printLine(line, json2) {
24715
+ console.log(json2 ? JSON.stringify(line) : formatLogLine(line));
24716
+ }
24717
+ function warnIfEvicted(since, oldestAvailableAt) {
24718
+ if (!since || !oldestAvailableAt) return;
24719
+ if (new Date(since) < new Date(oldestAvailableAt)) {
24720
+ console.error(`note: logs before ${oldestAvailableAt} have been evicted (size cap)`);
24721
+ }
24722
+ }
24723
+ function followLogs(fetchOptions, startSeq, json2) {
24724
+ let nextSeq = startSeq;
24725
+ let intervalMs = FOLLOW_MIN_INTERVAL_MS;
24726
+ process.on("SIGINT", () => {
24727
+ process.exit(0);
24728
+ });
24729
+ const poll = async () => {
24730
+ try {
24731
+ const page = await fetchLogs({ ...fetchOptions, afterSeq: nextSeq });
24732
+ if (page.lines.length > 0) {
24733
+ for (const line of page.lines) printLine(line, json2);
24734
+ nextSeq = page.nextSeq;
24735
+ intervalMs = FOLLOW_MIN_INTERVAL_MS;
24736
+ } else {
24737
+ intervalMs = Math.min(intervalMs * FOLLOW_BACKOFF_FACTOR, FOLLOW_MAX_INTERVAL_MS);
24738
+ }
24739
+ } catch (err) {
24740
+ if (err instanceof ApiError && (err.status === 401 || err.status === 503)) {
24741
+ reportApiError(err);
24742
+ }
24743
+ const message = err instanceof Error ? err.message : String(err);
24744
+ console.error(`warning: poll failed (${message}) \u2014 retrying`);
24745
+ intervalMs = FOLLOW_MAX_INTERVAL_MS;
24746
+ }
24747
+ setTimeout(() => void poll(), intervalMs);
24748
+ };
24749
+ setTimeout(() => void poll(), intervalMs);
24750
+ }
24751
+ function buildLogsCommand() {
24752
+ return new Command("logs").description("Tail or query application logs").argument("[appSlug]", "Only logs of this app").option("--run <runId>", "Only lines of this run").option("--function <name>", "Only this function").option("--level <level>", "Minimum level (debug|info|warn|error)", "debug").option("--since <value>", "Duration (15m, 2h, 3d) or ISO 8601 datetime").option("--limit <n>", "Max lines to fetch (max 1000)", "200").option("-f, --follow", "Keep polling for new lines").option("--json", "Raw NDJSON output (one JSON line per log)").option("--remote <name>", "Named remote server to target").action(async (appSlug, opts) => {
24753
+ const baseUrl = opts.remote ? getRemoteUrl(opts.remote) : DEFAULT_REMOTE_URL;
24754
+ const apiKey = resolveApiKey(opts.remote);
24755
+ const json2 = opts.json ?? false;
24756
+ let fetchOptions;
24757
+ try {
24758
+ fetchOptions = buildFetchOptions(appSlug, opts, baseUrl, apiKey);
24759
+ } catch (err) {
24760
+ console.error(err instanceof Error ? err.message : String(err));
24761
+ process.exit(1);
24762
+ }
24763
+ try {
24764
+ const initial = await fetchLogs(fetchOptions);
24765
+ for (const line of initial.lines) printLine(line, json2);
24766
+ if (opts.follow) {
24767
+ followLogs(fetchOptions, initial.nextSeq, json2);
24768
+ return;
24769
+ }
24770
+ warnIfEvicted(fetchOptions.from, initial.oldestAvailableAt);
24771
+ } catch (err) {
24772
+ reportApiError(err);
24773
+ }
24774
+ });
24775
+ }
24776
+
24777
+ // src/commands/runs.ts
24778
+ var STATUS_ALIASES = Object.fromEntries(
24779
+ FUNCTION_RUN_STATUSES.map((status) => [status.toLowerCase(), status])
24780
+ );
24781
+ function mapStatusCsv(csv) {
24782
+ return csv.split(",").map((raw) => raw.trim()).filter((s) => s.length > 0).map((s) => STATUS_ALIASES[s.toLowerCase()] ?? s.toUpperCase()).join(",");
24783
+ }
24784
+ function formatDurationMs(ms) {
24785
+ if (ms < 1e3) return `${ms}ms`;
24786
+ const totalSeconds = Math.floor(ms / 1e3);
24787
+ const minutes = Math.floor(totalSeconds / 60);
24788
+ const seconds = totalSeconds % 60;
24789
+ return minutes === 0 ? `${seconds}s` : `${minutes}m${seconds}s`;
24790
+ }
24791
+ function formatDuration(run) {
24792
+ if (!run.startedAt) return "-";
24793
+ const end = run.endedAt ?? (run.status === "RUNNING" ? (/* @__PURE__ */ new Date()).toISOString() : void 0);
24794
+ if (!end) return "-";
24795
+ return formatDurationMs(new Date(end).getTime() - new Date(run.startedAt).getTime());
24796
+ }
24797
+ function appFunctionLabel(run) {
24798
+ if (run.source === "app") return `${run.appSlug ?? "?"}/${run.functionName ?? run.functionId}`;
24799
+ return run.functionSlug ?? run.functionId;
24800
+ }
24801
+ function triggerLabel(run) {
24802
+ if (run.triggerType) return run.triggerType;
24803
+ if (run.cronSchedule) return `cron(${run.cronSchedule})`;
24804
+ if (run.eventName) return run.eventName;
24805
+ return "-";
24806
+ }
24807
+ function renderTable(headers, rows) {
24808
+ const widths = headers.map(
24809
+ (header, i) => Math.max(header.length, ...rows.map((row) => (row[i] ?? "").length))
24810
+ );
24811
+ const renderRow = (cells) => cells.map((cell, i) => cell.padEnd(widths[i] ?? 0)).join(" ").trimEnd();
24812
+ return [renderRow(headers), ...rows.map(renderRow)].join("\n");
24813
+ }
24814
+ function renderRunsTable(runs) {
24815
+ if (runs.length === 0) return "No runs found.";
24816
+ const headers = ["STATUS", "RUN ID", "APP/FUNCTION", "TRIGGER", "STARTED", "DURATION"];
24817
+ const rows = runs.map((run) => [
24818
+ run.status,
24819
+ run.id,
24820
+ appFunctionLabel(run),
24821
+ triggerLabel(run),
24822
+ formatLocalTimestamp(run.startedAt ?? run.queuedAt),
24823
+ formatDuration(run)
24824
+ ]);
24825
+ return renderTable(headers, rows);
24826
+ }
24827
+ function renderRunDetail(detail) {
24828
+ const lines = [
24829
+ `Status: ${detail.status}`,
24830
+ `Function: ${appFunctionLabel(detail)}`,
24831
+ `Trigger: ${triggerLabel(detail)}`,
24832
+ `Run ID: ${detail.id}`,
24833
+ `Queued: ${formatLocalTimestamp(detail.queuedAt)}`,
24834
+ `Started: ${detail.startedAt ? formatLocalTimestamp(detail.startedAt) : "-"}`,
24835
+ `Ended: ${detail.endedAt ? formatLocalTimestamp(detail.endedAt) : "-"}`,
24836
+ `Duration: ${formatDuration(detail)}`
24837
+ ];
24838
+ if (detail.error) {
24839
+ lines.push("", `Error: ${detail.error}`);
24840
+ }
24841
+ if (detail.steps.length > 0) {
24842
+ lines.push("", "Steps:");
24843
+ for (const step of detail.steps) {
24844
+ const duration3 = step.durationMs !== null && step.durationMs !== void 0 ? formatDurationMs(step.durationMs) : "-";
24845
+ lines.push(` - ${step.name} [${step.status}] ${duration3}`);
24846
+ }
24847
+ }
24848
+ return lines.join("\n");
24849
+ }
24850
+ function buildListCommand() {
24851
+ return new Command("list").description("List job/function runs").argument("[appSlug]", "Only runs of this app").option("--status <statuses>", "CSV of queued|running|completed|failed|cancelled|skipped").option("--function <name>", "Only this function").option("--since <value>", "Duration (15m, 2h, 3d) or ISO 8601 datetime", "24h").option("--limit <n>", "Max runs to fetch (max 100)", "50").option("--json", "Output the raw response as JSON").option("--remote <name>", "Named remote server to target").action(async (appSlug, opts) => {
24852
+ const baseUrl = opts.remote ? getRemoteUrl(opts.remote) : DEFAULT_REMOTE_URL;
24853
+ const apiKey = resolveApiKey(opts.remote);
24854
+ try {
24855
+ const page = await fetchRuns({
24856
+ baseUrl,
24857
+ apiKey,
24858
+ appSlug,
24859
+ functionName: opts.function,
24860
+ status: opts.status ? mapStatusCsv(opts.status) : void 0,
24861
+ from: parseSince(opts.since),
24862
+ limit: Number(opts.limit),
24863
+ source: appSlug ? "app" : "both"
24864
+ });
24865
+ if (opts.json) {
24866
+ console.log(JSON.stringify(page));
24867
+ } else {
24868
+ console.log(renderRunsTable(page.runs));
24869
+ }
24870
+ } catch (err) {
24871
+ reportApiError(err);
24872
+ }
24873
+ });
24874
+ }
24875
+ function buildShowCommand() {
24876
+ return new Command("show").description("Show detail for one run").argument("<runId>", "Run ID").option("--logs", "Also fetch and print the run's ctx.logger lines").option("--json", "Output the raw response as JSON").option("--remote <name>", "Named remote server to target").action(async (runId, opts) => {
24877
+ const baseUrl = opts.remote ? getRemoteUrl(opts.remote) : DEFAULT_REMOTE_URL;
24878
+ const apiKey = resolveApiKey(opts.remote);
24879
+ try {
24880
+ const [detail, logs] = await Promise.all([
24881
+ fetchRunDetail({ baseUrl, apiKey, runId }),
24882
+ opts.logs ? fetchLogs({ baseUrl, apiKey, run: runId }) : void 0
24883
+ ]);
24884
+ const logLines = logs?.lines;
24885
+ if (opts.json) {
24886
+ console.log(JSON.stringify(logLines ? { ...detail, logs: logLines } : detail));
24887
+ return;
24888
+ }
24889
+ console.log(renderRunDetail(detail));
24890
+ if (logLines) {
24891
+ console.log("\nLogs:");
24892
+ for (const line of logLines) console.log(formatLogLine(line));
24893
+ }
24894
+ } catch (err) {
24895
+ reportApiError(err);
24896
+ }
24897
+ });
24898
+ }
24899
+ function buildRunsCommand() {
24900
+ const runs = new Command("runs").description("Inspect job/function runs");
24901
+ runs.addCommand(buildListCommand());
24902
+ runs.addCommand(buildShowCommand());
24903
+ return runs;
24904
+ }
24905
+
24585
24906
  // src/index.ts
24586
24907
  function readVersion() {
24587
24908
  try {
@@ -24600,6 +24921,8 @@ program2.addCommand(buildLoginCommand());
24600
24921
  program2.addCommand(buildBuildCommand());
24601
24922
  program2.addCommand(buildPublishCommand());
24602
24923
  program2.addCommand(buildInstallCommand());
24924
+ program2.addCommand(buildLogsCommand());
24925
+ program2.addCommand(buildRunsCommand());
24603
24926
  program2.parseAsync(process.argv).catch((err) => {
24604
24927
  console.error(err instanceof Error ? err.message : String(err));
24605
24928
  process.exit(1);