@zinn-dev/cli 0.43.0 → 0.45.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.
Files changed (78) hide show
  1. package/README.md +1 -1
  2. package/index.js +3 -3
  3. package/package.json +7 -4
  4. package/skills/zinn/SKILL.md +7 -9
  5. package/src/actor.d.ts +8 -0
  6. package/src/actor.js +5 -1
  7. package/src/capabilities-schema.d.ts +6 -2
  8. package/src/column-hint.js +2 -5
  9. package/src/database.d.ts +1 -2
  10. package/src/database.js +1 -6
  11. package/src/duration-input.d.ts +7 -0
  12. package/src/duration-input.js +31 -0
  13. package/src/errors.d.ts +34 -3
  14. package/src/errors.js +49 -7
  15. package/src/expected-values.d.ts +48 -0
  16. package/src/expected-values.js +60 -0
  17. package/src/failure-log.d.ts +6 -0
  18. package/src/failure-log.js +167 -0
  19. package/src/follow.d.ts +9 -0
  20. package/src/follow.js +58 -0
  21. package/src/input.d.ts +10 -7
  22. package/src/input.js +57 -13
  23. package/src/lib.d.ts +12 -7
  24. package/src/lib.js +70 -41
  25. package/src/list-continuation.js +1 -4
  26. package/src/list-limit.d.ts +2 -2
  27. package/src/list-limit.js +2 -2
  28. package/src/overview.d.ts +10 -0
  29. package/src/overview.js +41 -0
  30. package/src/presentation/activity-presentation.d.ts +4 -0
  31. package/src/presentation/activity-presentation.js +154 -38
  32. package/src/presentation/column-presentation.d.ts +22 -2
  33. package/src/presentation/column-presentation.js +68 -12
  34. package/src/presentation/doctor-presentation.d.ts +4 -0
  35. package/src/presentation/doctor-presentation.js +24 -0
  36. package/src/presentation/info-presentation.js +36 -6
  37. package/src/presentation/relation-presentation.d.ts +6 -2
  38. package/src/presentation/relation-presentation.js +37 -26
  39. package/src/presentation/task-blame-presentation.d.ts +8 -0
  40. package/src/presentation/task-blame-presentation.js +56 -0
  41. package/src/presentation/task-presentation.d.ts +8 -1
  42. package/src/presentation/task-presentation.js +59 -10
  43. package/src/result-schemas.d.ts +780 -20
  44. package/src/result-schemas.js +99 -2
  45. package/src/results.d.ts +6 -2
  46. package/src/results.js +9 -3
  47. package/src/routes/activity-router.d.ts +21 -4
  48. package/src/routes/activity-router.js +107 -60
  49. package/src/routes/aliases.js +1 -0
  50. package/src/routes/comment-router.d.ts +24 -6
  51. package/src/routes/comment-router.js +15 -5
  52. package/src/routes/doctor-router.d.ts +39 -0
  53. package/src/routes/doctor-router.js +103 -0
  54. package/src/routes/info-router.js +3 -2
  55. package/src/routes/label-router.d.ts +39 -6
  56. package/src/routes/label-router.js +22 -5
  57. package/src/routes/migrate-router.js +2 -2
  58. package/src/routes/project-router.d.ts +61 -12
  59. package/src/routes/project-router.js +103 -45
  60. package/src/routes/restore-router.js +11 -5
  61. package/src/routes/router.js +25 -16
  62. package/src/routes/routes.d.ts +455 -41
  63. package/src/routes/routes.js +4 -0
  64. package/src/routes/skill-router.d.ts +25 -0
  65. package/src/routes/skill-router.js +96 -0
  66. package/src/routes/task-router.d.ts +272 -19
  67. package/src/routes/task-router.js +325 -40
  68. package/src/routes/whoami-router.js +1 -1
  69. package/src/run-facts.d.ts +14 -0
  70. package/src/run-facts.js +14 -0
  71. package/src/store-folder.d.ts +5 -0
  72. package/src/store-folder.js +16 -0
  73. package/src/telemetry.d.ts +31 -0
  74. package/src/telemetry.js +329 -0
  75. package/src/text-edit.d.ts +2 -2
  76. package/src/text-input.d.ts +19 -1
  77. package/src/text-input.js +27 -10
  78. package/src/types.d.ts +1 -1
