@apet97/clockify-cli-115 6.0.0 → 8.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 (48) hide show
  1. package/README.md +167 -21
  2. package/dist/client.js +30 -7
  3. package/dist/commands/api.js +44 -76
  4. package/dist/commands/approvals.js +2 -5
  5. package/dist/commands/auth.js +229 -0
  6. package/dist/commands/balanceAssignment.js +5 -12
  7. package/dist/commands/batch.js +226 -0
  8. package/dist/commands/clients.js +18 -79
  9. package/dist/commands/doctor.js +65 -66
  10. package/dist/commands/entries.js +5 -8
  11. package/dist/commands/expenses.js +29 -39
  12. package/dist/commands/helpers.js +68 -30
  13. package/dist/commands/invoices.js +3 -3
  14. package/dist/commands/leaf-command.js +7 -0
  15. package/dist/commands/manifest.js +63 -0
  16. package/dist/commands/operations.js +271 -0
  17. package/dist/commands/projects.js +17 -37
  18. package/dist/commands/reports.js +22 -7
  19. package/dist/commands/shared-report-body.js +14 -81
  20. package/dist/commands/sharedReports.js +8 -47
  21. package/dist/commands/skill.js +85 -0
  22. package/dist/commands/status.js +19 -13
  23. package/dist/commands/stop.js +3 -12
  24. package/dist/commands/tags.js +12 -21
  25. package/dist/commands/tasks.js +26 -134
  26. package/dist/commands/timeoff.js +1 -1
  27. package/dist/commands/users.js +4 -14
  28. package/dist/commands/webhook-delivery.js +331 -0
  29. package/dist/commands/webhooks.js +37 -110
  30. package/dist/completions.js +2 -1
  31. package/dist/config.js +166 -63
  32. package/dist/credentials.js +164 -0
  33. package/dist/failure.js +4 -9
  34. package/dist/flags.js +14 -4
  35. package/dist/generated/version.js +1 -1
  36. package/dist/index.js +38 -15
  37. package/dist/interrupts.js +28 -0
  38. package/dist/output.js +137 -48
  39. package/dist/receipt.js +2 -10
  40. package/dist/stdin.js +6 -0
  41. package/dist/stdout.js +38 -0
  42. package/dist/write-outcome.js +1 -1
  43. package/package.json +5 -3
  44. package/plugin/.claude-plugin/plugin.json +16 -0
  45. package/plugin/skills/clockify-cli/SKILL.md +88 -0
  46. package/plugin/skills/clockify-mcp/SKILL.md +48 -0
  47. package/plugin/skills/clockify-sdk/SKILL.md +85 -0
  48. package/dist/error-codes.js +0 -300
@@ -1,9 +1,12 @@
1
- import { createRoutedClient } from "../client.js";
1
+ import { requireHeaderValue, requireRoute } from "../client.js";
2
2
  import { globalFlags, resolveFlags } from "../flags.js";
3
- import { printObject, printRecords } from "../output.js";
3
+ import { fixedColumns, printObject, printRecords } from "../output.js";
4
4
  import { rootProgram } from "./helpers.js";
5
5
  import { leafCommand } from "./leaf-command.js";
6
6
  const DEFAULT_CLOCKIFY_BASE_URL = "https://api.clockify.me/api/v1";
