@apet97/clockify-cli-115 5.0.4 → 6.0.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 (40) hide show
  1. package/README.md +96 -26
  2. package/dist/client.js +18 -15
  3. package/dist/closed-pipe.js +3 -0
  4. package/dist/commands/api.js +182 -61
  5. package/dist/commands/approvals.js +9 -7
  6. package/dist/commands/auditlog.js +11 -8
  7. package/dist/commands/balanceAssignment.js +10 -8
  8. package/dist/commands/clients.js +16 -7
  9. package/dist/commands/doctor.js +42 -25
  10. package/dist/commands/entries.js +29 -14
  11. package/dist/commands/expenses.js +64 -22
  12. package/dist/commands/helpers.js +28 -7
  13. package/dist/commands/invoices.js +12 -16
  14. package/dist/commands/leaf-command.js +8 -0
  15. package/dist/commands/log.js +4 -2
  16. package/dist/commands/projects.js +18 -9
  17. package/dist/commands/reports.js +32 -14
  18. package/dist/commands/resolve-refs.js +30 -53
  19. package/dist/commands/scheduling.js +94 -40
  20. package/dist/commands/shared-report-body.js +205 -0
  21. package/dist/commands/sharedReports.js +19 -215
  22. package/dist/commands/start.js +6 -4
  23. package/dist/commands/status.js +55 -19
  24. package/dist/commands/stop.js +15 -17
  25. package/dist/commands/tags.js +6 -4
  26. package/dist/commands/tasks.js +18 -23
  27. package/dist/commands/timeoff.js +23 -16
  28. package/dist/commands/users.js +7 -5
  29. package/dist/commands/webhooks.js +14 -12
  30. package/dist/completions.js +290 -55
  31. package/dist/config.js +10 -6
  32. package/dist/duration.js +5 -4
  33. package/dist/error-codes.js +34 -6
  34. package/dist/failure.js +87 -0
  35. package/dist/flags.js +74 -0
  36. package/dist/generated/version.js +1 -1
  37. package/dist/index.js +41 -105
  38. package/dist/output.js +62 -28
  39. package/dist/write-outcome.js +84 -0
  40. package/package.json +3 -3
