@apet97/clockify-cli-115 5.0.4 → 7.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 (55) hide show
  1. package/README.md +255 -39
  2. package/dist/client.js +43 -17
  3. package/dist/closed-pipe.js +3 -0
  4. package/dist/commands/api.js +192 -103
  5. package/dist/commands/approvals.js +9 -10
  6. package/dist/commands/auditlog.js +11 -8
  7. package/dist/commands/auth.js +229 -0
  8. package/dist/commands/balanceAssignment.js +10 -8
  9. package/dist/commands/batch.js +226 -0
  10. package/dist/commands/clients.js +27 -72
  11. package/dist/commands/doctor.js +98 -82
  12. package/dist/commands/entries.js +29 -14
  13. package/dist/commands/expenses.js +75 -36
  14. package/dist/commands/helpers.js +74 -9
  15. package/dist/commands/invoices.js +12 -16
  16. package/dist/commands/leaf-command.js +15 -0
  17. package/dist/commands/log.js +4 -2
  18. package/dist/commands/manifest.js +63 -0
  19. package/dist/commands/operations.js +271 -0
  20. package/dist/commands/projects.js +28 -32
  21. package/dist/commands/reports.js +54 -21
  22. package/dist/commands/resolve-refs.js +30 -53
  23. package/dist/commands/scheduling.js +94 -40
  24. package/dist/commands/shared-report-body.js +127 -0
  25. package/dist/commands/sharedReports.js +19 -235
  26. package/dist/commands/skill.js +85 -0
  27. package/dist/commands/start.js +6 -4
  28. package/dist/commands/status.js +69 -27
  29. package/dist/commands/stop.js +7 -18
  30. package/dist/commands/tags.js +11 -11
  31. package/dist/commands/tasks.js +27 -133
  32. package/dist/commands/timeoff.js +23 -16
  33. package/dist/commands/users.js +11 -19
  34. package/dist/commands/webhook-delivery.js +331 -0
  35. package/dist/commands/webhooks.js +40 -104
  36. package/dist/completions.js +291 -55
  37. package/dist/config.js +168 -61
  38. package/dist/credentials.js +164 -0
  39. package/dist/duration.js +5 -4
  40. package/dist/failure.js +82 -0
  41. package/dist/flags.js +84 -0
  42. package/dist/generated/version.js +1 -1
  43. package/dist/index.js +68 -108
  44. package/dist/interrupts.js +28 -0
  45. package/dist/output.js +189 -66
  46. package/dist/receipt.js +2 -10
  47. package/dist/stdin.js +6 -0
  48. package/dist/stdout.js +38 -0
  49. package/dist/write-outcome.js +84 -0
  50. package/package.json +6 -4
  51. package/plugin/.claude-plugin/plugin.json +16 -0
  52. package/plugin/skills/clockify-cli/SKILL.md +88 -0
  53. package/plugin/skills/clockify-mcp/SKILL.md +48 -0
  54. package/plugin/skills/clockify-sdk/SKILL.md +85 -0
  55. package/dist/error-codes.js +0 -272
@@ -1,22 +1,24 @@
1
1
  import { listExpensesFiltered } from "clockify-sdk-ts-115/expense-list";
2
- import { entityId } from "clockify-sdk-ts-115/operation-receipt";
3
- import { printObject, printRecords } from "../output.js";
2
+ import { expenseAmountToWire } from "clockify-sdk-ts-115/money";
3
+ import { expenseChangeFields } from "clockify-sdk-ts-115/updates";
4
+ import { InvalidArgumentError } from "commander";
5
+ import { UsageError } from "../failure.js";
6
+ import { resolveFlags } from "../flags.js";
7
+ import { pickFields, printObject, printRecords, printWarning, warnUnknownFields } from "../output.js";
4
8
  import { printReceipt } from "../receipt.js";