7
+ const RECEIPT_KEYS = ["ok", "readiness", "checks", "next"];
8
+ const CHECK_KEYS = ["check", "ok", "status", "source", "value", "recovery"];
9
+ const INSTALL_NODE = "Install Node.js 22.13 or newer";
7
10
  export const registerDoctorCommand = (program, services) => {
8
11
  leafCommand(program, "doctor", "read")
9
12
  .description("Check local CLI configuration without contacting Clockify.")
@@ -13,10 +16,12 @@ export const registerDoctorCommand = (program, services) => {
13
16
  .action(async function () {
14
17
  const root = rootProgram(this);
15
18
  const flags = globalFlags(root);
16
- const output = resolveFlags(root);
19
+ const { mode } = resolveFlags(root);
20
+ const asReceipt = mode === "json" || mode === "ndjson";
21
+ const output = fixedColumns(asReceipt ? RECEIPT_KEYS : CHECK_KEYS, resolveFlags(root));
17
22
  const config = services.loadConfig(flags);
18
- const receipt = await buildDoctorReceipt(config, flags, process.env);
19
- if (output.mode !== "table") {
23
+ const receipt = await buildDoctorReceipt(config, flags, process.env, services);
24
+ if (asReceipt) {
20
25
  printObject(receipt, output);
21
26
  return;
22
27
  }
@@ -28,32 +33,61 @@ export const registerDoctorCommand = (program, services) => {
28
33
  value: c.value ?? "",
29
34
  recovery: c.recovery ?? "",
30
35
  })), output);
31
- printObject({ ok: receipt.ok, readiness: receipt.readiness }, output);
36
+ if (mode === "csv")
37
+ return;
38
+ const { fields: _fields, ...summary } = output;
39
+ printObject({ ok: receipt.ok, readiness: receipt.readiness }, summary);
32
40
  for (const step of receipt.next)
33
41
  console.log(step);
34
42
  });
35
43
  };
36
- const offline = () => { throw new Error("Doctor is offline"); };
37
44
  async function acceptsBaseUrl(baseUrl) {
38
45
  try {
39
- await createRoutedClient({ baseUrl }, offline);
46
+ await requireRoute({ baseUrl });
40
47
  return true;
41
48
  }
42
49
  catch {
43
50
  return false;
44
51
  }
45
52
  }
