@apet97/clockify-cli-115 5.0.3 → 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 +73 -23
  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
@@ -1,4 +1,6 @@
1
+ import { UsageError } from "../failure.js";
1
2
  import { printReceipt } from "../receipt.js";
3
+ import { dispatchedWrite } from "../write-outcome.js";
2
4
  import { requireRfc3339Timestamp, resolveContext } from "./helpers.js";
3
5
  import { leafCommand } from "./leaf-command.js";
4
6
  const PERIODS = ["WEEKLY", "SEMI_MONTHLY", "MONTHLY"];
@@ -8,7 +10,7 @@ function requireEnum(value, allowed, flag) {
8
10
  const upper = value.toUpperCase();
9
11
  const match = allowed.find((candidate) => candidate === upper);
10
12
  if (!match) {
11
- throw new Error(`--${flag} must be one of: ${allowed.join(", ")} (got ${JSON.stringify(value)}).`);
13
+ throw new UsageError(`--${flag} must be one of: ${allowed.join(", ")} (got ${JSON.stringify(value)}).`);
12
14
  }
13
15
  return match;
14
16
  }
@@ -32,17 +34,17 @@ export const registerApprovalsCommand = (program, services) => {
32
34
  .action(async function (opts) {
33
35
  const type = requireEnum(opts.type, SELF_TYPES, "type");
34
36
  const periodStart = requireRfc3339Timestamp(opts.periodStart, "period-start");
35
- const { client, workspaceId, output } = await resolveContext(this, services);
36
37
  const body = {
37
38
  periodStart,
38
39
  };
39
40
  if (opts.period)
40
41
  body.period = requireEnum(opts.period, PERIODS, "period");
41
- const created = await client.approvals.submitWithType({
42
+ const { client, workspaceId, output } = await resolveContext(this, services);
43
+ const created = await dispatchedWrite(this, client.approvals.submitWithType({
42
44
  workspaceId,
43
45
  approvalRequestId: type,
44
46
  body,
45
- });
47
+ }));
46
48
  const data = approvalReceiptData(created);
47
49
  printReceipt({
48
50
  ok: true,
@@ -71,18 +73,18 @@ export const registerApprovalsCommand = (program, services) => {
71
73
  .action(async function (opts) {
72
74
  const type = requireEnum(opts.type, OTHER_TYPES, "type");
73
75
  const periodStart = requireRfc3339Timestamp(opts.periodStart, "period-start");
74
- const { client, workspaceId, output } = await resolveContext(this, services);
75
76
  const body = {
76
77
  periodStart,
77
78
  };
78
79
  if (opts.period)
79
80
  body.period = requireEnum(opts.period, PERIODS, "period");
80
- const created = await client.approvals.submitForUserWithType({
81
+ const { client, workspaceId, output } = await resolveContext(this, services);
82
+ const created = await dispatchedWrite(this, client.approvals.submitForUserWithType({
81
83
  workspaceId,
82
84
  userId: opts.user,
83
85
  type,
84
86
  body,
85
- });
87
+ }));
86
88
  const data = approvalReceiptData(created);
87
89
  printReceipt({
88
90
  ok: true,
@@ -1,4 +1,5 @@
1
1
  import { AUDIT_LOG_ACTIONS, } from "clockify-sdk-ts-115/requests";
2
+ import { UsageError } from "../failure.js";
2
3
  import { printRecords } from "../output.js";
3
4
  import { clampPageSize, parseIntArg, promoteDateBoundary, resolveContext, splitList, } from "./helpers.js";
4
5
  import { leafCommand } from "./leaf-command.js";
@@ -7,7 +8,7 @@ export const registerAuditLogCommand = (program, services) => {
7
8
  leafCommand(audit, "search", "read")
8
9
  .description("Search the workspace audit log.")
9
10
  .addHelpText("after", "\nExamples:\n" +
10
- " $ clk115 audit-log search --start 2026-06-01 --end 2026-06-30\n")
11
+ " $ clk115 audit-log search --actions CREATE_PROJECT --start 2026-06-01 --end 2026-06-30\n")
11
12
  .requiredOption("--start <date>", "Window start (YYYY-MM-DD or RFC3339, e.g. 2026-05-01T00:00:00Z).")
12
13
  .requiredOption("--end <date>", "Window end (YYYY-MM-DD or RFC3339); the server caps the window at 31 days.")
13
14
  .requiredOption("--actions <list>", "Comma-separated action names (e.g. CREATE_PROJECT,UPDATE_PROJECT).")
@@ -16,29 +17,31 @@ export const registerAuditLogCommand = (program, services) => {
16
17
  .option("--page <n>", "Page number.", parseIntArg, 1)
17
18
  .option("--limit <n>", "Items per page (default 50, max 50 — the audit-log server caps page size).", parseIntArg, 50)
18
19
  .action(async function (opts) {
19
- const { client, workspaceId, output } = await resolveContext(this, services);
20
20
  const actions = splitList(opts.actions).map((action) => action.toUpperCase());
21
21
  if (actions.length === 0) {
22
- throw new Error("--actions must include at least one action name");
22
+ throw new UsageError("--actions must include at least one action name");
23
23
  }
24
24
  const knownActions = new Set(AUDIT_LOG_ACTIONS);
25
25
  const invalidActions = actions.filter((action) => !knownActions.has(action));
26
26
  if (invalidActions.length > 0) {
27
- throw new Error(`Unknown audit action(s): ${invalidActions.join(", ")}; provide known audit action names such as CREATE_PROJECT or UPDATE_PROJECT`);
27
+ throw new UsageError(`Unknown audit action(s): ${invalidActions.join(", ")}; provide known audit action names such as CREATE_PROJECT or UPDATE_PROJECT`);
28
28
  }
29
29
  const authorIds = opts.authors ? splitList(opts.authors) : [];
30
30
  const mode = String(opts.authorsMode).toUpperCase();
31
31
  if (mode !== "CONTAINS" && mode !== "DOES_NOT_CONTAIN") {
32
- throw new Error(`--authors-mode must be CONTAINS or DOES_NOT_CONTAIN (got "${String(opts.authorsMode)}").`);
32
+ throw new UsageError(`--authors-mode must be CONTAINS or DOES_NOT_CONTAIN (got "${String(opts.authorsMode)}").`);
33
33
  }
34
34
  const authors = {
35
35
  authorIds,
36
36
  contains: mode,
37
37
  };
38
+ const start = promoteDateBoundary(opts.start, "start", "start");
39
+ const end = promoteDateBoundary(opts.end, "end", "end");
40
+ const { client, workspaceId, output } = await resolveContext(this, services);
38
41
  const req = {
39
42
  workspaceId,
40
- start: promoteDateBoundary(opts.start, "start", "start"),
41
- end: promoteDateBoundary(opts.end, "end", "end"),
43
+ start,
44
+ end,
42
45
  actions: actions,
43
46
  authors,
44
47
  page: opts.page,
@@ -52,7 +55,7 @@ export const registerAuditLogCommand = (program, services) => {
52
55
  id: e.id ?? "",
53
56
  timestamp: e.timestamp ?? "",
54
57
  action: e.action ?? "",
55
- author: e.authorName ?? e.authorId ?? "",
58
+ author: e.userName ?? e.userEmail ?? e.userId ?? e.authorName ?? e.authorId ?? "",
56
59
  entityType: e.entityType ?? "",
57
60
  entityId: e.entityId ?? "",
58
61
  };
@@ -1,5 +1,7 @@
1
+ import { UsageError } from "../failure.js";
1
2
  import { printRecords } from "../output.js";
2
3
  import { printReceipt } from "../receipt.js";
4
+ import { dispatchedWrite } from "../write-outcome.js";
3
5
  import { parseSignedFloatArg, requireCalendarDate, resolveContext, splitList, } from "./helpers.js";
4
6
  import { leafCommand } from "./leaf-command.js";
5
7
  function dateRange(opts) {
@@ -51,10 +53,10 @@ export function registerBalanceAssignmentCommands(timeoff, services) {
51
53
  .option("--end <date>", "Balance window end (YYYY-MM-DD).")
52
54
  .action(async function (opts) {
53
55
  const range = dateRange(opts);
54
- const { client, workspaceId, output } = await resolveContext(this, services);
55
56
  const userIds = splitList(opts.user);
56
57
  if (userIds.length === 0)
57
- throw new Error("--user needs at least one user ID");
58
+ throw new UsageError("--user needs at least one user ID");
59
+ const { client, workspaceId, output } = await resolveContext(this, services);
58
60
  const body = {
59
61
  balance: opts.balance,
60
62
  policyId: opts.policy,
@@ -64,7 +66,7 @@ export function registerBalanceAssignmentCommands(timeoff, services) {
64
66
  body.note = opts.note;
65
67
  if (range !== undefined)
66
68
  body.dateRange = range;
67
- await client.balanceAssignment.createBalanceAssignment({ workspaceId, body });
69
+ await dispatchedWrite(this, client.balanceAssignment.createBalanceAssignment({ workspaceId, body }));
68
70
  printReceipt({
69
71
  ok: true,
70
72
  action: "timeoff.balance-assignment.create",
@@ -102,13 +104,13 @@ export function registerBalanceAssignmentCommands(timeoff, services) {
102
104
  body.note = opts.note;
103
105
  if (range !== undefined)
104
106
  body.dateRange = range;
105
- await client.balanceAssignment.updateBalanceAssignment({
107
+ await dispatchedWrite(this, client.balanceAssignment.updateBalanceAssignment({
106
108
  workspaceId,
107
109
  userId: opts.user,
108
110
  policyId: opts.policy,
109
111
  balanceAssignmentId: opts.id,
110
112
  body,
111
- });
113
+ }));
112
114
  printReceipt({
113
115
  ok: true,
114
116
  action: "timeoff.balance-assignment.update",
@@ -135,16 +137,16 @@ export function registerBalanceAssignmentCommands(timeoff, services) {
135
137
  .requiredOption("--note <text>", "Note explaining the deletion. The API rejects an empty note.")
136
138
  .action(async function (opts) {
137
139
  if (typeof opts.note !== "string" || opts.note.trim() === "") {
138
- throw new Error("--note must be a non-empty note: the API rejects an empty note on balance-assignment delete.");
140
+ throw new UsageError("--note must be a non-empty note: the API rejects an empty note on balance-assignment delete.");
139
141
  }
140
142
  const { client, workspaceId, output } = await resolveContext(this, services);
141
- await client.balanceAssignment.deleteBalanceAssignment({
143
+ await dispatchedWrite(this, client.balanceAssignment.deleteBalanceAssignment({
142
144
  workspaceId,
143
145
  userId: opts.user,
144
146
  policyId: opts.policy,
145
147
  balanceAssignmentId: opts.id,
146
148
  body: { note: opts.note },
147
- });
149
+ }));
148
150
  printReceipt({
149
151
  ok: true,
150
152
  action: "timeoff.balance-assignment.delete",
@@ -1,6 +1,8 @@
1
1
  import { archiveThenDeleteClient } from "clockify-sdk-ts-115/ensure";
2
+ import { PartialDeleteError, UsageError } from "../failure.js";
2
3
  import { printObject, printRecords } from "../output.js";
3
4
  import { printReceipt } from "../receipt.js";
5
+ import { dispatchedWrite } from "../write-outcome.js";
4
6
  import { clampPageSize, parseIntArg, resolveContext } from "./helpers.js";
5
7
  import { leafCommand } from "./leaf-command.js";
6
8
  function quoteShellArgument(value) {
@@ -98,7 +100,7 @@ export const registerClientsCommand = (program, services) => {
98
100
  workspaceId,
99
101
  body: { name, ...(opts.note !== undefined ? { note: opts.note } : {}) },
100
102
  };
101
- const created = (await client.clients.create(req));
103
+ const created = (await dispatchedWrite(this, client.clients.create(req)));
102
104
  const data = { id: created.id ?? "", name: created.name ?? "" };
103
105
  printReceipt({
104
106
  ok: true,
@@ -136,14 +138,14 @@ export const registerClientsCommand = (program, services) => {
136
138
  " $ clk115 clients update client_123 --name \"New name\"\n" +
137
139
  " $ clk115 clients update client_123 --archived\n")
138
140
  .action(async function (id, opts) {
139
- const { client, workspaceId, output } = await resolveContext(this, services);
140
141
  const hasChanges = opts.name !== undefined ||
141
142
  opts.note !== undefined ||
142
143
  opts.address !== undefined ||
143
144
  opts.archived !== undefined;
144
145
  if (!hasChanges) {
145
- throw new Error("clients.update needs a change: provide at least one client field.");
146
+ throw new UsageError("clients.update needs a change: provide at least one client field.");
146
147
  }
148
+ const { client, workspaceId, output } = await resolveContext(this, services);
147
149
  const current = (await client.clients.get({
148
150
  workspaceId,
149
151
  clientId: id,
@@ -170,7 +172,7 @@ export const registerClientsCommand = (program, services) => {
170
172
  clientId: id,
171
173
  body,
172
174
  };
173
- const updated = (await client.clients.update(req));
175
+ const updated = (await dispatchedWrite(this, client.clients.update(req)));
174
176
  const data = { id: updated.id ?? id, name: updated.name ?? body.name };
175
177
  printReceipt({
176
178
  ok: true,
@@ -193,20 +195,27 @@ export const registerClientsCommand = (program, services) => {
193
195
  .addHelpText("after", "\nExamples:\n" + " $ clk115 clients delete client_123\n")
194
196
  .action(async function (id) {
195
197
  const { client, workspaceId, output } = await resolveContext(this, services);
198
+ let archivedByCall = false;
196
199
  await archiveThenDeleteClient({
197
200
  workspaceId,
198
201
  id,
199
202
  adapter: {
200
203
  getCurrent: ({ workspaceId: currentWorkspaceId, id: clientId }) => client.clients.get({ workspaceId: currentWorkspaceId, clientId }),
201
204
  archive: async ({ workspaceId: currentWorkspaceId, id: clientId, current }) => {
202
- await client.clients.update({
205
+ await dispatchedWrite(this, client.clients.update({
203
206
  workspaceId: currentWorkspaceId,
204
207
  clientId,
205
208
  body: reconstructClientBody({ ...current, archived: true }),
206
- });
209
+ }));
210
+ archivedByCall = true;
207
211
  },
208
212
  delete: async ({ workspaceId: currentWorkspaceId, id: clientId }) => {
209
- await client.clients.delete({ workspaceId: currentWorkspaceId, clientId });
213
+ try {
214
+ await dispatchedWrite(this, client.clients.delete({ workspaceId: currentWorkspaceId, clientId }));
215
+ }
216
+ catch (cause) {
217
+ throw new PartialDeleteError(cause, "archived", `clk115 clients get ${id} --json`, archivedByCall ? "archived_by_call" : "already_archived");
218
+ }
210
219
  },
211
220
  },
212
221
  });
@@ -1,6 +1,5 @@
1
- import { classifyClockifyBaseUrl } from "clockify-sdk-ts-115/create-client";
2
- import { buildRoutingOptions } from "../client.js";
3
- import { globalFlags, resolveFlags } from "../index.js";
1
+ import { createRoutedClient } from "../client.js";
2
+ import { globalFlags, resolveFlags } from "../flags.js";
4
3
  import { printObject, printRecords } from "../output.js";
5
4
  import { rootProgram } from "./helpers.js";
6
5
  import { leafCommand } from "./leaf-command.js";
@@ -11,12 +10,12 @@ export const registerDoctorCommand = (program, services) => {
11
10
  .addHelpText("after", "\nExamples:\n" +
12
11
  " $ clk115 doctor\n" +
13
12
  " $ clk115 doctor --json\n")
14
- .action(function () {
13
+ .action(async function () {
15
14
  const root = rootProgram(this);
16
15
  const flags = globalFlags(root);
17
- const config = services.loadConfig(flags);
18
16
  const output = resolveFlags(root);
19
- const receipt = buildDoctorReceipt(config, flags, process.env);
17
+ const config = services.loadConfig(flags);
18
+ const receipt = await buildDoctorReceipt(config, flags, process.env);
20
19
  if (output.mode !== "table") {
21
20
  printObject(receipt, output);
22
21
  return;
@@ -34,7 +33,17 @@ export const registerDoctorCommand = (program, services) => {
34
33
  console.log(step);
35
34
  });
36
35
  };
37
- function buildDoctorReceipt(config, flags, env) {
36
+ const offline = () => { throw new Error("Doctor is offline"); };
37
+ async function acceptsBaseUrl(baseUrl) {
38
+ try {
39
+ await createRoutedClient({ baseUrl }, offline);
40
+ return true;
41
+ }
42
+ catch {
43
+ return false;
44
+ }
45
+ }
46
+ async function buildDoctorReceipt(config, flags, env) {
38
47
  const [nodeMajor = 0, nodeMinor = 0] = process.versions.node
39
48
  .split(".")
40
49
  .map((part) => Number.parseInt(part, 10) || 0);
@@ -46,29 +55,37 @@ function buildDoctorReceipt(config, flags, env) {
46
55
  const subdomainSource = sourceFor("subdomain", config, flags, env) ?? "default";
47
56
  const apiKeyOk = isPresent(config.apiKey);
48
57
  const workspaceOk = isPresent(config.workspaceId);
49
- const baseUrl = config.baseUrl ?? DEFAULT_CLOCKIFY_BASE_URL;
50
- const baseUrlClass = config.baseUrl ? classifyClockifyBaseUrl(baseUrl) : undefined;
58
+ const baseUrl = config.baseUrl === undefined
59
+ ? DEFAULT_CLOCKIFY_BASE_URL
60
+ : (await import("clockify-sdk-ts-115/diagnostics")).clockifyDiagnostics({
61
+ baseUrl: config.baseUrl,
62
+ env: {},
63
+ }).checks.baseUrl.value;
51
64
  let routingError;
52
- if (isPresent(config.region) || isPresent(config.subdomain)) {
65
+ let baseUrlOk = true;
66
+ if (config.region !== undefined || config.subdomain !== undefined || config.baseUrl !== undefined) {
53
67
  try {
54
- buildRoutingOptions(config.region, config.subdomain);
68
+ await createRoutedClient(config, offline);
55
69
  }
56
70
  catch (err) {
57
- routingError = err instanceof Error ? err.message : String(err);
71
+ if (config.region !== undefined || config.subdomain !== undefined) {
72
+ routingError = err instanceof Error ? err.message : String(err);
73
+ if (config.subdomain)
74
+ routingError = routingError.replace(JSON.stringify(config.subdomain), '"<redacted>"');
75
+ }
76
+ baseUrlOk = config.baseUrl === undefined || await acceptsBaseUrl(config.baseUrl);
58
77
  }
59
78
  }
60
79
  const regionOk = routingError === undefined;
61
- const subdomainOk = routingError === undefined;
62
- const baseUrlOk = baseUrlClass ? baseUrlClass.allowed : true;
63
- const configOk = apiKeyOk && workspaceOk && regionOk && baseUrlOk;
64
- const ok = nodeOk && configOk;
80
+ const subdomainOk = regionOk;
81
+ const readinessState = !nodeOk
82
+ ? { kind: "runtime_unsupported", ok: false }
83
+ : apiKeyOk && workspaceOk && regionOk && baseUrlOk
84
+ ? { kind: "ready_for_status", ok: true }
85
+ : { kind: "configuration_incomplete", ok: false };
65
86
  return {
66
- ok,
67
- readiness: !nodeOk
68
- ? "runtime_unsupported"
69
- : configOk
70
- ? "ready_for_status"
71
- : "configuration_incomplete",
87
+ ok: readinessState.ok,
88
+ readiness: readinessState.kind,
72
89
  checks: {
73
90
  node: {
74
91
  ok: nodeOk,
@@ -100,11 +117,11 @@ function buildDoctorReceipt(config, flags, env) {
100
117
  ok: baseUrlOk,
101
118
  status: config.baseUrl ? "override" : "default",
102
119
  source: baseUrlSource,
103
- value: baseUrl,
120
+ ...(baseUrl !== undefined && { value: baseUrl }),
104
121
  ...(config.baseUrl
105
122
  ? {
106
- recovery: baseUrlClass && !baseUrlClass.allowed
107
- ? `${baseUrlClass.reason ?? "Base URL is outside the Clockify host allowlist."} The client will reject it — use the default Clockify API base URL, or a loopback host for mocks/replay.`
123
+ recovery: !baseUrlOk
124
+ ? "The client will reject it. Use a Clockify API URL or loopback URL without credentials, a query or a fragment."
108
125
  : "Use the default Clockify API base URL for real work; keep overrides for mocks or replay.",
109
126
  }
110
127
  : {}),
@@ -1,7 +1,8 @@
1
- import { entityId } from "clockify-sdk-ts-115/operation-receipt";
1
+ import { UsageError } from "../failure.js";
2
2
  import { printRecords } from "../output.js";
3
3
  import { printReceipt } from "../receipt.js";
4
- import { clampPageSize, parseIntArg, promoteDateBoundary, resolveContext, splitList, } from "./helpers.js";
4
+ import { dispatchedWrite } from "../write-outcome.js";
5
+ import { clampPageSize, parseIntArg, parseTimeViewMode, promoteDateBoundary, requireCurrentUserId, resolveContext, splitList, TIME_VIEW_MODE_HELP, } from "./helpers.js";
5
6
  import { leafCommand } from "./leaf-command.js";
6
7
  export const registerEntriesCommand = (program, services) => {
7
8
  const entries = program.command("entries").description("Manage time entries.");
@@ -13,27 +14,36 @@ export const registerEntriesCommand = (program, services) => {
13
14
  .option("--limit <n>", "Items per page (default 25, max 200).", parseIntArg, 25)
14
15
  .option("--page <n>", "Page number (default 1).", parseIntArg, 1)
15
16
  .option("--from <date>", "Inclusive start bound (YYYY-MM-DD or RFC3339).")
16
- .option("--to <date>", "Inclusive end bound (YYYY-MM-DD or RFC3339).")
17
+ .option("--to <date>", "Include this calendar date (YYYY-MM-DD), or exclude the RFC3339 instant itself.")
17
18
  .option("--description <text>", "Filter by description substring.")
19
+ .option("--time-view-mode <mode>", TIME_VIEW_MODE_HELP)
18
20
  .action(async function (opts) {
19
- const { client, workspaceId, output } = await resolveContext(this, services);
20
- const user = await client.users.getCurrentUser();
21
- const userId = entityId(user);
22
- if (!userId) {
23
- throw new Error("could not determine user ID");
21
+ const start = opts.from ? promoteDateBoundary(opts.from, "from", "start") : undefined;
22
+ let end = opts.to ? promoteDateBoundary(opts.to, "to", "start") : undefined;
23
+ if (end && end !== opts.to) {
24
+ const midnight = new Date(end);
25
+ midnight.setUTCDate(midnight.getUTCDate() + 1);
26
+ end = midnight.getUTCFullYear() > 9999
27
+ ? promoteDateBoundary(opts.to, "to", "end")
28
+ : midnight.toISOString().replace(".000Z", "Z");
24
29
  }
30
+ const timeViewMode = opts.timeViewMode === undefined ? undefined : parseTimeViewMode(opts.timeViewMode);
31
+ const { client, workspaceId, output } = await resolveContext(this, services);
32
+ const userId = await requireCurrentUserId(client);
25
33
  const req = {
26
34
  workspaceId,
27
35
  userId,
28
36
  page: opts.page,
29
37
  "page-size": clampPageSize(opts.limit, 200),
30
38
  };
31
- if (opts.from)
32
- req.start = promoteDateBoundary(opts.from, "from", "start");
33
- if (opts.to)
34
- req.end = promoteDateBoundary(opts.to, "to", "end");
39
+ if (start !== undefined)
40
+ req.start = start;
41
+ if (end !== undefined)
42
+ req.end = end;
35
43
  if (opts.description)
36
44
  req.description = opts.description;
45
+ if (timeViewMode !== undefined)
46
+ req.timeViewMode = timeViewMode;
37
47
  const items = await client.timeEntries.listForUser(req);
38
48
  const rows = items.map((raw) => {
39
49
  const e = raw;
@@ -60,7 +70,7 @@ export const registerEntriesCommand = (program, services) => {
60
70
  .action(async function (opts) {
61
71
  const timeEntryIds = splitList(opts.ids);
62
72
  if (timeEntryIds.length === 0)
63
- throw new Error("--ids needs at least one time-entry ID");
73
+ throw new UsageError("--ids needs at least one time-entry ID");
64
74
  const { client, workspaceId, output } = await resolveContext(this, services);
65
75
  const items = await client.timeEntries.getMultipleTimeEntries({
66
76
  workspaceId,
@@ -71,6 +81,11 @@ export const registerEntriesCommand = (program, services) => {
71
81
  description: entry.description ?? "",
72
82
  project: entry.projectId ?? "",
73
83
  task: entry.taskId ?? "",
84
+ ...(opts.hydrated === true && {
85
+ project: entry.project ?? entry.projectId ?? null,
86
+ task: entry.task ?? entry.taskId ?? null,
87
+ tags: entry.tags ?? entry.tagIds ?? [],
88
+ }),
74
89
  billable: entry.billable === true,
75
90
  start: entry.timeInterval?.start ?? "",
76
91
  end: entry.timeInterval?.end ?? "",
@@ -84,7 +99,7 @@ export const registerEntriesCommand = (program, services) => {
84
99
  .addHelpText("after", "\nExamples:\n" + " $ clk115 entries delete entry_123\n")
85
100
  .action(async function (id) {
86
101
  const { client, workspaceId, output } = await resolveContext(this, services);
87
- await client.timeEntries.delete({ workspaceId, timeEntryId: id });
102
+ await dispatchedWrite(this, client.timeEntries.delete({ workspaceId, timeEntryId: id }));
88
103
  printReceipt({
89
104
  ok: true,
90
105
  action: "entries.delete",
@@ -1,8 +1,11 @@
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 { InvalidArgumentError } from "commander";
4
+ import { UsageError } from "../failure.js";
5
+ import { printNdjson, printObject, printRecords, printWarning } from "../output.js";
4
6
  import { printReceipt } from "../receipt.js";
5
- import { clampPageSize, parseFloatArg, parseIntArg, promoteDateBoundary, resolveContext, } from "./helpers.js";
7
+ import { dispatchedWrite } from "../write-outcome.js";
8
+ import { clampPageSize, parseFloatArg, parseIntArg, promoteDateBoundary, requireCurrentUserId, resolveContext, } from "./helpers.js";
6
9
  import { leafCommand } from "./leaf-command.js";
7
10
  const EXPENSE_CHANGE_FIELDS = {
8
11
  amount: "AMOUNT",
@@ -18,28 +21,51 @@ function expenseChangeFields(fields) {
18
21
  .filter(([key]) => fields[key] !== undefined)
19
22
  .map(([, value]) => value);
20
23
  }
24
+ function parseExpenseAmount(value) {
25
+ const amount = parseFloatArg(value);
26
+ try {
27
+ return expenseAmountToWire(amount);
28
+ }
29
+ catch (cause) {
30
+ if (!(cause instanceof RangeError))
31
+ throw cause;
32
+ throw new InvalidArgumentError(`must not exceed ${Number.MAX_SAFE_INTEGER}, the largest amount that can be sent exactly.`);
33
+ }
34
+ }
21
35
  export const registerExpensesCommand = (program, services) => {
22
36
  const expenses = program.command("expenses").description("Inspect workspace expenses.");
23
37
  leafCommand(expenses, "list", "read")
24
38
  .description("List expenses in the workspace.")
25
39
  .addHelpText("after", "\nExamples:\n" +
26
40
  " $ clk115 expenses list\n" +
41
+ " $ clk115 expenses list --json --with-meta\n" +
27
42
  " $ clk115 expenses list --start 2026-06-01 --end 2026-06-30\n")
43
+ .option("--with-meta", "Include scan metadata in JSON or as the final NDJSON line.")
28
44
  .option("--limit <n>", "Total records to return (default 25, max 10000).", parseIntArg, 25)
29
45
  .option("--page-size <n>", "Records fetched per page (default 50, max 200).", parseIntArg, 50)
30
46
  .option("--max-pages <n>", "Maximum pages to scan (default 100, max 1000).", parseIntArg, 100)
47
+ .option("--offset <n>", "Matching rows to skip on the first page when resuming.", (value) => value === "0" ? 0 : parseIntArg(value), 0)
31
48
  .option("--page <n>", "Page number.", parseIntArg, 1)
32
49
  .option("--start <date>", "Inclusive start bound (YYYY-MM-DD or RFC3339 with explicit Z/offset).")
33
50
  .option("--end <date>", "Inclusive end bound (YYYY-MM-DD or RFC3339 with explicit Z/offset).")
34
51
  .action(async function (opts) {
35
52
  const { client, workspaceId, output } = await resolveContext(this, services);
36
- const result = await listExpensesFiltered(client.expenses.list.bind(client.expenses), { workspaceId }, {
53
+ let requested = false;
54
+ const result = await listExpensesFiltered((request) => {
55
+ requested = true;
56
+ return client.expenses.list(request);
57
+ }, { workspaceId }, {
37
58
  page: opts.page,
59
+ offset: opts.offset,
38
60
  pageSize: clampPageSize(opts.pageSize, 200),
39
61
  limit: opts.limit,
40
62
  maxPages: opts.maxPages,
41
63
  ...(opts.start !== undefined ? { start: opts.start } : {}),
42
64
  ...(opts.end !== undefined ? { end: opts.end } : {}),
65
+ }).catch((cause) => {
66
+ if (!requested && cause instanceof RangeError)
67
+ throw new UsageError(cause.message);
68
+ throw cause;
43
69
  });
44
70
  const rows = result.items.map((raw) => {
45
71
  const e = raw;
@@ -53,17 +79,37 @@ export const registerExpensesCommand = (program, services) => {
53
79
  date: e.date ?? "",
54
80
  category,
55
81
  projectId: e.project?.id ?? "",
56
- amount: e.total ?? e.amount ?? e.quantity ?? 0,
82
+ ...(output.mode === "table" ? { amount: e.total ?? "—" } : {
83
+ amount: e.total ?? e.amount ?? e.quantity ?? 0,
84
+ totalMinor: e.total ?? null,
85
+ amountSource: e.total == null ? "unavailable" : "total",
86
+ }),
57
87
  currency: e.currency ?? "",
58
88
  billable: e.billable === true,
59
89
  };
60
90
  });
61
91
  for (const warning of result.warnings)
62
- console.error(`WARN ${warning}`);
92
+ printWarning(warning, output);
93
+ const { meta } = result;
94
+ if (meta.hasMore) {
95
+ const continuation = meta.nextPage === undefined
96
+ ? "Reached the last supported page."
97
+ : `Keep the same filters and page size and append --page ${meta.nextPage} --offset ${meta.nextOffset ?? 0} --max-pages ${meta.nextMaxPages}`;
98
+ const reason = rows.length === meta.limit
99
+ ? `Returned the requested --limit of ${meta.limit} expenses. More rows may be available.`
100
+ : "The --max-pages cap stopped the scan before all pages were examined. Matches may be missing.";
101
+ printWarning(`${reason} ${continuation}`, output);
102
+ }
103
+ if (opts.withMeta && output.mode === "json") {
104
+ printObject({ items: rows, meta }, output);
105
+ return;
106
+ }
63
107
  printRecords(rows, output);
108
+ if (opts.withMeta && output.mode === "ndjson")
109
+ printNdjson({ meta });
64
110
  });
65
111
  leafCommand(expenses, "create", "write")
66
- .requiredOption("--amount <n>", "Amount.", parseFloatArg)
112
+ .requiredOption("--amount <n>", "Amount.", parseExpenseAmount)
67
113
  .requiredOption("--category <id>", "Expense category ID.")
68
114
  .requiredOption("--date <date>", "Expense date (YYYY-MM-DD or ISO).")
69
115
  .option("--user <id>", "Owning user ID (defaults to the API-key owner).")
@@ -76,18 +122,14 @@ export const registerExpensesCommand = (program, services) => {
76
122
  .addHelpText("after", "\nExamples:\n" +
77
123
  " $ clk115 expenses create --amount 42.50 --category cat_123 --date 2026-06-01\n")
78
124
  .action(async function (opts) {
125
+ const date = promoteDateBoundary(opts.date, "date", "start");
79
126
  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
- }
127
+ const userId = opts.user ||
128
+ (await requireCurrentUserId(client, "pass --user"));
87
129
  const fields = {
88
130
  amount: opts.amount,
89
131
  categoryId: opts.category,
90
- date: promoteDateBoundary(opts.date, "date", "start"),
132
+ date,
91
133
  };
92
134
  if (opts.project)
93
135
  fields.projectId = opts.project;
@@ -97,11 +139,11 @@ export const registerExpensesCommand = (program, services) => {
97
139
  fields.notes = opts.notes;
98
140
  if (opts.billable !== undefined)
99
141
  fields.billable = opts.billable;
100
- const created = (await client.expenses.create({
142
+ const created = (await dispatchedWrite(this, client.expenses.create({
101
143
  ...fields,
102
144
  userId,
103
145
  workspaceId,
104
- }));
146
+ })));
105
147
  const data = { id: created.id ?? "" };
106
148
  printReceipt({
107
149
  ok: true,
@@ -129,7 +171,7 @@ export const registerExpensesCommand = (program, services) => {
129
171
  });
130
172
  leafCommand(expenses, "update", "write")
131
173
  .argument("<id>", "Expense ID.")
132
- .requiredOption("--amount <n>", "Amount.", parseFloatArg)
174
+ .requiredOption("--amount <n>", "Amount.", parseExpenseAmount)
133
175
  .requiredOption("--category <id>", "Expense category ID.")
134
176
  .requiredOption("--date <date>", "Expense date (YYYY-MM-DD or ISO).")
135
177
  .requiredOption("--user <id>", "Owning user ID.")
@@ -143,12 +185,12 @@ export const registerExpensesCommand = (program, services) => {
143
185
  " $ clk115 expenses update expense_123 --amount 50 --category cat_123 \\\n" +
144
186
  " --date 2026-06-01 --user user_123\n")
145
187
  .action(async function (id, opts) {
146
- const { client, workspaceId, output } = await resolveContext(this, services);
147
188
  const fields = {
148
189
  amount: opts.amount,
149
190
  categoryId: opts.category,
150
191
  date: promoteDateBoundary(opts.date, "date", "start"),
151
192
  };
193
+ const { client, workspaceId, output } = await resolveContext(this, services);
152
194
  if (opts.project)
153
195
  fields.projectId = opts.project;
154
196
  if (opts.task)
@@ -157,13 +199,13 @@ export const registerExpensesCommand = (program, services) => {
157
199
  fields.notes = opts.notes;
158
200
  if (opts.billable !== undefined)
159
201
  fields.billable = opts.billable;
160
- const updated = (await client.expenses.update({
202
+ const updated = (await dispatchedWrite(this, client.expenses.update({
161
203
  ...fields,
162
204
  changeFields: expenseChangeFields(fields),
163
205
  userId: opts.user,
164
206
  expenseId: id,
165
207
  workspaceId,
166
- }));
208
+ })));
167
209
  const data = { id: updated.id ?? id };
168
210
  printReceipt({
169
211
  ok: true,
@@ -186,7 +228,7 @@ export const registerExpensesCommand = (program, services) => {
186
228
  .addHelpText("after", "\nExamples:\n" + " $ clk115 expenses delete expense_123\n")
187
229
  .action(async function (id) {
188
230
  const { client, workspaceId, output } = await resolveContext(this, services);
189
- await client.expenses.delete({ workspaceId, expenseId: id });
231
+ await dispatchedWrite(this, client.expenses.delete({ workspaceId, expenseId: id }));
190
232
  printReceipt({
191
233
  ok: true,
192
234
  action: "expenses.delete",