package/dist/duration.js CHANGED
@@ -1,7 +1,8 @@
1
+ import { UsageError } from "./failure.js";
1
2
  export function parseDuration(input) {
2
3
  const trimmed = input.trim();
3
4
  if (trimmed === "") {
4
- throw new Error('duration is missing; provide a form like "1h30m", "45m", "90", or ISO "PT1H30M"');
5
+ throw new UsageError('duration is missing; provide a form like "1h30m", "45m", "90", or ISO "PT1H30M"');
5
6
  }
6
7
  if (/^PT/i.test(trimmed)) {
7
8
  return requirePositive(parseIsoDuration(trimmed), input);
@@ -16,7 +17,7 @@ export function parseDuration(input) {
16
17
  re.lastIndex = offset;
17
18
  const match = re.exec(trimmed);
18
19
  if (match === null) {
19
- throw new Error(`could not parse duration ${JSON.stringify(input)}; use forms like "1h30m", "45m", "90", or ISO "PT1H30M"`);
20
+ throw new UsageError(`could not parse duration ${JSON.stringify(input)}; use forms like "1h30m", "45m", "90", or ISO "PT1H30M"`);
20
21
  }
21
22
  const value = Number(match[1]);
22
23
  const unit = (match[2] ?? "").toLowerCase();
@@ -27,7 +28,7 @@ export function parseDuration(input) {
27
28
  }
28
29
  function requirePositive(seconds, input) {
29
30
  if (seconds <= 0) {
30
- throw new Error(`duration ${JSON.stringify(input)} must be positive; a zero-length entry records nothing`);
31
+ throw new UsageError(`duration ${JSON.stringify(input)} must be positive; a zero-length entry records nothing`);
31
32
  }
32
33
  return seconds;
33
34
  }
@@ -35,7 +36,7 @@ function parseIsoDuration(input) {
35
36
  const re = /^PT(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?$/i;
36
37
  const match = re.exec(input);
37
38
  if (!match || (match[1] == null && match[2] == null && match[3] == null)) {
38
- throw new Error(`could not parse ISO duration ${JSON.stringify(input)}; provide a form like "PT1H30M"`);
39
+ throw new UsageError(`could not parse ISO duration ${JSON.stringify(input)}; provide a form like "PT1H30M"`);
39
40
  }
40
41
  const hours = match[1] != null ? Number(match[1]) : 0;
41
42
  const minutes = match[2] != null ? Number(match[2]) : 0;
@@ -10,8 +10,8 @@ export const CLOCKIFY_ERROR_CODES = [
10
10
  "cli",
11
11
  "mcp"
12
12
  ],
13
- "meaning": "The request is malformed, missing required fields, or locally invalid before Clockify accepts it.",
14
- "recovery": "Fix the request fields, IDs, dates, pagination values, or enum values, then retry.",
13
+ "meaning": "The request is malformed, missing required fields, or locally invalid before Clockify accepts it, including \"Approval period has changed, please update your app version.\" when an approval request's period does not match the workspace approval period.",
14
+ "recovery": "Fix the request fields, IDs, dates, pagination values, or enum values, then retry. For \"Approval period has changed\", send the period matching the workspace's approvalSettings.approvalPeriod (expense approvals: expenseApprovalSettings.approvalPeriod); read it from the workspace settings first.",
15
15
  "reachable": true
16
16
  },
17
17
  {
@@ -41,8 +41,8 @@ export const CLOCKIFY_ERROR_CODES = [
41
41
  "cli",
42
42
  "mcp"
43
43
  ],
44
- "meaning": "The endpoint exists but the workspace plan or feature configuration does not expose it.",
45
- "recovery": "Use a supported workspace plan, skip the gated workflow, or fall back to a lower-level read operation.",
44
+ "meaning": "The endpoint exists but the workspace plan or feature configuration does not expose it: HTTP 402, or HTTP 401/403 whose body is exactly \"Wrong subscription plan\" (Clockify's plan gate on Enterprise-only endpoints), or HTTP 400 when a workspace setting the request needs is switched off (\"Action cannot be performed because Original time view is disabled on workspace.\" for timeViewMode=AGGREGATED_TIME_VIEW; \"...since break feature is not enabled.\" for a BREAK entry); HTTP 403 code 501 \"Action not allowed. Enable rates in your workspace settings.\" on a rate write; HTTP 400 code 501 \"Export type: ... is not supported on current plan.\"; or an HTTP 400 plan quota identified by body code alone (4000 seat limit, 4033 custom-field limit, 40999 organization workspace cap).",
45
+ "recovery": "Use a supported workspace plan, skip the gated workflow, or fall back to a lower-level read operation. For a disabled workspace setting, omit the option (timeViewMode, type BREAK) or have an admin enable Original time view or Breaks. For rates, have an admin enable rates in workspace settings. For an export type, use one the plan supports (or upgrade). For a seat, custom-field, or workspace quota (codes 4000, 4033, 40999), free capacity or upgrade the plan; retrying does not help.",
46
46
  "reachable": true
47
47
  },
48
48
  {
@@ -181,8 +181,34 @@ export const CLOCKIFY_ERROR_CODES = [
181
181
  "cli",
182
182
  "mcp"
183
183
  ],
184
- "meaning": "Clockify rejected a bare DELETE of an active project, task, or client before the object could be removed.",
185
- "recovery": "Archive the project/client first, or mark a task done first, then issue the delete.",
184
+ "meaning": "Clockify rejected a bare DELETE of an entity that is still active: a project, task, or client (\"Cannot delete an active …\"), a time-off policy (\"Policy must be archived in order to be deleted\"), or an expense category (\"Category must be archived to be deleted.\").",
185
+ "recovery": "Archive the project, client, time-off policy, or expense category first, or mark a task done first, then issue the delete.",
186
+ "reachable": true
187
+ },
188
+ {
189
+ "code": "manual_time_tracking_disabled",
190
+ "httpStatus": [],
191
+ "retry": false,
192
+ "surfaces": [
193
+ "sdk",
194
+ "cli",
195
+ "mcp"
196
+ ],
197
+ "meaning": "The workspace enforces Force timer (timeTrackingMode STOPWATCH_ONLY): Clockify answers HTTP 403 with body code 4030 (\"Manual time tracking disabled on … workspace\") to any write that sets `end`, edits `start`, or duplicates an entry, for every role.",
198
+ "recovery": "Start a running timer (omit `end`) and stop it when the work ends instead of logging a finished or duplicated entry; do not retry the same manual write. A workspace admin can turn off Force timer to allow manual entries.",
199
+ "reachable": true
200
+ },
201
+ {
202
+ "code": "entry_locked",
203
+ "httpStatus": [],
204
+ "retry": false,
205
+ "surfaces": [
206
+ "sdk",
207
+ "cli",
208
+ "mcp"
209
+ ],
210
+ "meaning": "The time entry or expense falls inside a locked period (lock time entries / automatic lock): Clockify answers HTTP 403 \"Can't edit locked time entry.\" (code 1003) or \"Can't edit locked expense.\" / \"Can't set expense to locked date.\" (code 1006) to non-admin writes.",
211
+ "recovery": "Write to a date outside the locked period, or ask a workspace owner or admin (who bypass the lock) to make the change or move the lock date; retrying the same write does not help.",
186
212
  "reachable": true
187
213
  },
188
214
  {
@@ -243,6 +269,8 @@ export function errorCodeForStatus(status) {
243
269
  export function errorCodeForMessage(message) {
244
270
  if (/does(?:n'?t| not) (?:belong to|exist)/i.test(message))
245
271
  return "not_found";
272
+ if (/(?:^|\n)\s*wrong subscription plan\s*(?:$|\n)/i.test(message))
273
+ return "feature_unavailable";
246
274
  if (/(unauthorized|forbidden|permission|api[\s_-]?key|addon[\s_-]?token|CLOCKIFY_API_KEY|CLOCKIFY_ADDON_TOKEN|workspace id not set)/i.test(message))
247
275
  return "auth_or_permission";
248
276
  if (/(upstream|gateway|bad gateway|service unavailable|internal server error)/i.test(message)) {
@@ -0,0 +1,87 @@
1
+ import { recoveryForCode } from "./error-codes.js";
2
+ import { AlreadyReportedError, printError, } from "./output.js";
3
+ import { failureStatus, writeFailure } from "./write-outcome.js";
4
+ export class LookupError extends Error {
5
+ lookupState;
6
+ constructor(lookupState, message) {
7
+ super(message);
8
+ this.lookupState = lookupState;
9
+ }
10
+ }
11
+ export class UsageError extends Error {
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = "UsageError";
15
+ }
16
+ }
17
+ export class PartialDeleteError extends Error {
18
+ completedStage;
19
+ next;
20
+ archiveAction;
21
+ constructor(cause, completedStage, next, archiveAction) {
22
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
23
+ this.completedStage = completedStage;
24
+ this.next = next;
25
+ this.archiveAction = archiveAction;
26
+ }
27
+ }
28
+ const COMMANDER_EXIT_ZERO_CODES = new Set([
29
+ "commander.helpDisplayed",
30
+ "commander.help",
31
+ "commander.version",
32
+ ]);
33
+ function isCommanderFailure(err) {
34
+ return (typeof err === "object" &&
35
+ err !== null &&
36
+ typeof err.code === "string" &&
37
+ err.code.startsWith("commander."));
38
+ }
39
+ function helpInvocation(command) {
40
+ const names = [];
41
+ for (let current = command; current?.parent != null; current = current.parent) {
42
+ names.unshift(current.name());
43
+ }
44
+ return ["clk115", ...names, "--help"].join(" ");
45
+ }
46
+ function redactInlineOptionValues(message) {
47
+ return message.replace(/'(--?[^\s'=]+)=[^']*'/g, "'$1=<redacted>'");
48
+ }
49
+ function usage(failedCommand) {
50
+ return {
51
+ code: "invalid_request",
52
+ recovery: `Run \`${helpInvocation(failedCommand)}\` for usage.`,
53
+ retryable: false,
54
+ };
55
+ }
56
+ export async function reportFailure(err, output, failedCommand) {
57
+ const write = await writeFailure(failedCommand, err instanceof PartialDeleteError ? err.cause : err);
58
+ if (isCommanderFailure(err)) {
59
+ if (COMMANDER_EXIT_ZERO_CODES.has(err.code))
60
+ return err.exitCode ?? 0;
61
+ const message = redactInlineOptionValues(err.message.replace(/^error: /, ""));
62
+ printError(message, output, undefined, usage(failedCommand), undefined, write);
63
+ return 2;
64
+ }
65
+ if (err instanceof AlreadyReportedError)
66
+ return 1;
67
+ if (err instanceof UsageError && (!write || write.stage === "before_dispatch")) {
68
+ printError(err.message, output, undefined, usage(failedCommand), undefined, write);
69
+ return 2;
70
+ }
71
+ const { classifyClockifyError, clockifyErrorDetail } = await import("clockify-sdk-ts-115/errors");
72
+ const partial = err instanceof PartialDeleteError ? err : undefined;
73
+ if (partial)
74
+ err = partial.cause;
75
+ const message = clockifyErrorDetail(err);
76
+ const classified = err instanceof LookupError
77
+ ? {
78
+ code: err.lookupState === "not_found" ? "not_found" : "invalid_request",
79
+ recovery: err.lookupState === "not_found" ? recoveryForCode("not_found") : "Provide the 24-character id instead.",
80
+ retryable: false,
81
+ }
82
+ : classifyClockifyError(err);
83
+ const statusCode = failureStatus(err);
84
+ const details = { ...write, ...(err instanceof LookupError && { lookupState: err.lookupState }) };
85
+ printError(message, output, statusCode, classified, partial, details);
86
+ return 1;
87
+ }
package/dist/flags.js ADDED
@@ -0,0 +1,74 @@
1
+ import { InvalidArgumentError } from "commander";
2
+ import { UsageError } from "./failure.js";
3
+ const OUTPUT_MODES = ["table", "json", "ndjson"];
4
+ export function colorEnabled(colorFlag, stream, env = process.env) {
5
+ if (colorFlag === false)
6
+ return false;
7
+ if (env.NO_COLOR !== undefined && env.NO_COLOR !== "")
8
+ return false;
9
+ const forced = env.FORCE_COLOR;
10
+ if (forced !== undefined && forced !== "")
11
+ return forced !== "0" && forced !== "false";
12
+ return stream.isTTY === true && env.TERM !== "dumb";
13
+ }
14
+ export function resolveFlags(program) {
15
+ const opts = program.opts();
16
+ const jsonShaping = opts.select !== undefined || opts.compact === true;
17
+ let mode = resolveMode(opts.output, opts.json);
18
+ if (jsonShaping && mode === "table") {
19
+ if (opts.output === "table") {
20
+ throw new UsageError("--select and --compact shape JSON output; use them with --output json or ndjson, not --output table.");
21
+ }
22
+ mode = "json";
23
+ }
24
+ const resolved = { mode, ...colorOptions(opts.color) };
25
+ if (opts.compact)
26
+ resolved.compact = true;
27
+ if (opts.select !== undefined)
28
+ resolved.select = opts.select;
29
+ return resolved;
30
+ }
31
+ export function resolveFlagsSafe(program) {
32
+ try {
33
+ return resolveFlags(program);
34
+ }
35
+ catch {
36
+ return { mode: "table", ...colorOptions(program.opts().color) };
37
+ }
38
+ }
39
+ function colorOptions(colorFlag) {
40
+ return {
41
+ color: colorEnabled(colorFlag, process.stdout),
42
+ errorColor: colorEnabled(colorFlag, process.stderr),
43
+ };
44
+ }
45
+ export function parseOutputMode(value) {
46
+ const match = OUTPUT_MODES.find((mode) => mode === value);
47
+ if (!match) {
48
+ throw new InvalidArgumentError(`Provide one of: ${OUTPUT_MODES.join(", ")}.`);
49
+ }
50
+ return match;
51
+ }
52
+ function resolveMode(output, json) {
53
+ if (output === undefined) {
54
+ return json ? "json" : "table";
55
+ }
56
+ const match = OUTPUT_MODES.find((mode) => mode === output);
57
+ if (!match) {
58
+ throw new Error(`Unsupported output mode "${output}". Provide one of: ${OUTPUT_MODES.join(", ")}.`);
59
+ }
60
+ return match;
61
+ }
62
+ export function globalFlags(program) {
63
+ const opts = program.opts();
64
+ const out = {};
65
+ if (opts.workspace)
66
+ out.workspace = opts.workspace;
67
+ if (opts.baseUrl)
68
+ out.baseUrl = opts.baseUrl;
69
+ if (opts.region)
70
+ out.region = opts.region;
71
+ if (opts.subdomain)
72
+ out.subdomain = opts.subdomain;
73
+ return out;
74
+ }
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = "5.0.4";
1
+ export const PACKAGE_VERSION = "6.0.0";
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { realpathSync } from "node:fs";
3
3
  import { pathToFileURL } from "node:url";
4
- import { clockifyErrorDetail } from "clockify-sdk-ts-115/errors";
5
- import { Command, InvalidArgumentError } from "commander";
4
+ import { Argument, Command } from "commander";
6
5
  import { buildClient } from "./client.js";
6
+ import { isClosedPipeError } from "./closed-pipe.js";
7
7
  import { registerApiCommand } from "./commands/api.js";
8
8
  import { registerApprovalsCommand } from "./commands/approvals.js";
9
9
  import { registerAuditLogCommand } from "./commands/auditlog.js";
@@ -26,10 +26,13 @@ import { registerTasksCommand } from "./commands/tasks.js";
26
26
  import { registerTimeOffCommand } from "./commands/timeoff.js";
27
27
  import { registerUsersCommand } from "./commands/users.js";
28
28
  import { registerWebhooksCommand } from "./commands/webhooks.js";
29
- import { parseCompletionShell, renderCompletion } from "./completions.js";
29
+ import { COMPLETION_SHELLS, parseCompletionShell, renderCompletion } from "./completions.js";
30
30
  import { loadConfig } from "./config.js";
31
+ import { reportFailure } from "./failure.js";
32
+ import { parseOutputMode, resolveFlags, resolveFlagsSafe } from "./flags.js";
31
33
  import { PACKAGE_VERSION } from "./generated/version.js";
32
- import { AlreadyReportedError, printError, } from "./output.js";
34
+ import { printJson } from "./output.js";
35
+ export { globalFlags, resolveFlags } from "./flags.js";
33
36
  const defaultServices = {
34
37
  loadConfig,
35
38
  buildClient,
@@ -46,10 +49,9 @@ export function buildProgram(services = defaultServices) {
46
49
  .option("--subdomain <label>", "Workspace subdomain for reports routing; requires --region eu/us/uk/au (or CLOCKIFY_SUBDOMAIN env var).")
47
50
  .option("--json", "Emit machine-readable JSON instead of human-friendly tables.", false)
48
51
  .option("--output <mode>", "Output mode: table, json, or ndjson.", parseOutputMode)
49
- .option("--compact", "Print compact JSON without indentation.", false)
50
- .option("--select <path>", "Select a dot-path before printing JSON or NDJSON.")
51
- .option("--no-color", "Disable ANSI color output.")
52
- .showHelpAfterError(true);
52
+ .option("--compact", "Print compact JSON without indentation (implies --output json).", false)
53
+ .option("--select <path>", "Select a dot-path before printing JSON or NDJSON (implies --output json).")
54
+ .option("--no-color", "Disable ANSI color output (NO_COLOR and FORCE_COLOR are also honored).");
53
55
  registerApiCommand(program, services);
54
56
  registerStatusCommand(program, services);
55
57
  registerDoctorCommand(program, services);
@@ -72,118 +74,49 @@ export function buildProgram(services = defaultServices) {
72
74
  registerUsersCommand(program, services);
73
75
  registerApprovalsCommand(program, services);
74
76
  leafCommand(program, "completion", "read")
75
- .argument("[shell]", "Shell to generate completion for: zsh, bash, or fish.", "zsh")
77
+ .addArgument(new Argument("[shell]", "Shell to generate completion for: zsh, bash, or fish.")
78
+ .choices(COMPLETION_SHELLS)
79
+ .argParser(parseCompletionShell)
80
+ .default("zsh"))
76
81
  .description("Print shell completion script for zsh, bash, or fish.")
77
82
  .addHelpText("after", "\nExamples:\n" +
78
83
  " $ clk115 completion zsh >> ~/.zshrc\n" +
79
84
  " $ clk115 completion bash\n")
80
85
  .action((shell) => {
81
- console.log(renderCompletion(parseCompletionShell(shell)));
86
+ const output = resolveFlags(program);
87
+ const script = renderCompletion(parseCompletionShell(shell), program);
88
+ if (output.mode === "table")
89
+ console.log(script);
90
+ else
91
+ printJson(script, output);
82
92
  });
83
93
  return program;
84
94
  }
85
- function isTty(stream) {
86
- return stream.isTTY === true;
87
- }
88
- export function resolveFlags(program) {
89
- const opts = program.opts();
90
- const mode = resolveMode(opts.output, opts.json);
91
- const resolved = {
92
- mode,
93
- color: opts.color !== false && isTty(process.stdout),
94
- };
95
- if (opts.compact)
96
- resolved.compact = true;
97
- if (opts.select !== undefined)
98
- resolved.select = opts.select;
99
- return resolved;
100
- }
101
- function resolveFlagsSafe(program) {
102
- try {
103
- return resolveFlags(program);
104
- }
105
- catch {
106
- const opts = program.opts();
107
- return {
108
- mode: "table",
109
- color: opts.color !== false && isTty(process.stdout),
110
- };
111
- }
112
- }
113
- function parseOutputMode(value) {
114
- const modes = ["table", "json", "ndjson"];
115
- const match = modes.find((mode) => mode === value);
116
- if (!match) {
117
- throw new InvalidArgumentError("Provide one of: table, json, ndjson.");
118
- }
119
- return match;
120
- }
121
- function resolveMode(output, json) {
122
- if (output === undefined) {
123
- return json ? "json" : "table";
124
- }
125
- const modes = ["table", "json", "ndjson"];
126
- const match = modes.find((mode) => mode === output);
127
- if (!match) {
128
- throw new Error(`Unsupported output mode "${output}". Provide one of: table, json, ndjson.`);
129
- }
130
- return match;
131
- }
132
- export function globalFlags(program) {
133
- const opts = program.opts();
134
- const out = {};
135
- if (opts.workspace)
136
- out.workspace = opts.workspace;
137
- if (opts.baseUrl)
138
- out.baseUrl = opts.baseUrl;
139
- if (opts.region)
140
- out.region = opts.region;
141
- if (opts.subdomain)
142
- out.subdomain = opts.subdomain;
143
- return out;
144
- }
145
95
  export async function main(argv, services = defaultServices) {
146
96
  const program = buildProgram(services);
147
- const applyExitOverride = (cmd) => {
97
+ let active;
98
+ const prepare = (cmd) => {
148
99
  cmd.exitOverride();
100
+ cmd.configureOutput({
101
+ outputError: () => {
102
+ active = cmd;
103
+ },
104
+ });
149
105
  for (const sub of cmd.commands)
150
- applyExitOverride(sub);
106
+ prepare(sub);
151
107
  };
152
- applyExitOverride(program);
108
+ prepare(program);
109
+ program.hook("preAction", (_root, actionCommand) => {
110
+ active = actionCommand;
111
+ });
153
112
  try {
154
113
  await program.parseAsync(argv);
155
114
  return 0;
156
115
  }
157
116
  catch (err) {
158
- if (isCommanderHelpError(err)) {
159
- return err.exitCode ?? 0;
160
- }
161
- if (err instanceof AlreadyReportedError) {
162
- return 1;
163
- }
164
- const message = clockifyErrorDetail(err);
165
- const statusCode = err.statusCode;
166
- const flags = resolveFlagsSafe(program);
167
- printError(message, { mode: flags.mode, color: flags.color }, statusCode);
168
- return isCommanderUsageError(err) ? 2 : 1;
117
+ return reportFailure(err, resolveFlagsSafe(program), active);
169
118
  }
170
119
  }
171
- function isCommanderHelpError(err) {
172
- return (typeof err === "object" &&
173
- err !== null &&
174
- "code" in err &&
175
- typeof err.code === "string" &&
176
- (err.code === "commander.helpDisplayed" ||
177
- err.code === "commander.help" ||
178
- err.code === "commander.version"));
179
- }
180
- function isCommanderUsageError(err) {
181
- return (typeof err === "object" &&
182
- err !== null &&
183
- "code" in err &&
184
- typeof err.code === "string" &&
185
- err.code.startsWith("commander."));
186
- }
187
120
  function isDirectInvocation(argv1) {
188
121
  if (argv1 === undefined)
189
122
  return false;
@@ -194,14 +127,17 @@ function isDirectInvocation(argv1) {
194
127
  return false;
195
128
  }
196
129
  }
197
- const invokedDirectly = typeof process !== "undefined" &&
198
- Array.isArray(process.argv) &&
199
- isDirectInvocation(process.argv[1]);
200
- if (invokedDirectly) {
130
+ if (isDirectInvocation(process.argv[1])) {
131
+ for (const stream of [process.stdout, process.stderr]) {
132
+ stream.on("error", (err) => {
133
+ if (!isClosedPipeError(err))
134
+ throw err;
135
+ });
136
+ }
201
137
  main(process.argv).then((code) => {
202
138
  process.exitCode = code;
203
139
  }, (err) => {
204
- console.error(`fatal: ${clockifyErrorDetail(err)}`);
140
+ console.error(`fatal: ${err instanceof Error ? err.message : String(err)}`);
205
141
  process.exitCode = 1;
206
142
  });
207
143
  }
package/dist/output.js CHANGED
@@ -1,6 +1,17 @@
1
- import Table from "cli-table3";
1
+ import { createRequire } from "node:module";
2
2
  import pc from "picocolors";
3
3
  import { errorCodeForMessage, errorCodeForStatus, recoveryForCode, retryableForCode, } from "./error-codes.js";
4
+ const paint = pc.createColors(true);
5
+ let tableConstructor;
6
+ function newTable(head) {
7
+ tableConstructor ??= createRequire(import.meta.url)("cli-table3");
8
+ return new tableConstructor({ head, style: { head: [], border: [] } });
9
+ }
10
+ const TERMINAL_SEQUENCE = /(?:\u001b\[|\u009b)[\u0030-\u003f]*[\u0020-\u002f]*[\u0040-\u007e]|(?:\u001b[\]PX^_]|[\u0090\u0098\u009d\u009e\u009f])[^\u0007\u001b\u009c]*(?:\u0007|\u001b\\|\u009c)?|\u001b[\u0020-\u002f]*[\u0030-\u007e]?/gu;
11
+ const CONTROL_CHARACTER = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/gu;
12
+ function terminalSafe(text) {
13
+ return text.replace(TERMINAL_SEQUENCE, "").replace(CONTROL_CHARACTER, "");
14
+ }
4
15
  export class AlreadyReportedError extends Error {
5
16
  constructor() {
6
17
  super("Command failed after reporting the error response.");
@@ -17,14 +28,12 @@ export function printRecords(rows, opts) {
17
28
  return;
18
29
  }
19
30
  if (rows.length === 0) {
20
- console.log(opts.color ? pc.dim("(no rows)") : "(no rows)");
31
+ console.log(opts.color ? paint.dim("(no rows)") : "(no rows)");
21
32
  return;
22
33
  }
23
34
  const headers = collectHeaders(rows);
24
- const table = new Table({
25
- head: opts.color ? headers.map((h) => pc.bold(h)) : headers,
26
- style: { head: [], border: [] },
27
- });
35
+ const labels = headers.map(terminalSafe);
36
+ const table = newTable(opts.color ? labels.map((h) => paint.bold(h)) : labels);
28
37
  for (const row of rows) {
29
38
  table.push(headers.map((h) => stringifyCell(row[h])));
30
39
  }
@@ -39,50 +48,72 @@ export function printObject(obj, opts) {
39
48
  printNdjson(obj, opts);
40
49
  return;
41
50
  }
42
- const table = new Table({
43
- head: opts.color ? [pc.bold("field"), pc.bold("value")] : ["field", "value"],
44
- style: { head: [], border: [] },
45
- });
51
+ const table = newTable(opts.color ? [paint.bold("field"), paint.bold("value")] : ["field", "value"]);
46
52
  for (const [key, value] of Object.entries(obj)) {
47
- table.push([key, stringifyCell(value)]);
53
+ table.push([terminalSafe(key), stringifyCell(value)]);
48
54
  }
49
55
  console.log(table.toString());
50
56
  }
51
- export function printError(message, opts, statusCode) {
52
- const messageCode = errorCodeForMessage(message);
53
- const code = messageCode === "not_found" && statusCode === 400
54
- ? "not_found"
55
- : (errorCodeForStatus(statusCode) ?? messageCode);
57
+ export function printWarning(message, opts) {
58
+ const color = opts.errorColor ?? opts.color;
59
+ console.error(`${color ? paint.yellow("WARN") : "WARN"} ${terminalSafe(message)}`);
60
+ }
61
+ const ARCHIVED_BY = { archived_by_call: " by this call", already_archived: " before this call" };
62
+ export function printError(message, opts, statusCode, classified, partial, details) {
63
+ const { code, recovery, retryable } = { ...(classified ?? classifyByStatusOrMessage(message, statusCode)), ...details };
56
64
  if (opts.mode !== "table") {
65
+ const serverCode = classified?.serverCode;
57
66
  console.error(JSON.stringify({
58
67
  ok: false,
59
68
  error: message,
69
+ ...(partial && { completedStage: partial.completedStage, next: partial.next }),
70
+ ...(partial?.archiveAction && { archiveAction: partial.archiveAction }),
60
71
  code,
61
- recovery: recoveryForCode(code),
62
- retryable: retryableForCode(code),
72
+ ...details,
73
+ ...(typeof statusCode === "number" ? { status: statusCode } : {}),
74
+ ...(serverCode !== undefined && /^\d+$/.test(serverCode) ? { serverCode: Number(serverCode) } : {}),
75
+ recovery,
76
+ retryable,
63
77
  }));
64
78
  return;
65
79
  }
66
- const prefix = opts.color ? pc.red("ERR") : "ERR";
67
- console.error(`${prefix} ${message}`);
68
- const recovery = recoveryForCode(code);
80
+ const color = opts.errorColor ?? opts.color;
81
+ console.error(`${color ? paint.red("ERR") : "ERR"} ${terminalSafe(message)}`);
82
+ if (partial) {
83
+ const by = partial.archiveAction === undefined ? "" : ARCHIVED_BY[partial.archiveAction];
84
+ console.error(`Completed: ${partial.completedStage}${by}. Check with ${terminalSafe(partial.next)}`);
85
+ }
69
86
  if (recovery) {
70
- console.error(`${opts.color ? pc.dim("→") : "→"} ${recovery}`);
87
+ console.error(`${color ? paint.dim("→") : "→"} ${terminalSafe(recovery)}`);
71
88
  }
72
89
  }
90
+ function classifyByStatusOrMessage(message, statusCode) {
91
+ const messageCode = errorCodeForMessage(message);
92
+ const code = messageCode === "not_found" && statusCode === 400
93
+ ? "not_found"
94
+ : messageCode === "feature_unavailable" && (statusCode === 401 || statusCode === 403)
95
+ ? "feature_unavailable"
96
+ : (errorCodeForStatus(statusCode) ?? messageCode);
97
+ return { code, recovery: recoveryForCode(code), retryable: retryableForCode(code) };
98
+ }
73
99
  export function selectValue(value, selector) {
74
100
  if (!selector) {
75
101
  return value;
76
102
  }
103
+ return selectPath(value, selector.split(".").filter(Boolean));
104
+ }
105
+ function selectPath(value, parts) {
77
106
  let current = value;
78
- for (const part of selector.split(".").filter(Boolean)) {
107
+ for (const [position, part] of parts.entries()) {
79
108
  if (Array.isArray(current)) {
80
- const index = Number(part);
81
- if (!Number.isInteger(index) || index < 0 || index >= current.length) {
82
- return undefined;
109
+ if (/^\d+$/.test(part)) {
110
+ current = current[Number(part)];
111
+ if (current === undefined)
112
+ return undefined;
113
+ continue;
83
114
  }
84
- current = current[index];
85
- continue;
115
+ const rest = parts.slice(position);
116
+ return current.map((item) => selectPath(item, rest) ?? null);
86
117
  }
87
118
  if (current !== null && typeof current === "object" && Object.hasOwn(current, part)) {
88
119
  current = current[part];
@@ -120,6 +151,9 @@ function collectHeaders(rows) {
120
151
  return ordered;
121
152
  }
122
153
  function stringifyCell(value) {
154
+ return terminalSafe(rawCellText(value));
155
+ }
156
+ function rawCellText(value) {
123
157
  if (value === null || value === undefined) {
124
158
  return "";
125
159
  }