46
- async function buildDoctorReceipt(config, flags, env) {
53
+ const messageOf = (err) => (err instanceof Error ? err.message : String(err));
54
+ function presentKey(key, source, value) {
55
+ try {
56
+ requireHeaderValue(key);
57
+ return { ok: true, status: "present", source, value };
58
+ }
59
+ catch (err) {
60
+ return { ok: false, status: "present", source, value, recovery: messageOf(err) };
61
+ }
62
+ }
63
+ async function checkApiKey(config, services) {
64
+ if (isPresent(config.apiKey))
65
+ return presentKey(config.apiKey, "env", "configured (redacted)");
66
+ if (config.profile === undefined) {
67
+ return { ok: false, status: "missing", recovery: "Set CLOCKIFY_API_KEY in the process environment, or run `clk115 auth login`." };
68
+ }
69
+ const { storedApiKey, systemCredentialStore } = await import("../credentials.js");
70
+ const login = `Run \`clk115 auth login --profile ${config.profile}\`.`;
71
+ try {
72
+ const key = await storedApiKey(config, services.credentials ?? systemCredentialStore);
73
+ if (key !== undefined)
74
+ return presentKey(key, "profile", `profile ${config.profile} (redacted)`);
75
+ return { ok: false, status: "missing", source: "profile", recovery: login };
76
+ }
77
+ catch (err) {
78
+ return { ok: false, status: "missing", source: "profile", recovery: `${messageOf(err)} ${login}` };
79
+ }
80
+ }
81
+ async function buildDoctorReceipt(config, flags, env, services) {
47
82
  const [nodeMajor = 0, nodeMinor = 0] = process.versions.node
48
83
  .split(".")
49
84
  .map((part) => Number.parseInt(part, 10) || 0);
50
85
  const nodeOk = nodeMajor > 22 || (nodeMajor === 22 && nodeMinor >= 13);
51
- const apiKeySource = sourceFor("apiKey", config, flags, env);
52
86
  const workspaceSource = sourceFor("workspaceId", config, flags, env);
53
87
  const baseUrlSource = sourceFor("baseUrl", config, flags, env) ?? "default";
54
88
  const regionSource = sourceFor("region", config, flags, env) ?? "default";
55
89
  const subdomainSource = sourceFor("subdomain", config, flags, env) ?? "default";
56
- const apiKeyOk = isPresent(config.apiKey);
90
+ const apiKey = await checkApiKey(config, services);
57
91
  const workspaceOk = isPresent(config.workspaceId);
58
92
  const baseUrl = config.baseUrl === undefined
59
93
  ? DEFAULT_CLOCKIFY_BASE_URL
@@ -65,11 +99,11 @@ async function buildDoctorReceipt(config, flags, env) {
65
99
  let baseUrlOk = true;
66
100
  if (config.region !== undefined || config.subdomain !== undefined || config.baseUrl !== undefined) {
67
101
  try {
68
- await createRoutedClient(config, offline);
102
+ await requireRoute(config);
69
103
  }
70
104
  catch (err) {
71
105
  if (config.region !== undefined || config.subdomain !== undefined) {
72
- routingError = err instanceof Error ? err.message : String(err);
106
+ routingError = messageOf(err);
73
107
  if (config.subdomain)
74
108
  routingError = routingError.replace(JSON.stringify(config.subdomain), '"<redacted>"');
75
109
  }
@@ -80,7 +114,7 @@ async function buildDoctorReceipt(config, flags, env) {
80
114
  const subdomainOk = regionOk;
81
115
  const readinessState = !nodeOk
82
116
  ? { kind: "runtime_unsupported", ok: false }
83
- : apiKeyOk && workspaceOk && regionOk && baseUrlOk
117
+ : apiKey.ok && workspaceOk && regionOk && baseUrlOk
84
118
  ? { kind: "ready_for_status", ok: true }
85
119
  : { kind: "configuration_incomplete", ok: false };
86
120
  return {
@@ -91,17 +125,9 @@ async function buildDoctorReceipt(config, flags, env) {
91
125
  ok: nodeOk,
92
126
  status: nodeOk ? "supported" : "unsupported",
93
127
  value: process.versions.node,
94
- ...(nodeOk ? {} : { recovery: "Install Node.js 22.13 or newer before using @apet97/clockify-cli-115." }),
95
- },
96
- apiKey: {
97
- ok: apiKeyOk,
98
- status: apiKeyOk ? "present" : "missing",
99
- ...(apiKeySource !== undefined ? { source: apiKeySource } : {}),
100
- ...(apiKeyOk ? { value: "configured (redacted)" } : {}),
101
- ...(apiKeyOk
102
- ? {}
103
- : { recovery: "Set CLOCKIFY_API_KEY in the process environment." }),
128
+ ...(nodeOk ? {} : { recovery: `${INSTALL_NODE} before using @apet97/clockify-cli-115.` }),
104
129
  },
130
+ apiKey,
105
131
  workspaceId: {
106
132
  ok: workspaceOk,
107
133
  status: workspaceOk ? "present" : "missing",
@@ -143,15 +169,15 @@ async function buildDoctorReceipt(config, flags, env) {
143
169
  : {}),
144
170
  },
145
171
  },
146
- next: nextSteps({ nodeOk, apiKeyOk, workspaceOk, hasBaseUrlOverride: isPresent(config.baseUrl) }),
172
+ next: nextSteps({ nodeOk, apiKey, workspaceOk, hasBaseUrlOverride: isPresent(config.baseUrl) }),
147
173
  };
148
174
  }
149
175
  function nextSteps(input) {
150
176
  const steps = [];
151
177
  if (!input.nodeOk)
152
- steps.push("Install Node.js 22.13 or newer.");
153
- if (!input.apiKeyOk)
154
- steps.push("Set CLOCKIFY_API_KEY in the process environment.");
178
+ steps.push(`${INSTALL_NODE}.`);
179
+ if (!input.apiKey.ok && input.apiKey.recovery !== undefined)
180
+ steps.push(input.apiKey.recovery);
155
181
  if (!input.workspaceOk)
156
182
  steps.push("Set CLOCKIFY_WORKSPACE_ID or pass --workspace.");
157
183
  if (input.hasBaseUrlOverride) {
@@ -163,46 +189,19 @@ function nextSteps(input) {
163
189
  }
164
190
  return steps;
165
191
  }
166
- function sourceFor(field, config, flags, env) {
167
- if (field === "apiKey") {
168
- if (isPresent(env.CLOCKIFY_API_KEY))
169
- return "env";
170
- return undefined;
171
- }
172
- if (field === "workspaceId") {
173
- if (isPresent(flags.workspace))
174
- return "flag";
175
- if (isPresent(env.CLOCKIFY_WORKSPACE_ID))
176
- return "env";
177
- if (isPresent(config.workspaceId))
178
- return "rc";
179
- return undefined;
180
- }
181
- if (field === "baseUrl") {
182
- if (isPresent(flags.baseUrl))
183
- return "flag";
184
- if (isPresent(env.CLOCKIFY_BASE_URL))
185
- return "env";
186
- if (isPresent(config.baseUrl))
187
- return "rc";
188
- return undefined;
189
- }
190
- if (field === "region") {
191
- if (isPresent(flags.region))
192
- return "flag";
193
- if (isPresent(env.CLOCKIFY_REGION))
194
- return "env";
195
- if (isPresent(config.region))
196
- return "rc";
192
+ const SOURCES = {
193
+ workspaceId: { flag: "workspace", env: "CLOCKIFY_WORKSPACE_ID" },
194
+ baseUrl: { flag: "baseUrl", env: "CLOCKIFY_BASE_URL" },
195
+ region: { flag: "region", env: "CLOCKIFY_REGION" },
196
+ subdomain: { flag: "subdomain", env: "CLOCKIFY_SUBDOMAIN" },
197
+ };
198
+ function sourceFor(field, config, flags, processEnv) {
199
+ if (!isPresent(config[field]))
197
200
  return undefined;
198
- }
199
- if (isPresent(flags.subdomain))
201
+ const { flag, env } = SOURCES[field];
202
+ if (isPresent(flags[flag]))
200
203
  return "flag";
201
- if (isPresent(env.CLOCKIFY_SUBDOMAIN))
202
- return "env";
203
- if (isPresent(config.subdomain))
204
- return "rc";
205
- return undefined;
204
+ return flags.profile === undefined && isPresent(processEnv[env]) ? "env" : "rc";
206
205
  }
207
206
  function isPresent(value) {
208
207
  return typeof value === "string" && value.trim().length > 0;
@@ -1,8 +1,7 @@
1
1
  import { UsageError } from "../failure.js";
2
2
  import { printRecords } from "../output.js";
3
- import { printReceipt } from "../receipt.js";
4
3
  import { dispatchedWrite } from "../write-outcome.js";
5
- import { clampPageSize, parseIntArg, parseTimeViewMode, promoteDateBoundary, requireCurrentUserId, resolveContext, splitList, TIME_VIEW_MODE_HELP, } from "./helpers.js";
4
+ import { clampPageSize, parseIntArg, parseTimeViewMode, printDeleted, promoteDateBoundary, requireCurrentUserId, resolveContext, splitList, TIME_VIEW_MODE_HELP, } from "./helpers.js";
6
5
  import { leafCommand } from "./leaf-command.js";
7
6
  export const registerEntriesCommand = (program, services) => {
8
7
  const entries = program.command("entries").description("Manage time entries.");
@@ -100,14 +99,12 @@ export const registerEntriesCommand = (program, services) => {
100
99
  .action(async function (id) {
101
100
  const { client, workspaceId, output } = await resolveContext(this, services);
102
101
  await dispatchedWrite(this, client.timeEntries.delete({ workspaceId, timeEntryId: id }));
103
- printReceipt({
104
- ok: true,
102
+ printDeleted(output, {
105
103
  action: "entries.delete",
106
104
  entity: "time_entry",
105
+ id,
107
106
  ids: { entryId: id },
108
- data: { id, deleted: true, message: `deleted time entry ${id}` },
109
- changed: { deleted: [{ type: "time_entry", id }] },
110
- next: [{ command: "clk115 entries list --json", reason: "Verify the entry no longer appears." }],
111
- }, output);
107
+ list: "entries list",
108
+ });
112
109
  });
113
110
  };
@@ -1,26 +1,14 @@
1
1
  import { listExpensesFiltered } from "clockify-sdk-ts-115/expense-list";
2
2
  import { expenseAmountToWire } from "clockify-sdk-ts-115/money";
3
+ import { expenseChangeFields } from "clockify-sdk-ts-115/updates";
3
4
  import { InvalidArgumentError } from "commander";
4
5
  import { UsageError } from "../failure.js";
5
- import { printNdjson, printObject, printRecords, printWarning } from "../output.js";
6
+ import { resolveFlags } from "../flags.js";
7
+ import { pickFields, printObject, printRecords, printWarning, warnUnknownFields } from "../output.js";
6
8
  import { printReceipt } from "../receipt.js";
7
9
  import { dispatchedWrite } from "../write-outcome.js";
8
- import { clampPageSize, parseFloatArg, parseIntArg, promoteDateBoundary, requireCurrentUserId, resolveContext, } from "./helpers.js";
10
+ import { clampPageSize, parseFloatArg, parseIntArg, printDeleted, printScan, promoteDateBoundary, requireCurrentUserId, resolveContext, rootProgram, } from "./helpers.js";
9
11
  import { leafCommand } from "./leaf-command.js";
10
- const EXPENSE_CHANGE_FIELDS = {
11
- amount: "AMOUNT",
12
- date: "DATE",
13
- projectId: "PROJECT",
14
- taskId: "TASK",
15
- categoryId: "CATEGORY",
16
- notes: "NOTES",
17
- billable: "BILLABLE",
18
- };
19
- function expenseChangeFields(fields) {
20
- return Object.entries(EXPENSE_CHANGE_FIELDS)
21
- .filter(([key]) => fields[key] !== undefined)
22
- .map(([, value]) => value);
23
- }
24
12
  function parseExpenseAmount(value) {
25
13
  const amount = parseFloatArg(value);
26
14
  try {
@@ -46,9 +34,13 @@ export const registerExpensesCommand = (program, services) => {
46
34
  .option("--max-pages <n>", "Maximum pages to scan (default 100, max 1000).", parseIntArg, 100)
47
35
  .option("--offset <n>", "Matching rows to skip on the first page when resuming.", (value) => value === "0" ? 0 : parseIntArg(value), 0)
48
36
  .option("--page <n>", "Page number.", parseIntArg, 1)
37
+ .option("--require-complete", "Print the rows, then exit 1 when more may be available.", false)
49
38
  .option("--start <date>", "Inclusive start bound (YYYY-MM-DD or RFC3339 with explicit Z/offset).")
50
39
  .option("--end <date>", "Inclusive end bound (YYYY-MM-DD or RFC3339 with explicit Z/offset).")
51
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
+ }
52
44
  const { client, workspaceId, output } = await resolveContext(this, services);
53
45
  let requested = false;
54
46
  const result = await listExpensesFiltered((request) => {
@@ -91,6 +83,7 @@ export const registerExpensesCommand = (program, services) => {
91
83
  for (const warning of result.warnings)
92
84
  printWarning(warning, output);
93
85
  const { meta } = result;
86
+ let gap;
94
87
  if (meta.hasMore) {
95
88
  const continuation = meta.nextPage === undefined
96
89
  ? "Reached the last supported page."
@@ -98,15 +91,19 @@ export const registerExpensesCommand = (program, services) => {
98
91
  const reason = rows.length === meta.limit
99
92
  ? `Returned the requested --limit of ${meta.limit} expenses. More rows may be available.`
100
93
  : "The --max-pages cap stopped the scan before all pages were examined. Matches may be missing.";
101
- printWarning(`${reason} ${continuation}`, output);
94
+ gap = `${reason} ${continuation}`;
102
95
  }
103
- if (opts.withMeta && output.mode === "json") {
104
- printObject({ items: rows, meta }, output);
105
- return;
106
- }
107
- printRecords(rows, output);
108
- if (opts.withMeta && output.mode === "ndjson")
109
- printNdjson({ meta });
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);
110
107
  });
111
108
  leafCommand(expenses, "create", "write")
112
109
  .requiredOption("--amount <n>", "Amount.", parseExpenseAmount)
@@ -139,11 +136,11 @@ export const registerExpensesCommand = (program, services) => {
139
136
  fields.notes = opts.notes;
140
137
  if (opts.billable !== undefined)
141
138
  fields.billable = opts.billable;
142
- const created = (await dispatchedWrite(this, client.expenses.create({
139
+ const created = await dispatchedWrite(this, client.expenses.create({
143
140
  ...fields,
144
141
  userId,
145
142
  workspaceId,
146
- })));
143
+ }));
147
144
  const data = { id: created.id ?? "" };
148
145
  printReceipt({
149
146
  ok: true,
@@ -199,13 +196,13 @@ export const registerExpensesCommand = (program, services) => {
199
196
  fields.notes = opts.notes;
200
197
  if (opts.billable !== undefined)
201
198
  fields.billable = opts.billable;
202
- const updated = (await dispatchedWrite(this, client.expenses.update({
199
+ const updated = await dispatchedWrite(this, client.expenses.update({
203
200
  ...fields,
204
201
  changeFields: expenseChangeFields(fields),
205
202
  userId: opts.user,
206
203
  expenseId: id,
207
204
  workspaceId,
208
- })));
205
+ }));
209
206
  const data = { id: updated.id ?? id };
210
207
  printReceipt({
211
208
  ok: true,
@@ -229,19 +226,12 @@ export const registerExpensesCommand = (program, services) => {
229
226
  .action(async function (id) {
230
227
  const { client, workspaceId, output } = await resolveContext(this, services);
231
228
  await dispatchedWrite(this, client.expenses.delete({ workspaceId, expenseId: id }));
232
- printReceipt({
233
- ok: true,
229
+ printDeleted(output, {
234
230
  action: "expenses.delete",
235
231
  entity: "expense",
232
+ id,
236
233
  ids: { expenseId: id },
237
- data: { id, deleted: true, message: `deleted expense ${id}` },
238
- changed: { deleted: [{ type: "expense", id }] },
239
- next: [
240
- {
241
- command: "clk115 expenses list --json",
242
- reason: "Verify the expense no longer appears.",
243
- },
244
- ],
245
- }, output);
234
+ list: "expenses list",
235
+ });
246
236
  });
247
237
  };
@@ -1,8 +1,13 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { parseWeeklyDateTime } from "clockify-sdk-ts-115/dates";
1
3
  import { entityId } from "clockify-sdk-ts-115/operation-receipt";
2
4
  import { InvalidArgumentError } from "commander";
3
5
  import { requireWorkspaceId } from "../config.js";
4
6
  import { UsageError } from "../failure.js";
5
7
  import { globalFlags, resolveFlags } from "../flags.js";
8
+ import { printWarning } from "../output.js";
9
+ import { printReceipt } from "../receipt.js";
10
+ import { readStdin } from "../stdin.js";
6
11
  function parseStrictNumber(value) {
7
12
  const trimmed = value.trim();
8
13
  if (trimmed === "" || /^[+-]?0[xXoObB]/.test(trimmed)) {
@@ -52,39 +57,51 @@ export function splitList(value) {
52
57
  .map((s) => s.trim())
53
58
  .filter((s) => s.length > 0);
54
59
  }
55
- const BARE_DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
56
- const RFC3339_TIMESTAMP_PATTERN = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|[+-](\d{2}):(\d{2}))$/;
57
- function hasValidCalendarDate(yearText, monthText, dayText) {
58
- const year = Number(yearText);
59
- const month = Number(monthText);
60
- const day = Number(dayText);
61
- const probe = new Date(0);
62
- probe.setUTCFullYear(year, month - 1, day);
63
- probe.setUTCHours(0, 0, 0, 0);
64
- return (probe.getUTCFullYear() === year &&
65
- probe.getUTCMonth() === month - 1 &&
66
- probe.getUTCDate() === day);
60
+ export function collect(value, previous) {
61
+ return [...previous, value];
67
62
  }
63
+ export function parsePair(value, flag) {
64
+ const index = value.indexOf("=");
65
+ if (index <= 0) {
66
+ throw new UsageError(`${flag} expected key=value, received "${value}".`);
67
+ }
68
+ const key = value.slice(0, index).trim();
69
+ if (!key) {
70
+ throw new UsageError(`${flag} expected a non-empty key in "${value}".`);
71
+ }
72
+ return [key, value.slice(index + 1)];
73
+ }
74
+ export async function readTextInput(value, flag) {
75
+ if (value === undefined || (value !== "-" && !value.startsWith("@")))
76
+ return value;
77
+ try {
78
+ return value === "-" ? await readStdin() : readFileSync(value.slice(1), "utf8");
79
+ }
80
+ catch (err) {
81
+ const detail = err instanceof Error ? err.message : String(err);
82
+ throw new UsageError(`${flag} ${JSON.stringify(value)} could not be read: ${detail}; provide a readable JSON file path or pipe the body on stdin`);
83
+ }
84
+ }
85
+ export function parseJson(text, flag, alternative) {
86
+ try {
87
+ return JSON.parse(text);
88
+ }
89
+ catch (err) {
90
+ const detail = err instanceof Error ? err.message : String(err);
91
+ throw new UsageError(`${flag} is not valid JSON (${detail}); provide valid JSON${alternative === undefined ? "." : `, or ${alternative}.`}`);
92
+ }
93
+ }
94
+ const BARE_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
95
+ const RFC3339_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-](\d{2}):(\d{2}))$/;
68
96
  function isRfc3339Timestamp(value) {
69
97
  const match = RFC3339_TIMESTAMP_PATTERN.exec(value);
70
- if (match === null || !hasValidCalendarDate(match[1], match[2], match[3])) {
71
- return false;
72
- }
73
- const hour = Number(match[4]);
74
- const minute = Number(match[5]);
75
- const second = Number(match[6]);
76
- const offsetHour = match[7] === undefined ? 0 : Number(match[7]);
77
- const offsetMinute = match[8] === undefined ? 0 : Number(match[8]);
78
- return (hour <= 23 &&
79
- minute <= 59 &&
80
- second <= 59 &&
81
- offsetHour <= 23 &&
82
- offsetMinute <= 59 &&
83
- !Number.isNaN(Date.parse(value)));
98
+ return (match !== null &&
99
+ parseWeeklyDateTime(value.slice(0, 19)) !== undefined &&
100
+ Number(match[1] ?? 0) <= 23 &&
101
+ Number(match[2] ?? 0) <= 59);
84
102
  }
85
103
  export function requireCalendarDate(value, flag) {
86
- const match = BARE_DATE_PATTERN.exec(value);
87
- if (match === null || !hasValidCalendarDate(match[1], match[2], match[3])) {
104
+ if (parseWeeklyDateTime(`${value}T00:00:00`) === undefined) {
88
105
  throw new UsageError(`--${flag} ${JSON.stringify(value)} is not a valid calendar date (YYYY-MM-DD); provide a real calendar date`);
89
106
  }
90
107
  return value;
@@ -111,6 +128,13 @@ export function promoteDateBoundary(value, flag, edge) {
111
128
  }
112
129
  return validValue;
113
130
  }
131
+ export function printScan(print, gap, requireComplete, output) {
132
+ if (gap !== undefined && !requireComplete)
133
+ printWarning(gap, output);
134
+ print();
135
+ if (gap !== undefined && requireComplete)
136
+ throw new Error(gap);
137
+ }
114
138
  export function rootProgram(cmd) {
115
139
  let current = cmd;
116
140
  while (current.parent != null) {
@@ -125,8 +149,8 @@ export async function resolveBaseContext(cmd, services, resolvedOutput) {
125
149
  const client = await services.buildClient(config, cmd);
126
150
  return { client, config, output };
127
151
  }
128
- export async function resolveContext(cmd, services) {
129
- const { client, config, output } = await resolveBaseContext(cmd, services);
152
+ export async function resolveContext(cmd, services, resolvedOutput) {
153
+ const { client, config, output } = await resolveBaseContext(cmd, services, resolvedOutput);
130
154
  return { client, workspaceId: requireWorkspaceId(config), output };
131
155
  }
132
156
  export async function requireCurrentUserId(client, hint) {
@@ -136,3 +160,17 @@ export async function requireCurrentUserId(client, hint) {
136
160
  }
137
161
  return userId;
138
162
  }
163
+ export function printDeleted(output, target) {
164
+ const { action, entity, id, ids, list } = target;
165
+ const noun = entity.replaceAll("_", " ");
166
+ const kind = entity.slice(entity.lastIndexOf("_") + 1);
167
+ printReceipt({
168
+ ok: true,
169
+ action,
170
+ entity,
171
+ ids,
172
+ data: { id, deleted: true, message: `deleted ${noun} ${id}` },
173
+ changed: { deleted: [{ type: entity, id }] },
174
+ next: [{ command: `clk115 ${list} --json`, reason: `Verify the ${kind} no longer appears.` }],
175
+ }, output);
176
+ }
@@ -12,11 +12,11 @@ export const registerInvoicesCommand = (program, services) => {
12
12
  .option("--page <n>", "Page number.", parseIntArg, 1)
13
13
  .action(async function (opts) {
14
14
  const { client, workspaceId, output } = await resolveContext(this, services);
15
- const response = (await client.invoices.list({
15
+ const response = await client.invoices.list({
16
16
  workspaceId,
17
17
  page: opts.page,
18
18
  "page-size": clampPageSize(opts.limit, 200),
19
- }));
19
+ });
20
20
  const items = response.invoices ?? [];
21
21
  const rows = items.map((raw) => {
22
22
  const inv = raw;
@@ -60,7 +60,7 @@ export const registerInvoicesCommand = (program, services) => {
60
60
  body.timeViewMode = parseTimeViewMode(opts.timeViewMode);
61
61
  const { client, workspaceId, output } = await resolveContext(this, services);
62
62
  const req = { workspaceId, body };
63
- const created = (await dispatchedWrite(this, client.invoices.create(req)));
63
+ const created = await dispatchedWrite(this, client.invoices.create(req));
64
64
  const data = {
65
65
  id: created.id ?? "",
66
66
  number: created.number ?? "",
@@ -1,5 +1,12 @@
1
1
  const commandRisks = new WeakMap();
2
+ const declaredMutations = new WeakMap();
3
+ export function declareMutation(command, mutates) {
4
+ declaredMutations.set(command, mutates);
5
+ }
2
6
  export function isMutationCommand(command) {
7
+ const declared = declaredMutations.get(command);
8
+ if (declared !== undefined)
9
+ return declared;
3
10
  if (command.name() === "api") {
4
11
  const method = command.args[0]?.toUpperCase();
5
12
  return method !== undefined && ["POST", "PUT", "PATCH", "DELETE"].includes(method);
@@ -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
+ };