5
- import { clampPageSize, parseFloatArg, parseIntArg, promoteDateBoundary, resolveContext, } from "./helpers.js";
9
+ import { dispatchedWrite } from "../write-outcome.js";
10
+ import { clampPageSize, parseFloatArg, parseIntArg, printScan, promoteDateBoundary, requireCurrentUserId, resolveContext, rootProgram, } from "./helpers.js";
6
11
  import { leafCommand } from "./leaf-command.js";
7
- const EXPENSE_CHANGE_FIELDS = {
8
- amount: "AMOUNT",
9
- date: "DATE",
10
- projectId: "PROJECT",
11
- taskId: "TASK",
12
- categoryId: "CATEGORY",
13
- notes: "NOTES",
14
- billable: "BILLABLE",
15
- };
16
- function expenseChangeFields(fields) {
17
- return Object.entries(EXPENSE_CHANGE_FIELDS)
18
- .filter(([key]) => fields[key] !== undefined)
19
- .map(([, value]) => value);
12
+ function parseExpenseAmount(value) {
13
+ const amount = parseFloatArg(value);
14
+ try {
15
+ return expenseAmountToWire(amount);
16
+ }
17
+ catch (cause) {
18
+ if (!(cause instanceof RangeError))
19
+ throw cause;
20
+ throw new InvalidArgumentError(`must not exceed ${Number.MAX_SAFE_INTEGER}, the largest amount that can be sent exactly.`);
21
+ }
20
22
  }
21
23
  export const registerExpensesCommand = (program, services) => {
22
24
  const expenses = program.command("expenses").description("Inspect workspace expenses.");
@@ -24,22 +26,38 @@ export const registerExpensesCommand = (program, services) => {
24
26
  .description("List expenses in the workspace.")
25
27
  .addHelpText("after", "\nExamples:\n" +
26
28
  " $ clk115 expenses list\n" +
29
+ " $ clk115 expenses list --json --with-meta\n" +
27
30
  " $ clk115 expenses list --start 2026-06-01 --end 2026-06-30\n")
31
+ .option("--with-meta", "Include scan metadata in JSON or as the final NDJSON line.")
28
32
  .option("--limit <n>", "Total records to return (default 25, max 10000).", parseIntArg, 25)
29
33
  .option("--page-size <n>", "Records fetched per page (default 50, max 200).", parseIntArg, 50)
30
34
  .option("--max-pages <n>", "Maximum pages to scan (default 100, max 1000).", parseIntArg, 100)
35
+ .option("--offset <n>", "Matching rows to skip on the first page when resuming.", (value) => value === "0" ? 0 : parseIntArg(value), 0)
31
36
  .option("--page <n>", "Page number.", parseIntArg, 1)
37
+ .option("--require-complete", "Print the rows, then exit 1 when more may be available.", false)
32
38
  .option("--start <date>", "Inclusive start bound (YYYY-MM-DD or RFC3339 with explicit Z/offset).")
33
39
  .option("--end <date>", "Inclusive end bound (YYYY-MM-DD or RFC3339 with explicit Z/offset).")
34
40
  .action(async function (opts) {
41
+ if (opts.withMeta && resolveFlags(rootProgram(this)).mode === "csv") {
42
+ throw new UsageError("--with-meta needs --output json or ndjson.");
43
+ }
35
44
  const { client, workspaceId, output } = await resolveContext(this, services);
36
- const result = await listExpensesFiltered(client.expenses.list.bind(client.expenses), { workspaceId }, {
45
+ let requested = false;
46
+ const result = await listExpensesFiltered((request) => {
47
+ requested = true;
48
+ return client.expenses.list(request);
49
+ }, { workspaceId }, {
37
50
  page: opts.page,
51
+ offset: opts.offset,
38
52
  pageSize: clampPageSize(opts.pageSize, 200),
39
53
  limit: opts.limit,
40
54
  maxPages: opts.maxPages,
41
55
  ...(opts.start !== undefined ? { start: opts.start } : {}),
42
56
  ...(opts.end !== undefined ? { end: opts.end } : {}),
57
+ }).catch((cause) => {
58
+ if (!requested && cause instanceof RangeError)
59
+ throw new UsageError(cause.message);
60
+ throw cause;
43
61
  });
44
62
  const rows = result.items.map((raw) => {
45
63
  const e = raw;
@@ -53,17 +71,42 @@ export const registerExpensesCommand = (program, services) => {
53
71
  date: e.date ?? "",
54
72
  category,
55
73
  projectId: e.project?.id ?? "",
56
- amount: e.total ?? e.amount ?? e.quantity ?? 0,
74
+ ...(output.mode === "table" ? { amount: e.total ?? "—" } : {
75
+ amount: e.total ?? e.amount ?? e.quantity ?? 0,
76
+ totalMinor: e.total ?? null,
77
+ amountSource: e.total == null ? "unavailable" : "total",
78
+ }),
57
79
  currency: e.currency ?? "",
58
80
  billable: e.billable === true,
59
81
  };
60
82
  });
61
83
  for (const warning of result.warnings)
62
- console.error(`WARN ${warning}`);
63
- printRecords(rows, output);
84
+ printWarning(warning, output);
85
+ const { meta } = result;
86
+ let gap;
87
+ if (meta.hasMore) {
88
+ const continuation = meta.nextPage === undefined
89
+ ? "Reached the last supported page."
90
+ : `Keep the same filters and page size and append --page ${meta.nextPage} --offset ${meta.nextOffset ?? 0} --max-pages ${meta.nextMaxPages}`;
91
+ const reason = rows.length === meta.limit
92
+ ? `Returned the requested --limit of ${meta.limit} expenses. More rows may be available.`
93
+ : "The --max-pages cap stopped the scan before all pages were examined. Matches may be missing.";
94
+ gap = `${reason} ${continuation}`;
95
+ }
96
+ printScan(() => {
97
+ if (opts.withMeta && output.mode === "json") {
98
+ const { fields, ...shape } = output;
99
+ warnUnknownFields(rows, output);
100
+ printObject({ items: rows.map((row) => pickFields(row, fields)), meta }, shape);
101
+ return;
102
+ }
103
+ printRecords(rows, output);
104
+ if (opts.withMeta && output.mode === "ndjson")
105
+ console.log(JSON.stringify({ meta }));
106
+ }, gap, opts.requireComplete, output);
64
107
  });
65
108
  leafCommand(expenses, "create", "write")
66
- .requiredOption("--amount <n>", "Amount.", parseFloatArg)
109
+ .requiredOption("--amount <n>", "Amount.", parseExpenseAmount)
67
110
  .requiredOption("--category <id>", "Expense category ID.")
68
111
  .requiredOption("--date <date>", "Expense date (YYYY-MM-DD or ISO).")
69
112
  .option("--user <id>", "Owning user ID (defaults to the API-key owner).")
@@ -76,18 +119,14 @@ export const registerExpensesCommand = (program, services) => {
76
119
  .addHelpText("after", "\nExamples:\n" +
77
120
  " $ clk115 expenses create --amount 42.50 --category cat_123 --date 2026-06-01\n")
78
121
  .action(async function (opts) {
122
+ const date = promoteDateBoundary(opts.date, "date", "start");
79
123
  const { client, workspaceId, output } = await resolveContext(this, services);
80
- let userId = opts.user;
81
- if (!userId) {
82
- userId = entityId(await client.users.getCurrentUser());
83
- if (!userId) {
84
- throw new Error("could not determine user ID from getCurrentUser response; pass --user.");
85
- }
86
- }
124
+ const userId = opts.user ||
125
+ (await requireCurrentUserId(client, "pass --user"));
87
126
  const fields = {
88
127
  amount: opts.amount,
89
128
  categoryId: opts.category,
90
- date: promoteDateBoundary(opts.date, "date", "start"),
129
+ date,
91
130
  };
92
131
  if (opts.project)
93
132
  fields.projectId = opts.project;
@@ -97,11 +136,11 @@ export const registerExpensesCommand = (program, services) => {
97
136
  fields.notes = opts.notes;
98
137
  if (opts.billable !== undefined)
99
138
  fields.billable = opts.billable;
100
- const created = (await client.expenses.create({
139
+ const created = (await dispatchedWrite(this, client.expenses.create({
101
140
  ...fields,
102
141
  userId,
103
142
  workspaceId,
104
- }));
143
+ })));
105
144
  const data = { id: created.id ?? "" };
106
145
  printReceipt({
107
146
  ok: true,
@@ -129,7 +168,7 @@ export const registerExpensesCommand = (program, services) => {
129
168
  });
130
169
  leafCommand(expenses, "update", "write")
131
170
  .argument("<id>", "Expense ID.")
132
- .requiredOption("--amount <n>", "Amount.", parseFloatArg)
171
+ .requiredOption("--amount <n>", "Amount.", parseExpenseAmount)
133
172
  .requiredOption("--category <id>", "Expense category ID.")
134
173
  .requiredOption("--date <date>", "Expense date (YYYY-MM-DD or ISO).")
135
174
  .requiredOption("--user <id>", "Owning user ID.")
@@ -143,12 +182,12 @@ export const registerExpensesCommand = (program, services) => {
143
182
  " $ clk115 expenses update expense_123 --amount 50 --category cat_123 \\\n" +
144
183
  " --date 2026-06-01 --user user_123\n")
145
184
  .action(async function (id, opts) {
146
- const { client, workspaceId, output } = await resolveContext(this, services);
147
185
  const fields = {
148
186
  amount: opts.amount,
149
187
  categoryId: opts.category,
150
188
  date: promoteDateBoundary(opts.date, "date", "start"),
151
189
  };
190
+ const { client, workspaceId, output } = await resolveContext(this, services);
152
191
  if (opts.project)
153
192
  fields.projectId = opts.project;
154
193
  if (opts.task)
@@ -157,13 +196,13 @@ export const registerExpensesCommand = (program, services) => {
157
196
  fields.notes = opts.notes;
158
197
  if (opts.billable !== undefined)
159
198
  fields.billable = opts.billable;
160
- const updated = (await client.expenses.update({
199
+ const updated = (await dispatchedWrite(this, client.expenses.update({
161
200
  ...fields,
162
201
  changeFields: expenseChangeFields(fields),
163
202
  userId: opts.user,
164
203
  expenseId: id,
165
204
  workspaceId,
166
- }));
205
+ })));
167
206
  const data = { id: updated.id ?? id };
168
207
  printReceipt({
169
208
  ok: true,
@@ -186,7 +225,7 @@ export const registerExpensesCommand = (program, services) => {
186
225
  .addHelpText("after", "\nExamples:\n" + " $ clk115 expenses delete expense_123\n")
187
226
  .action(async function (id) {
188
227
  const { client, workspaceId, output } = await resolveContext(this, services);
189
- await client.expenses.delete({ workspaceId, expenseId: id });
228
+ await dispatchedWrite(this, client.expenses.delete({ workspaceId, expenseId: id }));
190
229
  printReceipt({
191
230
  ok: true,
192
231
  action: "expenses.delete",
@@ -1,6 +1,11 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { entityId } from "clockify-sdk-ts-115/operation-receipt";
1
3
  import { InvalidArgumentError } from "commander";
2
4
  import { requireWorkspaceId } from "../config.js";
3
- import { globalFlags, resolveFlags } from "../index.js";
5
+ import { UsageError } from "../failure.js";
6
+ import { globalFlags, resolveFlags } from "../flags.js";
7
+ import { printWarning } from "../output.js";
8
+ import { readStdin } from "../stdin.js";
4
9
  function parseStrictNumber(value) {
5
10
  const trimmed = value.trim();
6
11
  if (trimmed === "" || /^[+-]?0[xXoObB]/.test(trimmed)) {
@@ -8,6 +13,18 @@ function parseStrictNumber(value) {
8
13
  }
9
14
  return Number(trimmed);
10
15
  }
16
+ export const TIME_VIEW_MODES = [
17
+ "TIME_SENSITIVE_VIEW",
18
+ "AGGREGATED_TIME_VIEW",
19
+ ];
20
+ export const TIME_VIEW_MODE_HELP = "Time view mode: TIME_SENSITIVE_VIEW (server default) or AGGREGATED_TIME_VIEW (needs Original time view enabled on the workspace).";
21
+ export function parseTimeViewMode(value) {
22
+ const mode = String(value).toUpperCase();
23
+ if (!TIME_VIEW_MODES.includes(mode)) {
24
+ throw new UsageError(`Unknown --time-view-mode "${String(value)}". Provide one of: ${TIME_VIEW_MODES.join(", ")}.`);
25
+ }
26
+ return mode;
27
+ }
11
28
  export function parseIntArg(value) {
12
29
  const parsed = parseStrictNumber(value);
13
30
  if (!Number.isInteger(parsed) || parsed <= 0) {
@@ -38,6 +55,40 @@ export function splitList(value) {
38
55
  .map((s) => s.trim())
39
56
  .filter((s) => s.length > 0);
40
57
  }
58
+ export function collect(value, previous) {
59
+ return [...previous, value];
60
+ }
61
+ export function parsePair(value, flag) {
62
+ const index = value.indexOf("=");
63
+ if (index <= 0) {
64
+ throw new UsageError(`${flag} expected key=value, received "${value}".`);
65
+ }
66
+ const key = value.slice(0, index).trim();
67
+ if (!key) {
68
+ throw new UsageError(`${flag} expected a non-empty key in "${value}".`);
69
+ }
70
+ return [key, value.slice(index + 1)];
71
+ }
72
+ export async function readTextInput(value, flag) {
73
+ if (value === undefined || (value !== "-" && !value.startsWith("@")))
74
+ return value;
75
+ try {
76
+ return value === "-" ? await readStdin() : readFileSync(value.slice(1), "utf8");
77
+ }
78
+ catch (err) {
79
+ const detail = err instanceof Error ? err.message : String(err);
80
+ throw new UsageError(`${flag} ${JSON.stringify(value)} could not be read: ${detail}; provide a readable JSON file path or pipe the body on stdin`);
81
+ }
82
+ }
83
+ export function parseJson(text, flag, alternative) {
84
+ try {
85
+ return JSON.parse(text);
86
+ }
87
+ catch (err) {
88
+ const detail = err instanceof Error ? err.message : String(err);
89
+ throw new UsageError(`${flag} is not valid JSON (${detail}); provide valid JSON${alternative === undefined ? "." : `, or ${alternative}.`}`);
90
+ }
91
+ }
41
92
  const BARE_DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
42
93
  const RFC3339_TIMESTAMP_PATTERN = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|[+-](\d{2}):(\d{2}))$/;
43
94
  function hasValidCalendarDate(yearText, monthText, dayText) {
@@ -71,13 +122,13 @@ function isRfc3339Timestamp(value) {
71
122
  export function requireCalendarDate(value, flag) {
72
123
  const match = BARE_DATE_PATTERN.exec(value);
73
124
  if (match === null || !hasValidCalendarDate(match[1], match[2], match[3])) {
74
- throw new Error(`--${flag} ${JSON.stringify(value)} is not a valid calendar date (YYYY-MM-DD); provide a real calendar date`);
125
+ throw new UsageError(`--${flag} ${JSON.stringify(value)} is not a valid calendar date (YYYY-MM-DD); provide a real calendar date`);
75
126
  }
76
127
  return value;
77
128
  }
78
129
  export function requireRfc3339Timestamp(value, flag) {
79
130
  if (!isRfc3339Timestamp(value)) {
80
- throw new Error(`--${flag} ${JSON.stringify(value)} is not a valid RFC3339 timestamp; provide a value such as 2026-06-22T09:30:00Z`);
131
+ throw new UsageError(`--${flag} ${JSON.stringify(value)} is not a valid RFC3339 timestamp; provide a value such as 2026-06-22T09:30:00Z`);
81
132
  }
82
133
  return value;
83
134
  }
@@ -86,7 +137,7 @@ export function requireDateOrRfc3339(value, flag) {
86
137
  return requireCalendarDate(value, flag);
87
138
  }
88
139
  if (!isRfc3339Timestamp(value)) {
89
- throw new Error(`--${flag} ${JSON.stringify(value)} is not a valid date (YYYY-MM-DD) or RFC3339 timestamp; provide YYYY-MM-DD or an RFC3339 timestamp`);
140
+ throw new UsageError(`--${flag} ${JSON.stringify(value)} is not a valid date (YYYY-MM-DD) or RFC3339 timestamp; provide YYYY-MM-DD or an RFC3339 timestamp`);
90
141
  }
91
142
  return value;
92
143
  }
@@ -97,6 +148,13 @@ export function promoteDateBoundary(value, flag, edge) {
97
148
  }
98
149
  return validValue;
99
150
  }
151
+ export function printScan(print, gap, requireComplete, output) {
152
+ if (gap !== undefined && !requireComplete)
153
+ printWarning(gap, output);
154
+ print();
155
+ if (gap !== undefined && requireComplete)
156
+ throw new Error(gap);
157
+ }
100
158
  export function rootProgram(cmd) {
101
159
  let current = cmd;
102
160
  while (current.parent != null) {
@@ -104,14 +162,21 @@ export function rootProgram(cmd) {
104
162
  }
105
163
  return current;
106
164
  }
107
- export async function resolveBaseContext(cmd, services) {
165
+ export async function resolveBaseContext(cmd, services, resolvedOutput) {
108
166
  const program = rootProgram(cmd);
167
+ const output = resolvedOutput ?? resolveFlags(program);
109
168
  const config = services.loadConfig(globalFlags(program));
110
- const client = await services.buildClient(config);
111
- const output = resolveFlags(program);
169
+ const client = await services.buildClient(config, cmd);
112
170
  return { client, config, output };
113
171
  }
114
- export async function resolveContext(cmd, services) {
115
- const { client, config, output } = await resolveBaseContext(cmd, services);
172
+ export async function resolveContext(cmd, services, resolvedOutput) {
173
+ const { client, config, output } = await resolveBaseContext(cmd, services, resolvedOutput);
116
174
  return { client, workspaceId: requireWorkspaceId(config), output };
117
175
  }
176
+ export async function requireCurrentUserId(client, hint) {
177
+ const userId = entityId(await client.users.getCurrentUser());
178
+ if (!userId) {
179
+ throw new Error(`could not determine user ID from the current-user response${hint ? `; ${hint}` : ""}`);
180
+ }
181
+ return userId;
182
+ }
@@ -1,11 +1,8 @@
1
1
  import { printRecords } from "../output.js";
2
2
  import { printReceipt } from "../receipt.js";
3
- import { clampPageSize, parseIntArg, promoteDateBoundary, resolveContext } from "./helpers.js";
3
+ import { dispatchedWrite } from "../write-outcome.js";
4
+ import { clampPageSize, parseIntArg, parseTimeViewMode, promoteDateBoundary, resolveContext, TIME_VIEW_MODE_HELP, } from "./helpers.js";
4
5
  import { leafCommand } from "./leaf-command.js";
5
- const TIME_VIEW_MODES = [
6
- "TIME_SENSITIVE_VIEW",
7
- "AGGREGATED_TIME_VIEW",
8
- ];
9
6
  export const registerInvoicesCommand = (program, services) => {
10
7
  const invoices = program.command("invoices").description("Manage invoices.");
11
8
  leafCommand(invoices, "list", "read")
@@ -28,7 +25,11 @@ export const registerInvoicesCommand = (program, services) => {
28
25
  number: inv.number ?? "",
29
26
  client: inv.clientName ?? inv.clientId ?? "",
30
27
  currency: inv.currency ?? "",
31
- amount: inv.amount ?? 0,
28
+ ...(output.mode === "table" ? { amount: inv.amount ?? "—" } : {
29
+ amount: inv.amount ?? 0,
30
+ totalMinor: inv.amount ?? null,
31
+ amountSource: inv.amount == null ? "unavailable" : "total",
32
+ }),
32
33
  status: inv.status ?? "",
33
34
  issued: inv.issuedDate ?? "",
34
35
  due: inv.dueDate ?? "",
@@ -46,9 +47,8 @@ export const registerInvoicesCommand = (program, services) => {
46
47
  .requiredOption("--currency <code>", "ISO currency code (e.g. USD, EUR).")
47
48
  .requiredOption("--issued <date>", "Issued date (YYYY-MM-DD or RFC3339).")
48
49
  .requiredOption("--due <date>", "Due date (YYYY-MM-DD or RFC3339).")
49
- .option("--time-view-mode <mode>", "Time view mode: TIME_SENSITIVE_VIEW or AGGREGATED_TIME_VIEW.")
50
+ .option("--time-view-mode <mode>", TIME_VIEW_MODE_HELP)
50
51
  .action(async function (opts) {
51
- const { client, workspaceId, output } = await resolveContext(this, services);
52
52
  const body = {
53
53
  clientId: opts.client,
54
54
  number: opts.number,
@@ -56,15 +56,11 @@ export const registerInvoicesCommand = (program, services) => {
56
56
  issuedDate: normaliseInvoiceDate(opts.issued, "issued"),
57
57
  dueDate: normaliseInvoiceDate(opts.due, "due"),
58
58
  };
59
- if (opts.timeViewMode !== undefined) {
60
- const mode = String(opts.timeViewMode).toUpperCase();
61
- if (!TIME_VIEW_MODES.includes(mode)) {
62
- throw new Error(`Unknown --time-view-mode "${String(opts.timeViewMode)}". Provide one of: ${TIME_VIEW_MODES.join(", ")}.`);
63
- }
64
- body.timeViewMode = mode;
65
- }
59
+ if (opts.timeViewMode !== undefined)
60
+ body.timeViewMode = parseTimeViewMode(opts.timeViewMode);
61
+ const { client, workspaceId, output } = await resolveContext(this, services);
66
62
  const req = { workspaceId, body };
67
- const created = (await client.invoices.create(req));
63
+ const created = (await dispatchedWrite(this, client.invoices.create(req)));
68
64
  const data = {
69
65
  id: created.id ?? "",
70
66
  number: created.number ?? "",
@@ -1,4 +1,19 @@
1
1
  const commandRisks = new WeakMap();
2
+ const declaredMutations = new WeakMap();
3
+ export function declareMutation(command, mutates) {
4
+ declaredMutations.set(command, mutates);
5
+ }
6
+ export function isMutationCommand(command) {
7
+ const declared = declaredMutations.get(command);
8
+ if (declared !== undefined)
9
+ return declared;
10
+ if (command.name() === "api") {
11
+ const method = command.args[0]?.toUpperCase();
12
+ return method !== undefined && ["POST", "PUT", "PATCH", "DELETE"].includes(method);
13
+ }
14
+ const risk = commandRisks.get(command);
15
+ return risk === "write" || risk === "destructive";
16
+ }
2
17
  export function leafCommand(parent, syntax, risk) {
3
18
  if (commandRisks.has(parent)) {
4
19
  throw new Error(`A classified leaf cannot become a grouping node: ${parent.name()}`);
@@ -1,5 +1,7 @@
1
1
  import { parseDuration } from "../duration.js";
2
+ import { UsageError } from "../failure.js";
2
3
  import { printReceipt } from "../receipt.js";
4
+ import { dispatchedWrite } from "../write-outcome.js";
3
5
  import { requireRfc3339Timestamp, resolveContext } from "./helpers.js";
4
6
  import { leafCommand } from "./leaf-command.js";
5
7
  import { resolveProjectId, resolveTaskId, resolveTagIds } from "./resolve-refs.js";
@@ -18,7 +20,7 @@ export const registerLogCommand = (program, services) => {
18
20
  .option("--end <iso>", "End timestamp (ISO 8601). Defaults to now.")
19
21
  .action(async function (duration, description, opts) {
20
22
  if (opts.task && !opts.project) {
21
- throw new Error("--task requires --project: a task entry must be scoped to its project.");
23
+ throw new UsageError("--task requires --project: a task entry must be scoped to its project.");
22
24
  }
23
25
  const seconds = parseDuration(duration);
24
26
  const endInput = requireRfc3339Timestamp(opts.end ?? new Date().toISOString(), "end");
@@ -49,7 +51,7 @@ export const registerLogCommand = (program, services) => {
49
51
  if (opts.billable)
50
52
  body.billable = true;
51
53
  const req = { workspaceId, body };
52
- const created = await client.timeEntries.create(req);
54
+ const created = await dispatchedWrite(this, client.timeEntries.create(req));
53
55
  const entry = created;
54
56
  const data = {
55
57
  id: entry.id ?? "",
@@ -0,0 +1,63 @@
1
+ import { resolveFlags } from "../flags.js";
2
+ import { PACKAGE_VERSION } from "../generated/version.js";
3
+ import { fixedColumns, printObject, printRecords } from "../output.js";
4
+ import { collectClassifiedLeaves, leafCommand } from "./leaf-command.js";
5
+ function describeOption({ flags, long, description, mandatory, defaultValue, argChoices, variadic, required, optional }) {
6
+ const parameter = required ? "required" : optional ? "optional" : "none";
7
+ return {
8
+ name: long ?? flags,
9
+ flags,
10
+ description,
11
+ required: mandatory,
12
+ value: parameter,
13
+ ...(variadic && { variadic }),
14
+ ...(argChoices && { choices: argChoices }),
15
+ ...(defaultValue !== undefined && { default: defaultValue }),
16
+ };
17
+ }
18
+ function describeArgument(argument) {
19
+ return {
20
+ name: argument.name(),
21
+ description: argument.description,
22
+ required: argument.required,
23
+ ...(argument.variadic && { variadic: true }),
24
+ ...(argument.argChoices && { choices: argument.argChoices }),
25
+ ...(argument.defaultValue !== undefined && { default: argument.defaultValue }),
26
+ };
27
+ }
28
+ export function commandManifest(program) {
29
+ return {
30
+ name: program.name(),
31
+ version: PACKAGE_VERSION,
32
+ exitCodes: {
33
+ 0: "success",
34
+ 1: "runtime or API error",
35
+ 2: "usage error; nothing was changed",
36
+ 129: "interrupted (SIGHUP)",
37
+ 130: "interrupted (SIGINT)",
38
+ 143: "interrupted (SIGTERM)",
39
+ },
40
+ globalOptions: program.options.map(describeOption),
41
+ commands: collectClassifiedLeaves(program).map(({ path, risk, command }) => ({
42
+ command: path.join(" "),
43
+ risk,
44
+ description: command.description(),
45
+ arguments: command.registeredArguments.map(describeArgument),
46
+ options: command.options.map(describeOption),
47
+ })),
48
+ };
49
+ }
50
+ export const registerCommandsCommand = (program) => {
51
+ leafCommand(program, "commands", "read")
52
+ .description("List every command with its arguments, options and risk, for scripts and agents.")
53
+ .addHelpText("after", "\nExamples:\n" + " $ clk115 commands\n" + " $ clk115 commands --json --select commands.command\n")
54
+ .action(function () {
55
+ const output = resolveFlags(program);
56
+ const manifest = commandManifest(program);
57
+ const rows = manifest.commands.map(({ command, risk, description }) => ({ command, risk, description }));
58
+ if (output.mode === "json" || output.mode === "ndjson")
59
+ printObject(manifest, fixedColumns(Object.keys(manifest), output));
60
+ else
61
+ printRecords(rows, fixedColumns(["command", "risk", "description"], output));
62
+ });
63
+ };