@@ -0,0 +1,167 @@
1
+ import { closeSync, openSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { arch, platform, release } from "node:os";
3
+ import { join } from "node:path";
4
+ import { createOutputFileName, getConfiguredStorage, getStorage, readOutputFileName, readSchemaVersionWithoutWaiting, } from "@zinn-dev/core";
5
+ import packageJson from "../package.json" with { type: "json" };
6
+ import { currentRuntime, readRunClock } from "./run-facts.js";
7
+ import { ensureFolderInStore } from "./store-folder.js";
8
+ const LOG_EXTENSION = ".log";
9
+ /** Logs kept in the folder. Including ones written by a failing run */
10
+ const MAX_LOG_FILES = 10;
11
+ /** One thrown value as text. An error keeps its stack, and its code and `errcode` when it has them */
12
+ function describeValue(value) {
13
+ if (!(value instanceof Error)) {
14
+ return String(value);
15
+ }
16
+ const lines = [typeof value.stack === "string" ? value.stack : `${value.name}: ${value.message}`];
17
+ const { code, errcode } = value;
18
+ if (code !== undefined) {
19
+ lines.push(`code: ${String(code)}`);
20
+ }
21
+ if (errcode !== undefined) {
22
+ lines.push(`errcode: ${String(errcode)}`);
23
+ }
24
+ return lines.join("\n");
25
+ }
26
+ /** The thrown error, then each cause and suppressed error, stopping at one already shown */
27
+ function describeErrors(error) {
28
+ const shown = new Set();
29
+ const entries = [];
30
+ const add = (value, label) => {
31
+ if (shown.has(value)) {
32
+ return;
33
+ }
34
+ shown.add(value);
35
+ entries.push(label === null ? describeValue(value) : `${label}\n${describeValue(value)}`);
36
+ if (!(value instanceof Error)) {
37
+ return;
38
+ }
39
+ const { suppressed } = value;
40
+ if (value.cause !== undefined) {
41
+ add(value.cause, "Caused by:");
42
+ }
43
+ if (suppressed !== undefined) {
44
+ add(suppressed, "Suppressed:");
45
+ }
46
+ };
47
+ add(error, null);
48
+ return entries.join("\n\n");
49
+ }
50
+ function describeRuntime() {
51
+ const { name, version } = currentRuntime();
52
+ return `${name} ${version}`;
53
+ }
54
+ function section(title, lines) {
55
+ return [title, ...lines].join("\n");
56
+ }
57
+ /** The resolved database path and its schema version, or the configured path when it cannot be resolved. */
58
+ function readDatabaseFacts(configuredPath) {
59
+ try {
60
+ const { databasePath } = getStorage();
61
+ return { databasePath, schemaVersion: readSchemaVersionWithoutWaiting(databasePath) };
62
+ }
63
+ catch {
64
+ return { databasePath: configuredPath, schemaVersion: null };
65
+ }
66
+ }
67
+ function formatLog(error, notices, storage) {
68
+ const { databasePath, schemaVersion } = readDatabaseFacts(storage.databasePath);
69
+ const { now: failedAt, elapsedMs, startedAt } = readRunClock();
70
+ const sections = [
71
+ section("Error", [describeErrors(error)]),
72
+ section("Run", [
73
+ `Process id: ${process.pid}`,
74
+ `Zinn version: ${packageJson.version}`,
75
+ `Runtime: ${describeRuntime()}`,
76
+ `Operating system: ${platform()} ${release()} ${arch()}`,
77
+ ]),
78
+ section("Store", [
79
+ `Directory: ${storage.directory}`,
80
+ `Database: ${databasePath}`,
81
+ `Schema version: ${schemaVersion ?? "unknown"}`,
82
+ ]),
83
+ section("Arguments", [JSON.stringify(process.argv.slice(2))]),
84
+ section("Timings", [
85
+ `Started: ${startedAt.toISOString()}`,
86
+ `Failed: ${failedAt.toISOString()}`,
87
+ `Elapsed: ${elapsedMs} ms`,
88
+ ]),
89
+ ];
90
+ if (notices.length > 0) {
91
+ sections.push(section("Notices", [...notices]));
92
+ }
93
+ return `${sections.join("\n\n")}\n`;
94
+ }
95
+ /** Creates a file that does not exist yet, and removes it again when its text cannot be written */
96
+ function createFile(path, text) {
97
+ const descriptor = openSync(path, "wx");
98
+ let isWritten = false;
99
+ try {
100
+ try {
101
+ writeFileSync(descriptor, text);
102
+ }
103
+ finally {
104
+ closeSync(descriptor);
105
+ }
106
+ isWritten = true;
107
+ }
108
+ finally {
109
+ if (!isWritten) {
110
+ rmSync(path, { force: true });
111
+ }
112
+ }
113
+ }
114
+ /** Other runs' logs, oldest first by modification time, then by name */
115
+ function listOtherLogs(logDirectory, ownName) {
116
+ return readdirSync(logDirectory)
117
+ .filter((name) => name !== ownName && readOutputFileName(name, LOG_EXTENSION) !== null)
118
+ .flatMap((name) => {
119
+ try {
120
+ return [{ name, modifiedMs: statSync(join(logDirectory, name)).mtimeMs }];
121
+ }
122
+ catch {
123
+ // Another run may have removed it since the listing
124
+ return [];
125
+ }
126
+ })
127
+ .sort((a, b) => a.modifiedMs - b.modifiedMs || a.name.localeCompare(b.name))
128
+ .map(({ name }) => name);
129
+ }
130
+ /** Removes the oldest logs so that at most `MAX_LOG_FILES` remain. Other files stay */
131
+ function removeOldLogs(logDirectory, ownName) {
132
+ try {
133
+ const others = listOtherLogs(logDirectory, ownName);
134
+ const excess = others.length - (MAX_LOG_FILES - 1);
135
+ for (const name of others.slice(0, Math.max(excess, 0))) {
136
+ try {
137
+ rmSync(join(logDirectory, name), { force: true });
138
+ }
139
+ catch {
140
+ // Another run may have removed it, and a leftover only keeps one more file
141
+ }
142
+ }
143
+ }
144
+ catch {
145
+ // The new log is already written, so a failed listing only skips the cleanup
146
+ }
147
+ }
148
+ /**
149
+ * Writes what a failure leaves out of its error message to a new file in the store's `logs` folder.
150
+ * Returns the file's path, or undefined when none was written. It never throws,
151
+ * so logging cannot hide the failure it reports.
152
+ */
153
+ export function writeFailureLog(error, notices) {
154
+ try {
155
+ const storage = getConfiguredStorage();
156
+ const name = createOutputFileName({ client: "cli", version: packageJson.version }, LOG_EXTENSION);
157
+ const path = join(storage.logDirectory, name);
158
+ const text = formatLog(error, notices, storage);
159
+ ensureFolderInStore(storage.logDirectory);
160
+ createFile(path, text);
161
+ removeOldLogs(storage.logDirectory, name);
162
+ return path;
163
+ }
164
+ catch {
165
+ return undefined;
166
+ }
167
+ }
@@ -0,0 +1,9 @@
1
+ /** How often a following command looks for new commits. GNU `tail -f` sleeps one second between checks by default. */
2
+ export declare const FOLLOW_POLL_INTERVAL_MS = 1000;
3
+ /**
4
+ * Calls poll every interval until the command is stopped.
5
+ * Resolves when the reader of stdout has closed it, which a write reports.
6
+ * Rejects with what poll throws, which is how poll ends the command.
7
+ * An interrupt ends the process by its signal, as it ends a command that handles no signal.
8
+ */
9
+ export declare function followUntilStopped(poll: (signal: AbortSignal) => void | Promise<void>): Promise<void>;
package/src/follow.js ADDED
@@ -0,0 +1,58 @@
1
+ import { finishRun } from "./lib.js";
2
+ /** How often a following command looks for new commits. GNU `tail -f` sleeps one second between checks by default. */
3
+ export const FOLLOW_POLL_INTERVAL_MS = 1_000;
4
+ const INTERRUPT_SIGNAL = "SIGINT";
5
+ const CLOSED_PIPE_CODE = "EPIPE";
6
+ /**
7
+ * Calls poll every interval until the command is stopped.
8
+ * Resolves when the reader of stdout has closed it, which a write reports.
9
+ * Rejects with what poll throws, which is how poll ends the command.
10
+ * An interrupt ends the process by its signal, as it ends a command that handles no signal.
11
+ */
12
+ export function followUntilStopped(poll) {
13
+ return new Promise((resolve, reject) => {
14
+ const stopped = new AbortController();
15
+ let timer;
16
+ function stopPolling() {
17
+ clearTimeout(timer);
18
+ stopped.abort();
19
+ process.off(INTERRUPT_SIGNAL, interrupt);
20
+ }
21
+ async function pollOnce() {
22
+ try {
23
+ await poll(stopped.signal);
24
+ }
25
+ catch (error) {
26
+ if (!stopped.signal.aborted) {
27
+ stopPolling();
28
+ reject(error);
29
+ }
30
+ return;
31
+ }
32
+ if (!stopped.signal.aborted) {
33
+ timer = setTimeout(pollOnce, FOLLOW_POLL_INTERVAL_MS);
34
+ }
35
+ }
36
+ function interrupt() {
37
+ stopPolling();
38
+ finishRun();
39
+ // The listener is gone, so the signal now ends the process and the shell sees an interrupt.
40
+ process.kill(process.pid, INTERRUPT_SIGNAL);
41
+ }
42
+ process.once(INTERRUPT_SIGNAL, interrupt);
43
+ // Stays attached, so a write already on its way to the closed pipe cannot crash the process.
44
+ process.stdout.on("error", (error) => {
45
+ if (stopped.signal.aborted) {
46
+ return;
47
+ }
48
+ stopPolling();
49
+ if (error.code === CLOSED_PIPE_CODE) {
50
+ resolve();
51
+ }
52
+ else {
53
+ reject(error);
54
+ }
55
+ });
56
+ timer = setTimeout(pollOnce, FOLLOW_POLL_INTERVAL_MS);
57
+ });
58
+ }
package/src/input.d.ts CHANGED
@@ -173,26 +173,29 @@ export declare const archiveConstraint: {
173
173
  };
174
174
  export declare const routerOptionNames: {
175
175
  readonly json: "json";
176
- readonly legacyRead: "allow-legacy-read";
177
176
  };
178
177
  export declare const routerOptions: {
179
178
  readonly json: {
180
179
  readonly type: "boolean";
181
180
  };
182
- readonly "allow-legacy-read": {
183
- readonly type: "boolean";
184
- };
185
181
  };
186
182
  export declare const helpSpellings: readonly string[];
187
183
  export declare const versionSpellings: readonly string[];
184
+ export declare const OPTION_SEPARATOR = "--";
185
+ export declare function isJsonFlag(flag: string): boolean;
186
+ /** A flag the router reads wherever it appears before --, for every command. */
187
+ export declare function isRouterFlag(flag: string): boolean;
188
+ export declare function isHelpFlag(flag: string): boolean;
189
+ /** The words before the first `--`, and the rest starting with that `--` */
190
+ export declare function splitAtOptionSeparator(words: Array<string>): {
191
+ optionWords: string[];
192
+ passthroughWords: string[];
193
+ };
188
194
  export declare const invocation: {
189
195
  readonly routerOptions: {
190
196
  readonly json: {
191
197
  readonly type: "boolean";
192
198
  };
193
- readonly "allow-legacy-read": {
194
- readonly type: "boolean";
195
- };
196
199
  };
197
200
  readonly routerOptionPlacement: "exact-tokens-anywhere-before-separator";
198
201
  readonly optionSeparator: "--";
package/src/input.js CHANGED
@@ -63,17 +63,37 @@ export const archiveConstraint = {
63
63
  kind: "exclusive",
64
64
  members: ["option:archived", "option:all"],
65
65
  };
66
- export const routerOptionNames = { json: "json", legacyRead: "allow-legacy-read" };
66
+ export const routerOptionNames = { json: "json" };
67
67
  export const routerOptions = {
68
68
  [routerOptionNames.json]: { type: "boolean" },
69
- [routerOptionNames.legacyRead]: { type: "boolean" },
70
69
  };
71
70
  export const helpSpellings = ["-h", "--help"];
72
71
  export const versionSpellings = ["-v", "--version"];
72
+ export const OPTION_SEPARATOR = "--";
73
+ export function isJsonFlag(flag) {
74
+ return flag === `--${routerOptionNames.json}`;
75
+ }
76
+ /** A flag the router reads wherever it appears before --, for every command. */
77
+ export function isRouterFlag(flag) {
78
+ return isJsonFlag(flag);
79
+ }
80
+ export function isHelpFlag(flag) {
81
+ return helpSpellings.includes(flag);
82
+ }
83
+ /** The words before the first `--`, and the rest starting with that `--` */
84
+ export function splitAtOptionSeparator(words) {
85
+ const separatorIndex = words.indexOf(OPTION_SEPARATOR);
86
+ return separatorIndex === -1
87
+ ? { optionWords: words, passthroughWords: [] }
88
+ : {
89
+ optionWords: words.slice(0, separatorIndex),
90
+ passthroughWords: words.slice(separatorIndex),
91
+ };
92
+ }
73
93
  export const invocation = {
74
94
  routerOptions,
75
95
  routerOptionPlacement: "exact-tokens-anywhere-before-separator",
76
- optionSeparator: "--",
96
+ optionSeparator: OPTION_SEPARATOR,
77
97
  literalOptionValue: "equals",
78
98
  singularOptions: "reject-repetition",
79
99
  jsonFailure: "one-stderr-document-with-buffered-diagnostics",
@@ -141,7 +161,7 @@ export function generateInputUsage(input) {
141
161
  constraint.members.length === members.length &&
142
162
  constraint.members.every((member) => members.includes(member)));
143
163
  const choice = (alternatives, isRequired) => isRequired ? `(${alternatives.join("|")})` : `[${alternatives.join("|")}]`;
144
- return input.forms.map((form) => {
164
+ return input.forms.flatMap((form) => {
145
165
  const words = new Map([
146
166
  ...form.positionals.map((positional, index) => [`positional:${positional.name}`, positionalWords(form)[index]]),
147
167
  ...options.map(({ reference, word }) => [reference, word]),
@@ -170,18 +190,42 @@ export function generateInputUsage(input) {
170
190
  words.delete(reference);
171
191
  }
172
192
  }
173
- for (const constraint of input.constraints) {
174
- const hasEveryMemberWord = constraint.kind === "exclusive" && constraint.members.every((member) => words.has(member));
175
- if (!hasEveryMemberWord) {
176
- continue;
193
+ const exclusiveGroups = input.constraints
194
+ .filter((constraint) => constraint.kind === "exclusive")
195
+ .map((constraint) => constraint.members)
196
+ .filter((members) => members.every((member) => words.has(member)));
197
+ function renderChoices(remaining) {
198
+ const groups = exclusiveGroups
199
+ .map((members) => members.filter((member) => remaining.has(member)))
200
+ .filter((members) => members.length > 1);
201
+ const overlappingMember = groups
202
+ .flat()
203
+ .find((member) => groups.filter((members) => members.includes(member)).length > 1);
204
+ // Separate usage lines preserve combinations allowed by overlapping exclusions.
205
+ if (overlappingMember !== undefined) {
206
+ const withoutMember = new Map(remaining);
207
+ withoutMember.delete(overlappingMember);
208
+ const withMember = new Map(remaining);
209
+ withMember.set(overlappingMember, remaining.get(overlappingMember).slice(1, -1));
210
+ for (const members of groups.filter((members) => members.includes(overlappingMember))) {
211
+ for (const member of members) {
212
+ if (member !== overlappingMember) {
213
+ withMember.delete(member);
214
+ }
215
+ }
216
+ }
217
+ return [...renderChoices(withoutMember), ...renderChoices(withMember)];
177
218
  }
178
- const alternatives = constraint.members.map((member) => words.get(member).slice(1, -1));
179
- words.set(constraint.members[0], choice(alternatives, isRequiredChoice(constraint.members)));
180
- for (const member of constraint.members.slice(1)) {
181
- words.delete(member);
219
+ for (const members of groups) {
220
+ const alternatives = members.map((member) => remaining.get(member).slice(1, -1));
221
+ remaining.set(members[0], choice(alternatives, isRequiredChoice(members)));
222
+ for (const member of members.slice(1)) {
223
+ remaining.delete(member);
224
+ }
182
225
  }
226
+ return [[...remaining.values()].join(" ")];
183
227
  }
184
- return [...words.values()].join(" ");
228
+ return renderChoices(words);
185
229
  });
186
230
  }
187
231
  export const usageLabel = "Usage: ";
package/src/lib.d.ts CHANGED
@@ -17,13 +17,18 @@ export declare function prepareOutput(args: Array<string>): void;
17
17
  /** Keeps JSON failures parseable while text-mode notices remain immediate. */
18
18
  export declare function diagnostic(message: string): void;
19
19
  export declare function flushDiagnostics(): void;
20
- export declare function isJsonFlag(flag: string): boolean;
21
- export declare function isAllowLegacyReadFlag(flag: string): boolean;
22
- /** A flag the router reads wherever it appears before --, for every command. */
23
- export declare function isRouterFlag(flag: string): boolean;
24
- export declare function setLegacyReadAllowed(allowed: boolean): void;
25
- export declare function isLegacyReadAllowed(): boolean;
20
+ export declare function isDebugOutputEnabled(): boolean;
21
+ /**
22
+ * Ends a successful run after its output, recording telemetry then releasing notices held back in JSON mode.
23
+ * Telemetry goes first so its own debug notice is released with the rest.
24
+ */
25
+ export declare function finishRun(): void;
26
26
  export declare function output<T>(data: T, transformToString: (data: T) => string): void;
27
+ /**
28
+ * Prints items as they arrive for a command that keeps running. JSON mode prints one document per line.
29
+ * It writes to the stream itself, whose error event reports a closed pipe under Node and Bun alike.
30
+ */
31
+ export declare function outputStream<T>(items: Array<T>, transformToString: (items: Array<T>) => string, signal: AbortSignal): Promise<void>;
27
32
  /** Includes change data in JSON and adds a stderr note for each unchanged object */
28
33
  export declare function outputChanges<Change extends {
29
34
  changed: boolean;
@@ -75,7 +80,6 @@ export declare function validateOrderForms<Form extends InputForm>(positionals:
75
80
  export declare function requireStringOption(option: InputOption & {
76
81
  required: true;
77
82
  }, value: string | undefined, name: string, message: string): string;
78
- export declare function isHelpFlag(flag: string): boolean;
79
83
  /**
80
84
  * Help sentence for a flag whose value may begin with a dash, such as a Markdown bullet.
81
85
  * `parseArgs` refuses `--flag -value`, since a value that looks like an option may mean the value
@@ -94,6 +98,7 @@ type SuggestFor = (flag: string) => {
94
98
  } | undefined;
95
99
  /** Renames an option without changing values or words after `--` */
96
100
  export declare function renameFlag(args: Array<string>, options: ParseArgsOptionsConfig, source: string, target: string): string[];
101
+ export declare function isParseArgsError(error: any): boolean;
97
102
  /**
98
103
  * An argument failure from parseArgs, rewritten where parseArgs' own advice misleads.
99
104
  * parseArgs names the flag only in its message text, which Node and Bun word the same.
package/src/lib.js CHANGED
@@ -1,14 +1,20 @@
1
+ import { basename } from "node:path";
2
+ import { once } from "node:events";
1
3
  import { parseArgs } from "node:util";
2
4
  import { createInterface } from "node:readline/promises";
3
5
  import { z } from "zod";
4
6
  import { assertWritable, InputValidationError } from "@zinn-dev/core";
5
7
  import { CliError, classifyFailure, recoveryHint } from "./errors.js";
6
- import { helpSpellings, routerOptionNames, positionalWords } from "./input.js";
8
+ import { writeFailureLog } from "./failure-log.js";
9
+ import { isJsonFlag, isRouterFlag, OPTION_SEPARATOR, positionalWords, splitAtOptionSeparator, } from "./input.js";
7
10
  import { formatParserReasonPreview } from "./presentation/description-presentation.js";
11
+ import { writeRunRecord } from "./telemetry.js";
8
12
  let outputMode = "text";
9
- let legacyReadAllowed = false;
10
13
  const diagnostics = [];
11
- const DOUBLE_DASH = "--";
14
+ /** Every notice of this run in order, kept for the failure log */
15
+ const runNotices = [];
16
+ /** Failures that write a log, because the error alone does not say what went wrong */
17
+ const LOGGED_ERROR_CODES = ["storage", "internal"];
12
18
  const MAX_PARSER_MESSAGE_LENGTH = 1024;
13
19
  /** Keeps recovery guidance outside the shortened reason and never clips a repair command. */
14
20
  export function boundParserMessage(message, options = {}) {
@@ -27,12 +33,12 @@ export function getOutputMode() {
27
33
  }
28
34
  /** Selects output before routing, without treating words after `--` as flags. */
29
35
  export function prepareOutput(args) {
30
- const separatorIndex = args.indexOf(DOUBLE_DASH);
31
- const options = separatorIndex === -1 ? args : args.slice(0, separatorIndex);
32
- setOutputMode(options.some(isJsonFlag) ? "json" : "text");
36
+ const { optionWords } = splitAtOptionSeparator(args);
37
+ setOutputMode(optionWords.some(isJsonFlag) ? "json" : "text");
33
38
  }
34
39
  /** Keeps JSON failures parseable while text-mode notices remain immediate. */
35
40
  export function diagnostic(message) {
41
+ runNotices.push(message);
36
42
  if (outputMode === "json") {
37
43
  diagnostics.push(message);
38
44
  }
@@ -45,21 +51,23 @@ export function flushDiagnostics() {
45
51
  console.error(message);
46
52
  }
47
53
  }
48
- export function isJsonFlag(flag) {
49
- return flag === `--${routerOptionNames.json}`;
54
+ // ZINN_DEBUG=1 prints routing detail on stderr, so stdout and `--json` results stay unchanged.
55
+ export function isDebugOutputEnabled() {
56
+ return process.env.ZINN_DEBUG === "1";
50
57
  }
51
- export function isAllowLegacyReadFlag(flag) {
52
- return flag === `--${routerOptionNames.legacyRead}`;
53
- }
54
- /** A flag the router reads wherever it appears before --, for every command. */
55
- export function isRouterFlag(flag) {
56
- return isJsonFlag(flag) || isAllowLegacyReadFlag(flag);
57
- }
58
- export function setLegacyReadAllowed(allowed) {
59
- legacyReadAllowed = allowed;
58
+ function recordRun(outcome) {
59
+ const problem = writeRunRecord(outcome);
60
+ if (problem !== undefined && isDebugOutputEnabled()) {
61
+ diagnostic(`::telemetry ${problem}`);
62
+ }
60
63
  }
61
- export function isLegacyReadAllowed() {
62
- return legacyReadAllowed;
64
+ /**
65
+ * Ends a successful run after its output, recording telemetry then releasing notices held back in JSON mode.
66
+ * Telemetry goes first so its own debug notice is released with the rest.
67
+ */
68
+ export function finishRun() {
69
+ recordRun({});
70
+ flushDiagnostics();
63
71
  }
64
72
  export function output(data, transformToString) {
65
73
  if (outputMode === "json") {
@@ -71,6 +79,21 @@ export function output(data, transformToString) {
71
79
  console.info(dataText);
72
80
  }
73
81
  }
82
+ /**
83
+ * Prints items as they arrive for a command that keeps running. JSON mode prints one document per line.
84
+ * It writes to the stream itself, whose error event reports a closed pipe under Node and Bun alike.
85
+ */
86
+ export async function outputStream(items, transformToString, signal) {
87
+ if (items.length === 0) {
88
+ return;
89
+ }
90
+ const text = outputMode === "json"
91
+ ? items.map((item) => JSON.stringify(item)).join("\n")
92
+ : transformToString(items);
93
+ if (!process.stdout.write(`${text}\n`)) {
94
+ await once(process.stdout, "drain", { signal });
95
+ }
96
+ }
74
97
  /** Includes change data in JSON and adds a stderr note for each unchanged object */
75
98
  export function outputChanges(changes, present, formatEntries, describeUnchanged) {
76
99
  const presentedChanges = changes.map((change) => ({
@@ -161,14 +184,22 @@ export function renderFailure(reason) {
161
184
  help: classified.help,
162
185
  message: failureMessage(reason, "Something went wrong"),
163
186
  };
187
+ const logPath = LOGGED_ERROR_CODES.includes(failure.code)
188
+ ? writeFailureLog(reason, runNotices)
189
+ : undefined;
190
+ recordRun({
191
+ failure: classified,
192
+ ...(logPath === undefined ? {} : { logFileName: basename(logPath) }),
193
+ });
164
194
  const pendingDiagnostics = diagnostics.splice(0);
165
195
  if (outputMode === "json") {
166
- const details = failure.details === undefined
167
- ? undefined
168
- : Object.fromEntries(Object.entries(failure.details).filter(([, value]) => value !== undefined));
196
+ const details = {
197
+ ...Object.fromEntries(Object.entries(failure.details ?? {}).filter(([, value]) => value !== undefined)),
198
+ ...(logPath === undefined ? {} : { logPath }),
199
+ };
169
200
  const error = {
170
201
  ...failure,
171
- details: details !== undefined && Object.keys(details).length > 0 ? details : undefined,
202
+ details: Object.keys(details).length > 0 ? details : undefined,
172
203
  diagnostics: pendingDiagnostics.length > 0 ? pendingDiagnostics : undefined,
173
204
  };
174
205
  console.error(JSON.stringify({ error }, null, 2));
@@ -178,9 +209,13 @@ export function renderFailure(reason) {
178
209
  console.error(message);
179
210
  }
180
211
  console.error(failure.help == null ? failure.message : `${failure.message}\n\n${failure.help}`);
212
+ if (logPath !== undefined) {
213
+ console.error(`Full log: ${logPath}`);
214
+ }
181
215
  }
216
+ const exitCode = reason instanceof CliError && reason.exitCode !== undefined ? reason.exitCode : 1;
182
217
  // Let piped stderr finish writing before Node exits
183
- process.stderr.write("", () => process.exit(1));
218
+ process.stderr.write("", () => process.exit(exitCode));
184
219
  }
185
220
  /** A command was given the wrong words. The router prints the message with the command's usage lines. */
186
221
  export class UsageError extends CliError {
@@ -266,9 +301,6 @@ export function requireStringOption(option, value, name, message) {
266
301
  }
267
302
  return value;
268
303
  }
269
- export function isHelpFlag(flag) {
270
- return helpSpellings.includes(flag);
271
- }
272
304
  /**
273
305
  * Help sentence for a flag whose value may begin with a dash, such as a Markdown bullet.
274
306
  * `parseArgs` refuses `--flag -value`, since a value that looks like an option may mean the value
@@ -353,13 +385,8 @@ function unknownOptionMessage(message, args, suggestFor, route) {
353
385
  if (suggestion === undefined) {
354
386
  return { message: boundParserMessage(reason) };
355
387
  }
356
- const separatorIndex = suggestion.args.indexOf(DOUBLE_DASH);
357
- const optionEnd = separatorIndex === -1 ? suggestion.args.length : separatorIndex;
358
- const correctedArgs = [
359
- ...suggestion.args.slice(0, optionEnd),
360
- ...args.filter(isRouterFlag),
361
- ...suggestion.args.slice(optionEnd),
362
- ];
388
+ const { optionWords, passthroughWords } = splitAtOptionSeparator(suggestion.args);
389
+ const correctedArgs = [...optionWords, ...args.filter(isRouterFlag), ...passthroughWords];
363
390
  return {
364
391
  message: boundParserMessage(`${reason}. Did you mean: ${formatCommand(correctedArgs)}`, {
365
392
  reason,
@@ -369,9 +396,8 @@ function unknownOptionMessage(message, args, suggestFor, route) {
369
396
  };
370
397
  }
371
398
  // Commands define no short options, so `parseArgs` refused the first single-dash word before `--`.
372
- const separatorIndex = args.indexOf(DOUBLE_DASH);
373
- const optionArgs = separatorIndex === -1 ? args : args.slice(0, separatorIndex);
374
- const wordIndex = optionArgs.findIndex((arg) => SHORT_OPTION_WORD_PATTERN.test(arg));
399
+ const { optionWords } = splitAtOptionSeparator(args);
400
+ const wordIndex = optionWords.findIndex((arg) => SHORT_OPTION_WORD_PATTERN.test(arg));
375
401
  if (wordIndex === -1) {
376
402
  return { message: boundParserMessage(message) };
377
403
  }
@@ -397,7 +423,7 @@ function unknownOptionMessage(message, args, suggestFor, route) {
397
423
  const fixedCommand = formatCommand([
398
424
  ...args.slice(0, wordIndex),
399
425
  ...routerFlagsAfter,
400
- DOUBLE_DASH,
426
+ OPTION_SEPARATOR,
401
427
  word,
402
428
  ...plainWordsAfter,
403
429
  ]);
@@ -406,17 +432,20 @@ function unknownOptionMessage(message, args, suggestFor, route) {
406
432
  suggestedRoute: route,
407
433
  };
408
434
  }
435
+ export function isParseArgsError(error) {
436
+ const code = error?.code;
437
+ return typeof code === "string" && code.startsWith("ERR_PARSE_ARGS_");
438
+ }
409
439
  /**
410
440
  * An argument failure from parseArgs, rewritten where parseArgs' own advice misleads.
411
441
  * parseArgs names the flag only in its message text, which Node and Bun word the same.
412
442
  * `null` for any other error.
413
443
  */
414
444
  export function parseArgsFailure(error, args, suggestFor, route) {
415
- const code = error?.code;
416
- const isParseArgsError = typeof code === "string" && code.startsWith("ERR_PARSE_ARGS_");
417
- if (!isParseArgsError) {
445
+ if (!isParseArgsError(error)) {
418
446
  return null;
419
447
  }
448
+ const code = error.code;
420
449
  const argument = /(?:Unknown option|Option) '(-[^' ]+)/.exec(error.message)?.[1];
421
450
  if (code === "ERR_PARSE_ARGS_UNKNOWN_OPTION") {
422
451
  const hint = unknownOptionMessage(error.message, args, suggestFor, route);
@@ -1,4 +1,4 @@
1
- import { formatCommand, getOutputMode, isLegacyReadAllowed } from "./lib.js";
1
+ import { formatCommand, getOutputMode } from "./lib.js";
2
2
  /** Rebuilds a list command with its existing filters and the next cursor. */
3
3
  export function formatListContinuation(command, positionals, tokens, cursorOption, cursorId) {
4
4
  const continuation = tokens.flatMap((token) => {
@@ -10,9 +10,6 @@ export function formatListContinuation(command, positionals, tokens, cursorOptio
10
10
  if (getOutputMode() === "json") {
11
11
  continuation.push("--json");
12
12
  }
13
- if (isLegacyReadAllowed()) {
14
- continuation.push("--allow-legacy-read");
15
- }
16
13
  continuation.push(`--${cursorOption}`, cursorId);
17
14
  return formatCommand([...command, ...positionals, ...continuation]);
18
15
  }
@@ -1,4 +1,4 @@
1
- export declare const listLimitDescription = "Return at most n results after all filters. Use an integer from 1 through 11871.";
1
+ export declare const listLimitDescription = "Return at most n results after all filters.";
2
2
  export declare const listLimitOption: {
3
3
  readonly type: "string";
4
4
  readonly value: {
@@ -6,6 +6,6 @@ export declare const listLimitOption: {
6
6
  readonly name: "n";
7
7
  readonly pattern: string;
8
8
  };
9
- readonly description: "Return at most n results after all filters. Use an integer from 1 through 11871.";
9
+ readonly description: "Return at most n results after all filters.";
10
10
  };
11
11
  export declare function parseListLimit(value: string | undefined): number | undefined;
package/src/list-limit.js CHANGED
@@ -1,6 +1,6 @@
1
- import { MAX_LIST_LIMIT, listLimitMessage, listLimitPattern } from "@zinn-dev/core";
1
+ import { listLimitMessage, listLimitPattern } from "@zinn-dev/core";
2
2
  import { quit } from "./lib.js";
3
- export const listLimitDescription = `Return at most n results after all filters. Use an integer from 1 through ${MAX_LIST_LIMIT}.`;
3
+ export const listLimitDescription = "Return at most n results after all filters.";
4
4
  export const listLimitOption = {
5
5
  type: "string",
6
6
  value: { kind: "positive-integer", name: "n", pattern: listLimitPattern },