@apet97/clockify-cli-115 0.4.0 → 0.5.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.
package/README.md CHANGED
@@ -3,8 +3,8 @@
3
3
  Command-line interface for [Clockify](https://clockify.me/), built on
4
4
  top of `clockify-sdk-ts-115`.
5
5
 
6
- Current release: `0.4.0`. Requires Node.js `>=22.13.0` and
7
- `clockify-sdk-ts-115 >=0.12.0 <1`.
6
+ Current release: `0.5.0`. Requires Node.js `>=22.13.0` and
7
+ `clockify-sdk-ts-115 >=0.13.0 <1`.
8
8
 
9
9
  Two binaries, identical behavior:
10
10
 
@@ -12,6 +12,8 @@ Two binaries, identical behavior:
12
12
  - `clk115` — short alias
13
13
 
14
14
  ```sh
15
+ npm ci && make sdk-codegen # from the repo root, once
16
+ npm run build -w clockify-sdk-ts-115 # build the workspace-linked SDK
15
17
  cd cli
16
18
  npm install
17
19
  npm run build
@@ -34,13 +36,15 @@ In precedence order (highest wins):
34
36
  2. **Environment variables:** `CLOCKIFY_API_KEY`, `CLOCKIFY_WORKSPACE_ID`,
35
37
  optional `CLOCKIFY_BASE_URL` for mock/replay or private gateway tests,
36
38
  optional `CLOCKIFY_REGION`/`CLOCKIFY_SUBDOMAIN` for regional routing
37
- 3. **Rc file:** `~/.clockifyrc.json` (or `clockifyrc.json` in
38
- `$CLOCKIFY_HOME`)
39
+ 3. **Rc file:** `clockifyrc.json`, then `.clockifyrc.json`, both looked up in
40
+ `$CLOCKIFY_HOME` when it is set and in your home directory otherwise
39
41
 
40
42
  `--region` (`global`, `eu`, `us`, `uk`, `au`, or `developer`) selects a Clockify
41
43
  routing profile; `--subdomain` selects a workspace subdomain and requires
42
44
  `--region` to be `eu`/`us`/`uk`/`au`. Both are mutually exclusive with
43
- `--base-url`/`CLOCKIFY_BASE_URL`.
45
+ `--base-url`/`CLOCKIFY_BASE_URL`. Only the `global` profile is live-confirmed;
46
+ naming any other region is itself the acknowledgement that its route is
47
+ unproven for data residency.
44
48
 
45
49
  Rc file shape:
46
50
 
@@ -69,7 +73,8 @@ touching production credentials.
69
73
  - **`--select <path>`:** print a dot-path (e.g. `--select data.id` or
70
74
  `--select 0.name`) before emitting JSON or NDJSON.
71
75
 
72
- Errors go to stderr as `{"ok": false, "error": "..."}`; success-only
76
+ In `json` and `ndjson` modes, errors go to stderr as `{"ok": false, "error":
77
+ "...", "code": "...", "recovery": "...", "retryable": true|false}`; success-only
73
78
  commands emit `{"ok": true, "message": "..."}`. `--no-color` disables ANSI
74
79
  codes, and the CLI also auto-disables color when stdout is not a TTY.
75
80
  Successful write commands in JSON and NDJSON include receipt fields:
@@ -111,7 +116,7 @@ Legacy top-level fields such as `id` remain for simple shell scripts.
111
116
  | `clk115 webhooks list [--type type]` | List outbound webhooks. |
112
117
  | `clk115 webhooks create --name X --url U --event E [--trigger-source-type T --trigger-source ids]` | Create a webhook subscription. |
113
118
  | `clk115 webhooks delete <id>` | Delete a webhook subscription. |
114
- | `clk115 invoices list` | List invoices in the workspace. |
119
+ | `clk115 invoices list [--limit N] [--page N]` | List invoices in the workspace. |
115
120
  | `clk115 invoices create --client id --number N --currency USD --issued YYYY-MM-DD --due YYYY-MM-DD [--time-view-mode mode]` | Create an invoice draft. |
116
121
  | `clk115 expenses list [--limit N] [--page-size N] [--max-pages N] [--page N] [--start date] [--end date]` | List workspace expenses; date bounds are applied client-side across bounded pages. |
117
122
  | `clk115 expenses get <id>` | Get one expense by ID. |
@@ -120,7 +125,7 @@ Legacy top-level fields such as `id` remain for simple shell scripts.
120
125
  | `clk115 expenses delete <id>` | Delete an expense. |
121
126
  | `clk115 timeoff list [--page N] [--limit N] [--start date] [--end date] [--status APPROVED,PENDING,…] [--user ids]` | List time-off requests. |
122
127
  | `clk115 timeoff submit --policy id --start date (--end date \| --days N) [--note text] [--half-day --half-day-period FIRST_HALF\|SECOND_HALF]` | Submit a time-off request against a policy. Provide --end (HOURS-unit policies) or --days (DAYS-unit policies). |
123
- | `clk115 scheduling list [--limit N] [--page N] [--name text]` | List scheduling assignments. |
128
+ | `clk115 scheduling list --from date --to date [--limit N] [--page N] [--name text]` | List scheduling assignments. |
124
129
  | `clk115 scheduling create --user id --project id --start date --end date --hours-per-day N [--task id --note text --billable --include-non-working-days --publish]` | Create a scheduling assignment. Drafts by default; pass `--publish` to publish. |
125
130
  | `clk115 audit-log search --start RFC3339 --end RFC3339 --actions A,B,… [--authors ids --authors-mode CONTAINS\|DOES_NOT_CONTAIN --page N --limit N]` | Search the workspace audit log. Window must be ≤ 31 days. |
126
131
  | `clk115 reports summary [--period p] [--from date] [--to date] [--groups PROJECT,TASK] [--billable] [--project name\|id…] [--client name\|id…]` | Summary report totals over a date range, grouped per --groups. Read-only. |
@@ -129,8 +134,8 @@ Legacy top-level fields such as `id` remain for simple shell scripts.
129
134
  | `clk115 reports attendance [--period p] [--from date] [--to date]` | Attendance report of clock-in/out activity over a date range. Read-only. |
130
135
  | `clk115 shared-reports list` | List the workspace's shared (public-link) reports. Read-only. |
131
136
  | `clk115 shared-reports view <id> [--export-type JSON_V1\|JSON\|CSV\|XLSX\|PDF]` | View a shared report's rendered data by ID (not workspace-scoped). Read-only. |
132
- | `clk115 shared-reports create --name X --type T --filter json [--public]` | Create a shared (public-link) report. |
133
- | `clk115 shared-reports update <id> --name X --type T --filter json [--public]` | Replace a shared report by ID (full replace of name, type, and filter). |
137
+ | `clk115 shared-reports create --name X --type T --filter json [--public\|--no-public]` | Create a shared (public-link) report. |
138
+ | `clk115 shared-reports update <id> --name X --type T --filter json [--public\|--no-public]` | Replace a shared report by ID (full replace of name, type, and filter). |
134
139
  | `clk115 shared-reports delete <id>` | Delete a shared report. |
135
140
  | `clk115 users me` | Show the current authenticated user (the API-key owner). Read-only. |
136
141
  | `clk115 users list [--limit N] [--page N] [--name text]` | List members of the workspace. Read-only. |
@@ -180,7 +185,10 @@ clk115 api POST '/workspaces/{workspaceId}/tags' --body '{"name":"billable"}' --
180
185
 
181
186
  `{workspaceId}` is filled from `--workspace` or `CLOCKIFY_WORKSPACE_ID`.
182
187
  `--all` walks `page`/`page-size` until a short or empty page (bounded by
183
- `--max-pages`), and `--body` also accepts `@file` or `-` for stdin.
188
+ `--max-pages`), and `--body` also accepts `@file` or `-` for stdin. If the walk
189
+ stops because it hit `--max-pages`, the collection is incomplete and a `WARN`
190
+ line goes to **stderr**; stdout stays byte-identical either way, so pipelines
191
+ are unaffected and a script can detect truncation without parsing output.
184
192
 
185
193
  ## Shell completion
186
194
 
@@ -213,7 +221,9 @@ scripts.
213
221
 
214
222
  ```sh
215
223
  git clone https://github.com/apet97/clockify-ts-sdk
216
- cd clockify-ts-sdk/cli
224
+ cd clockify-ts-sdk && npm ci && make sdk-codegen # populate the gitignored generated SDK sources
225
+ npm run build -w clockify-sdk-ts-115 # build the workspace-linked SDK
226
+ cd cli
217
227
  npm install
218
228
  npm run dev -- status # via tsx, no build needed
219
229
  npm test # unit tests across duration / config / output / CLI contract / mock server
@@ -222,7 +232,7 @@ node dist/index.js status # smoke test (or invoke installed clk115/clockify11
222
232
  ```
223
233
 
224
234
  `clockify-sdk-ts-115` is workspace-linked for local development and is a
225
- `>=0.12.0 <1` peer dependency for published consumers.
235
+ `>=0.13.0 <1` peer dependency for published consumers.
226
236
 
227
237
  ## License
228
238
 
package/dist/client.js CHANGED
@@ -6,7 +6,7 @@ export function buildRoutingOptions(region, subdomain) {
6
6
  return undefined;
7
7
  if (subdomain !== undefined) {
8
8
  if (region === undefined || !REGIONAL_PREFIXES.includes(region)) {
9
- throw new Error(`--subdomain requires --region to be one of ${REGIONAL_PREFIXES.join(", ")} (got ${JSON.stringify(region)}).`);
9
+ throw new Error(`--subdomain requires --region (got ${JSON.stringify(region)}). Provide one of: ${REGIONAL_PREFIXES.join(", ")}.`);
10
10
  }
11
11
  return {
12
12
  profile: "subdomain",
@@ -18,7 +18,7 @@ export function buildRoutingOptions(region, subdomain) {
18
18
  if (region === "global")
19
19
  return { profile: "global" };
20
20
  if (!KNOWN_REGIONS.includes(region)) {
21
- throw new Error(`Unrecognized Clockify region ${JSON.stringify(region)}. Expected one of ${KNOWN_REGIONS.join(", ")}.`);
21
+ throw new Error(`Unrecognized Clockify region ${JSON.stringify(region)}. Provide one of ${KNOWN_REGIONS.join(", ")}.`);
22
22
  }
23
23
  return {
24
24
  profile: region,
@@ -29,7 +29,7 @@ export async function buildClient(config) {
29
29
  const apiKey = requireApiKey(config);
30
30
  const routing = buildRoutingOptions(config.region, config.subdomain);
31
31
  if (routing !== undefined && config.baseUrl !== undefined) {
32
- throw new Error("clk115: pass either --region/--subdomain or --base-url, not both -- they configure the same thing two different ways.");
32
+ throw new Error("clk115: --region/--subdomain and --base-url configure the same thing two different ways; provide only one of them.");
33
33
  }
34
34
  const { createClockifyClient } = await import("clockify-sdk-ts-115");
35
35
  if (routing !== undefined) {
@@ -1,6 +1,7 @@
1
1
  import { readFileSync } from "node:fs";
2
+ import pc from "picocolors";
2
3
  import { printJson, printNdjson } from "../output.js";
3
- import { resolveBaseContext } from "./helpers.js";
4
+ import { parseIntArg, resolveBaseContext } from "./helpers.js";
4
5
  import { leafCommand } from "./leaf-command.js";
5
6
  const METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
6
7
  export const registerApiCommand = (program, services) => {
@@ -12,14 +13,14 @@ export const registerApiCommand = (program, services) => {
12
13
  .option("-H, --header <key=value>", "Request header (repeatable).", collect, [])
13
14
  .option("--body <json|@file|->", "JSON body: inline, @file, or - for stdin.")
14
15
  .option("--all", "Walk page/page-size pagination, honoring Last-Page when present.", false)
15
- .option("--page-size <n>", "Page size for --all.", "50")
16
- .option("--max-pages <n>", "Maximum pages for --all.", "20")
16
+ .option("--page-size <n>", "Page size for --all.", parseIntArg, 50)
17
+ .option("--max-pages <n>", "Maximum pages for --all.", parseIntArg, 20)
17
18
  .option("--include-headers", "Include status and response headers in output.", false)
18
19
  .action(async function (methodArg, pathArg, options) {
19
20
  const { client, config, output } = await resolveBaseContext(this, services);
20
21
  const method = methodArg.toUpperCase();
21
22
  if (!METHODS.has(method)) {
22
- throw new Error(`Unsupported method "${methodArg}". Use GET, POST, PUT, PATCH, or DELETE.`);
23
+ throw new Error(`Unsupported method "${methodArg}". Provide one of: GET, POST, PUT, PATCH, DELETE.`);
23
24
  }
24
25
  const path = resolvePath(pathArg, config.workspaceId);
25
26
  const query = parsePairs(options.query);
@@ -28,9 +29,14 @@ export const registerApiCommand = (program, services) => {
28
29
  if (method !== "GET") {
29
30
  throw new Error("--all is only supported for GET requests.");
30
31
  }
31
- const pageSize = parsePositiveInteger(options.pageSize, "--page-size");
32
- const maxPages = parsePositiveInteger(options.maxPages, "--max-pages");
33
- const items = await fetchAllPages(client, path, query, headers, pageSize, maxPages);
32
+ if (options.includeHeaders) {
33
+ throw new Error("--include-headers is not supported with --all; each page's status and headers are consumed by the pagination walk.");
34
+ }
35
+ const { items, truncated } = await fetchAllPages(client, path, query, headers, options.pageSize, options.maxPages);
36
+ if (truncated) {
37
+ const prefix = output.color ? pc.yellow("WARN") : "WARN";
38
+ console.error(`${prefix} --all stopped at the --max-pages limit (${options.maxPages}); the results are incomplete. Re-run with a larger --max-pages.`);
39
+ }
34
40
  printApiOutput(items, output);
35
41
  return;
36
42
  }
@@ -100,23 +106,21 @@ function readBody(body) {
100
106
  if (body === undefined) {
101
107
  return undefined;
102
108
  }
103
- if (body === "-") {
104
- return readFileSync(0, "utf8");
105
- }
106
- if (body.startsWith("@")) {
107
- return readFileSync(body.slice(1), "utf8");
109
+ if (body === "-" || body.startsWith("@")) {
110
+ const source = body === "-" ? 0 : body.slice(1);
111
+ try {
112
+ return readFileSync(source, "utf8");
113
+ }
114
+ catch (err) {
115
+ const detail = err instanceof Error ? err.message : String(err);
116
+ throw new Error(`--body ${JSON.stringify(body)} could not be read: ${detail}; provide a readable JSON file path or pipe the body on stdin`);
117
+ }
108
118
  }
109
119
  return body;
110
120
  }
111
- function parsePositiveInteger(value, flag) {
112
- const parsed = Number(value);
113
- if (!Number.isInteger(parsed) || parsed <= 0) {
114
- throw new Error(`${flag} must be a positive integer.`);
115
- }
116
- return parsed;
117
- }
118
121
  async function fetchAllPages(client, path, query, headers, pageSize, maxPages) {
119
122
  const items = [];
123
+ let truncated = true;
120
124
  for (let page = 1; page <= maxPages; page += 1) {
121
125
  const pagePath = buildPath(path, { ...query, page: String(page), "page-size": String(pageSize) });
122
126
  const response = await client.fetch(pagePath, requestInit("GET", headers));
@@ -132,16 +136,18 @@ async function fetchAllPages(client, path, query, headers, pageSize, maxPages) {
132
136
  const lastPage = parseLastPageHeader(response.headers.get("Last-Page"));
133
137
  items.push(...data);
134
138
  if (lastPage === true) {
139
+ truncated = false;
135
140
  break;
136
141
  }
137
142
  if (lastPage === false) {
138
143
  continue;
139
144
  }
140
145
  if (data.length === 0 || data.length < pageSize) {
146
+ truncated = false;
141
147
  break;
142
148
  }
143
149
  }
144
- return items;
150
+ return { items, truncated };
145
151
  }
146
152
  function parseLastPageHeader(value) {
147
153
  if (value == null)
@@ -1,38 +1,42 @@
1
1
  import { AUDIT_LOG_ACTIONS, } from "clockify-sdk-ts-115/requests";
2
2
  import { printRecords } from "../output.js";
3
- import { clampPageSize, parseIntArg, resolveContext, splitList } from "./helpers.js";
3
+ import { clampPageSize, parseIntArg, promoteDateBoundary, resolveContext, splitList, } from "./helpers.js";
4
4
  import { leafCommand } from "./leaf-command.js";
5
5
  export const registerAuditLogCommand = (program, services) => {
6
6
  const audit = program.command("audit-log").description("Workspace audit log.");
7
7
  leafCommand(audit, "search", "read")
8
8
  .description("Search the workspace audit log.")
9
- .requiredOption("--start <date>", "Window start (RFC3339, e.g. 2026-05-01T00:00:00Z).")
10
- .requiredOption("--end <date>", "Window end (RFC3339).")
9
+ .requiredOption("--start <date>", "Window start (YYYY-MM-DD or RFC3339, e.g. 2026-05-01T00:00:00Z).")
10
+ .requiredOption("--end <date>", "Window end (YYYY-MM-DD or RFC3339); the server caps the window at 31 days.")
11
11
  .requiredOption("--actions <list>", "Comma-separated action names (e.g. CREATE_PROJECT,UPDATE_PROJECT).")
12
12
  .option("--authors <ids>", "Comma-separated author IDs to include. Pass SYSTEM to include system audit events.")
13
13
  .option("--authors-mode <mode>", "Author filter mode (CONTAINS|DOES_NOT_CONTAIN). Defaults to CONTAINS when authors are provided.", "CONTAINS")
14
14
  .option("--page <n>", "Page number.", parseIntArg, 1)
15
- .option("--limit <n>", "Items per page (default 50, max 200).", parseIntArg, 50)
15
+ .option("--limit <n>", "Items per page (default 50, max 50 — the audit-log server caps page size).", parseIntArg, 50)
16
16
  .action(async function (opts) {
17
17
  const { client, workspaceId, output } = await resolveContext(this, services);
18
- const actions = splitList(opts.actions);
18
+ const actions = splitList(opts.actions).map((action) => action.toUpperCase());
19
19
  if (actions.length === 0) {
20
20
  throw new Error("--actions must include at least one action name");
21
21
  }
22
22
  const knownActions = new Set(AUDIT_LOG_ACTIONS);
23
23
  const invalidActions = actions.filter((action) => !knownActions.has(action));
24
24
  if (invalidActions.length > 0) {
25
- throw new Error(`Unknown audit action(s): ${invalidActions.join(", ")}`);
25
+ throw new Error(`Unknown audit action(s): ${invalidActions.join(", ")}; provide known audit action names such as CREATE_PROJECT or UPDATE_PROJECT`);
26
26
  }
27
27
  const authorIds = opts.authors ? splitList(opts.authors) : [];
28
+ const mode = String(opts.authorsMode).toUpperCase();
29
+ if (mode !== "CONTAINS" && mode !== "DOES_NOT_CONTAIN") {
30
+ throw new Error(`--authors-mode must be CONTAINS or DOES_NOT_CONTAIN (got "${String(opts.authorsMode)}").`);
31
+ }
28
32
  const authors = {
29
33
  authorIds,
30
- contains: opts.authorsMode === "DOES_NOT_CONTAIN" ? "DOES_NOT_CONTAIN" : "CONTAINS",
34
+ contains: mode,
31
35
  };
32
36
  const req = {
33
37
  workspaceId,
34
- start: opts.start,
35
- end: opts.end,
38
+ start: promoteDateBoundary(opts.start, "start", "start"),
39
+ end: promoteDateBoundary(opts.end, "end", "end"),
36
40
  actions: actions,
37
41
  authors,
38
42
  page: opts.page,
@@ -130,7 +130,7 @@ export const registerClientsCommand = (program, services) => {
130
130
  opts.address !== undefined ||
131
131
  opts.archived !== undefined;
132
132
  if (!hasChanges) {
133
- throw new Error("clients.update requires at least one client field to change.");
133
+ throw new Error("clients.update needs a change: provide at least one client field.");
134
134
  }
135
135
  const current = (await client.clients.get({
136
136
  workspaceId,
@@ -151,7 +151,7 @@ export const registerClientsCommand = (program, services) => {
151
151
  body.archived = opts.archived;
152
152
  }
153
153
  if (!changed) {
154
- throw new Error("clients.update values are unchanged; refusing to mutate.");
154
+ throw new Error("clients.update values are unchanged; provide a different value.");
155
155
  }
156
156
  const req = {
157
157
  workspaceId,
@@ -1,7 +1,7 @@
1
1
  import { classifyClockifyBaseUrl } from "clockify-sdk-ts-115/create-client";
2
2
  import { buildRoutingOptions } from "../client.js";
3
3
  import { globalFlags, resolveFlags } from "../index.js";
4
- import { printObject } from "../output.js";
4
+ import { printObject, printRecords } from "../output.js";
5
5
  import { rootProgram } from "./helpers.js";
6
6
  import { leafCommand } from "./leaf-command.js";
7
7
  const DEFAULT_CLOCKIFY_BASE_URL = "https://api.clockify.me/api/v1";
@@ -13,12 +13,29 @@ export const registerDoctorCommand = (program, services) => {
13
13
  const flags = globalFlags(root);
14
14
  const config = services.loadConfig(flags);
15
15
  const output = resolveFlags(root);
16
- printObject(buildDoctorReceipt(config, flags, process.env), output);
16
+ const receipt = buildDoctorReceipt(config, flags, process.env);
17
+ if (output.mode !== "table") {
18
+ printObject(receipt, output);
19
+ return;
20
+ }
21
+ printRecords(Object.entries(receipt.checks).map(([check, c]) => ({
22
+ check,
23
+ ok: c.ok,
24
+ status: c.status,
25
+ source: c.source ?? "",
26
+ value: c.value ?? "",
27
+ recovery: c.recovery ?? "",
28
+ })), output);
29
+ printObject({ ok: receipt.ok, readiness: receipt.readiness }, output);
30
+ for (const step of receipt.next)
31
+ console.log(step);
17
32
  });
18
33
  };
19
34
  function buildDoctorReceipt(config, flags, env) {
20
- const nodeMajor = Number.parseInt(process.versions.node.split(".")[0] ?? "0", 10);
21
- const nodeOk = nodeMajor >= 22;
35
+ const [nodeMajor = 0, nodeMinor = 0] = process.versions.node
36
+ .split(".")
37
+ .map((part) => Number.parseInt(part, 10) || 0);
38
+ const nodeOk = nodeMajor > 22 || (nodeMajor === 22 && nodeMinor >= 13);
22
39
  const apiKeySource = sourceFor("apiKey", config, flags, env);
23
40
  const workspaceSource = sourceFor("workspaceId", config, flags, env);
24
41
  const baseUrlSource = sourceFor("baseUrl", config, flags, env) ?? "default";
@@ -9,8 +9,8 @@ export const registerEntriesCommand = (program, services) => {
9
9
  .description("List the current user's time entries.")
10
10
  .option("--limit <n>", "Items per page (default 25, max 200).", parseIntArg, 25)
11
11
  .option("--page <n>", "Page number (default 1).", parseIntArg, 1)
12
- .option("--from <date>", "ISO 8601 start cutoff (inclusive).")
13
- .option("--to <date>", "ISO 8601 end cutoff (inclusive).")
12
+ .option("--from <date>", "Inclusive start bound (YYYY-MM-DD or RFC3339).")
13
+ .option("--to <date>", "Inclusive end bound (YYYY-MM-DD or RFC3339).")
14
14
  .option("--description <text>", "Filter by description substring.")
15
15
  .action(async function (opts) {
16
16
  const { client, workspaceId, output } = await resolveContext(this, services);
@@ -28,12 +28,12 @@ export function promoteDateBoundary(value, flag, edge) {
28
28
  if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
29
29
  const probe = new Date(`${value}T00:00:00Z`);
30
30
  if (Number.isNaN(probe.getTime()) || probe.toISOString().slice(0, 10) !== value) {
31
- throw new Error(`--${flag} ${JSON.stringify(value)} is not a valid calendar date (YYYY-MM-DD)`);
31
+ throw new Error(`--${flag} ${JSON.stringify(value)} is not a valid calendar date (YYYY-MM-DD); provide a real calendar date`);
32
32
  }
33
33
  return edge === "start" ? `${value}T00:00:00Z` : `${value}T23:59:59Z`;
34
34
  }
35
35
  if (Number.isNaN(Date.parse(value))) {
36
- throw new Error(`--${flag} ${JSON.stringify(value)} is not a valid date (YYYY-MM-DD) or RFC3339 timestamp`);
36
+ 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`);
37
37
  }
38
38
  return value;
39
39
  }
@@ -1,14 +1,24 @@
1
1
  import { printRecords } from "../output.js";
2
2
  import { printReceipt } from "../receipt.js";
3
- import { resolveContext } from "./helpers.js";
3
+ import { clampPageSize, parseIntArg, promoteDateBoundary, resolveContext } from "./helpers.js";
4
4
  import { leafCommand } from "./leaf-command.js";
5
+ const TIME_VIEW_MODES = [
6
+ "TIME_SENSITIVE_VIEW",
7
+ "AGGREGATED_TIME_VIEW",
8
+ ];
5
9
  export const registerInvoicesCommand = (program, services) => {
6
10
  const invoices = program.command("invoices").description("Manage invoices.");
7
11
  leafCommand(invoices, "list", "read")
8
12
  .description("List invoices in the workspace.")
9
- .action(async function () {
13
+ .option("--limit <n>", "Items per page (default 25, max 200).", parseIntArg, 25)
14
+ .option("--page <n>", "Page number.", parseIntArg, 1)
15
+ .action(async function (opts) {
10
16
  const { client, workspaceId, output } = await resolveContext(this, services);
11
- const response = (await client.invoices.list({ workspaceId }));
17
+ const response = (await client.invoices.list({
18
+ workspaceId,
19
+ page: opts.page,
20
+ "page-size": clampPageSize(opts.limit, 200),
21
+ }));
12
22
  const items = response.invoices ?? [];
13
23
  const rows = items.map((raw) => {
14
24
  const inv = raw;
@@ -32,7 +42,7 @@ export const registerInvoicesCommand = (program, services) => {
32
42
  .requiredOption("--currency <code>", "ISO currency code (e.g. USD, EUR).")
33
43
  .requiredOption("--issued <date>", "Issued date (YYYY-MM-DD or RFC3339).")
34
44
  .requiredOption("--due <date>", "Due date (YYYY-MM-DD or RFC3339).")
35
- .option("--time-view-mode <mode>", "Time view mode (e.g. AGGREGATED_TIME_VIEW, DETAILED_TIME_VIEW).")
45
+ .option("--time-view-mode <mode>", "Time view mode: TIME_SENSITIVE_VIEW or AGGREGATED_TIME_VIEW.")
36
46
  .action(async function (opts) {
37
47
  const { client, workspaceId, output } = await resolveContext(this, services);
38
48
  const body = {
@@ -42,8 +52,13 @@ export const registerInvoicesCommand = (program, services) => {
42
52
  issuedDate: normaliseInvoiceDate(opts.issued, "issued"),
43
53
  dueDate: normaliseInvoiceDate(opts.due, "due"),
44
54
  };
45
- if (opts.timeViewMode)
46
- body.timeViewMode = opts.timeViewMode;
55
+ if (opts.timeViewMode !== undefined) {
56
+ const mode = String(opts.timeViewMode).toUpperCase();
57
+ if (!TIME_VIEW_MODES.includes(mode)) {
58
+ throw new Error(`Unknown --time-view-mode "${String(opts.timeViewMode)}". Provide one of: ${TIME_VIEW_MODES.join(", ")}.`);
59
+ }
60
+ body.timeViewMode = mode;
61
+ }
47
62
  const req = { workspaceId, body };
48
63
  const created = (await client.invoices.create(req));
49
64
  const data = {
@@ -70,11 +85,5 @@ export const registerInvoicesCommand = (program, services) => {
70
85
  });
71
86
  };
72
87
  function normaliseInvoiceDate(value, label) {
73
- if (typeof value !== "string" || value.length === 0) {
74
- throw new Error(`--${label} is required`);
75
- }
76
- if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
77
- return `${value}T00:00:00Z`;
78
- }
79
- return value;
88
+ return promoteDateBoundary(value, label, "start");
80
89
  }
@@ -31,7 +31,7 @@ export const registerLogCommand = (program, services) => {
31
31
  const endInput = opts.end ?? new Date().toISOString();
32
32
  const endMs = Date.parse(endInput);
33
33
  if (Number.isNaN(endMs)) {
34
- throw new Error(`--end ${JSON.stringify(opts.end)} is not a valid ISO 8601 timestamp`);
34
+ throw new Error(`--end ${JSON.stringify(opts.end)} is not a valid ISO 8601 timestamp; provide an RFC3339 timestamp`);
35
35
  }
36
36
  const endIso = new Date(endMs).toISOString();
37
37
  const startIso = new Date(endMs - seconds * 1000).toISOString();
@@ -98,6 +98,15 @@ export const registerProjectsCommand = (program, services) => {
98
98
  .option("--no-archived", "Unarchive the project.")
99
99
  .description("Update a project by ID.")
100
100
  .action(async function (id, opts) {
101
+ const hasChanges = Boolean(opts.name) ||
102
+ Boolean(opts.client) ||
103
+ Boolean(opts.color) ||
104
+ opts.note !== undefined ||
105
+ opts.billable !== undefined ||
106
+ opts.archived !== undefined;
107
+ if (!hasChanges) {
108
+ throw new Error("projects.update needs a change: provide at least one project field.");
109
+ }
101
110
  const { client, workspaceId, output } = await resolveContext(this, services);
102
111
  const body = {};
103
112
  if (opts.name)
@@ -11,20 +11,20 @@ function resolveRange(opts) {
11
11
  .toLowerCase()
12
12
  .replace(/[\s-]+/g, "_");
13
13
  if (!REPORT_PERIODS.includes(periodInput)) {
14
- throw new Error(`Unknown --period "${opts.period}". Use one of: ${REPORT_PERIODS.join(", ")}.`);
14
+ throw new Error(`Unknown --period "${opts.period}". Provide one of: ${REPORT_PERIODS.join(", ")}.`);
15
15
  }
16
16
  const range = resolvePeriod(now, periodInput);
17
17
  let { dateRangeStart, dateRangeEnd } = range;
18
18
  if (opts.from) {
19
19
  const start = resolveInstant(now, opts.from, "start");
20
20
  if (!start)
21
- throw new Error(`--from "${opts.from}" is not a valid date, ISO timestamp, or period.`);
21
+ throw new Error(`--from "${opts.from}" is not a valid date, ISO timestamp, or period; provide YYYY-MM-DD, an ISO timestamp, or a period name.`);
22
22
  dateRangeStart = start;
23
23
  }
24
24
  if (opts.to) {
25
25
  const end = resolveInstant(now, opts.to, "end");
26
26
  if (!end)
27
- throw new Error(`--to "${opts.to}" is not a valid date, ISO timestamp, or period.`);
27
+ throw new Error(`--to "${opts.to}" is not a valid date, ISO timestamp, or period; provide YYYY-MM-DD, an ISO timestamp, or a period name.`);
28
28
  dateRangeEnd = end;
29
29
  }
30
30
  return { dateRangeStart, dateRangeEnd };
@@ -48,25 +48,25 @@ function parseSummaryGroups(raw) {
48
48
  .map((group) => group.trim().toUpperCase())
49
49
  .filter(Boolean);
50
50
  if (groups.length === 0 || groups.length > 3) {
51
- throw new Error("--groups must contain between one and three summary groups.");
51
+ throw new Error(`--groups must contain between one and three summary groups; provide 1-3 of: ${SUMMARY_GROUPS.join(", ")}.`);
52
52
  }
53
53
  const unknown = groups.find((group) => !SUMMARY_GROUPS.includes(group));
54
54
  if (unknown) {
55
- throw new Error(`Unknown summary group: ${unknown}. Use one of: ${SUMMARY_GROUPS.join(", ")}.`);
55
+ throw new Error(`Unknown summary group: ${unknown}. Provide one of: ${SUMMARY_GROUPS.join(", ")}.`);
56
56
  }
57
57
  return groups;
58
58
  }
59
59
  function parseWeeklyGroup(raw) {
60
60
  const group = String(raw).toUpperCase();
61
61
  if (group !== "USER" && group !== "PROJECT") {
62
- throw new Error("Weekly group must be USER or PROJECT.");
62
+ throw new Error("Unknown --group for the weekly report. Provide one of: USER, PROJECT.");
63
63
  }
64
64
  return group;
65
65
  }
66
66
  function parseWeeklySubgroup(raw) {
67
67
  const subgroup = String(raw).toUpperCase();
68
68
  if (subgroup !== "TIME") {
69
- throw new Error("Weekly subgroup must be TIME.");
69
+ throw new Error("Unknown --subgroup for the weekly report. Provide one of: TIME.");
70
70
  }
71
71
  return subgroup;
72
72
  }
@@ -13,7 +13,7 @@ function asNamed(rows) {
13
13
  function pickIdByName(rows, ref, noun) {
14
14
  const match = matchByName(asNamed(rows), ref);
15
15
  if (match.kind === "many") {
16
- throw new Error(`multiple ${noun}s named ${JSON.stringify(ref)}; pass the 24-character id instead`);
16
+ throw new Error(`multiple ${noun}s named ${JSON.stringify(ref)}; provide the 24-character id instead`);
17
17
  }
18
18
  if (match.kind === "none") {
19
19
  throw new Error(`${noun} ${JSON.stringify(ref)} not found in workspace`);
@@ -55,7 +55,7 @@ export async function resolveTaskId(client, workspaceId, projectId, ref) {
55
55
  });
56
56
  const match = matchByName(asNamed(list), ref);
57
57
  if (match.kind === "many") {
58
- throw new Error(`multiple tasks named ${JSON.stringify(ref)} on project ${projectId}; pass the 24-character id`);
58
+ throw new Error(`multiple tasks named ${JSON.stringify(ref)} on project ${projectId}; provide the 24-character id`);
59
59
  }
60
60
  if (match.kind === "none") {
61
61
  throw new Error(`task ${JSON.stringify(ref)} not found on project ${projectId}`);
@@ -45,8 +45,8 @@ export const registerSchedulingCommand = (program, services) => {
45
45
  .description("Create a scheduling assignment (defaults to draft; pass --publish to publish).")
46
46
  .requiredOption("--user <id>", "User ID to assign.")
47
47
  .requiredOption("--project <id>", "Project ID.")
48
- .requiredOption("--start <date>", "Period start (YYYY-MM-DD or RFC3339).")
49
- .requiredOption("--end <date>", "Period end (YYYY-MM-DD or RFC3339).")
48
+ .requiredOption("--start <date>", "Period start (RFC3339, e.g. 2026-05-01T00:00:00Z).")
49
+ .requiredOption("--end <date>", "Period end (RFC3339, e.g. 2026-05-05T00:00:00Z).")
50
50
  .requiredOption("--hours-per-day <n>", "Daily hour load (e.g. 6).", parseFloatArg)
51
51
  .option("--task <id>", "Task ID.")
52
52
  .option("--note <text>", "Assignment note.")
@@ -1,10 +1,18 @@
1
1
  import { z } from "zod";
2
- import { printObject } from "../output.js";
2
+ import { printObject, printRecords } from "../output.js";
3
3
  import { printReceipt } from "../receipt.js";
4
- import { resolveContext } from "./helpers.js";
4
+ import { resolveBaseContext, resolveContext } from "./helpers.js";
5
5
  import { leafCommand } from "./leaf-command.js";
6
- async function readReportBody(response) {
7
- const text = new TextDecoder().decode(await response.arrayBuffer());
6
+ async function readReportBody(response, exportType) {
7
+ const buffer = await response.arrayBuffer();
8
+ if (exportType === "XLSX" || exportType === "PDF") {
9
+ return {
10
+ exportType,
11
+ bytes: buffer.byteLength,
12
+ note: "Binary export; the CLI cannot emit it on stdout without corrupting it. Run `clk115 shared-reports list` and open the report's `link` to download the file.",
13
+ };
14
+ }
15
+ const text = new TextDecoder().decode(buffer);
8
16
  if (!text)
9
17
  return { body: "" };
10
18
  try {
@@ -58,7 +66,8 @@ const dateStringSchema = nonEmptyStringSchema.refine((value) => !Number.isNaN(Da
58
66
  const upperCaseString = (value) => typeof value === "string" ? value.toUpperCase() : value;
59
67
  const sharedReportTypeSchema = z.preprocess(upperCaseString, z.enum(SHARED_REPORT_TYPES));
60
68
  const sharedReportExportTypeSchema = z.preprocess(upperCaseString, z.enum(SHARED_REPORT_EXPORT_TYPES));
61
- const openObjectSchema = z.record(z.unknown());
69
+ const openObjectSchema = z.record(z.string(), z.unknown());
70
+ const INT_MESSAGE = { error: "provide a whole integer" };
62
71
  const sharedUsersFilterSchema = z
63
72
  .object({
64
73
  contains: z.enum(["CONTAINS", "DOES_NOT_CONTAIN", "CONTAINS_ONLY"]).optional(),
@@ -68,8 +77,8 @@ const sharedUsersFilterSchema = z
68
77
  .strict();
69
78
  const sharedAttendanceFilterSchema = z
70
79
  .object({
71
- page: z.number().finite().int().optional(),
72
- pageSize: z.number().finite().int().optional(),
80
+ page: z.number().finite().int(INT_MESSAGE).optional(),
81
+ pageSize: z.number().finite().int(INT_MESSAGE).optional(),
73
82
  users: sharedUsersFilterSchema.optional(),
74
83
  })
75
84
  .strict();
@@ -77,15 +86,18 @@ const sharedDetailedFilterSchema = z
77
86
  .object({
78
87
  auditFilter: openObjectSchema.optional(),
79
88
  options: openObjectSchema.optional(),
80
- page: z.number().finite().int().optional(),
81
- pageSize: z.number().finite().int().optional(),
89
+ page: z.number().finite().int(INT_MESSAGE).optional(),
90
+ pageSize: z.number().finite().int(INT_MESSAGE).optional(),
82
91
  sortColumn: nonEmptyStringSchema.optional(),
83
92
  sortOrder: z.enum(["ASCENDING", "DESCENDING"]).optional(),
84
93
  })
85
94
  .strict();
86
95
  const sharedSummaryFilterSchema = z
87
96
  .object({
88
- groups: z.array(z.enum(SUMMARY_GROUPS)).min(1).max(3),
97
+ groups: z
98
+ .array(z.enum(SUMMARY_GROUPS))
99
+ .min(1, { error: `provide 1-3 of: ${SUMMARY_GROUPS.join(", ")}` })
100
+ .max(3, { error: `provide at most 3 of: ${SUMMARY_GROUPS.join(", ")}` }),
89
101
  sortColumn: nonEmptyStringSchema.optional(),
90
102
  })
91
103
  .strict();
@@ -209,9 +221,9 @@ function schemaIssueLabel(issue, operation) {
209
221
  return operation;
210
222
  }
211
223
  function sharedReportValidationError(error, operation, rawType) {
212
- const invalidTypeIssue = error.issues.find((issue) => issue.path[0] === "type" && issue.code === z.ZodIssueCode.invalid_enum_value);
224
+ const invalidTypeIssue = error.issues.find((issue) => issue.path[0] === "type" && issue.code === z.ZodIssueCode.invalid_value);
213
225
  if (invalidTypeIssue !== undefined) {
214
- return new Error(`Unknown --type "${String(rawType)}". Use one of: ${SHARED_REPORT_TYPES.join(", ")}.`);
226
+ return new Error(`Unknown --type "${String(rawType)}". Provide one of: ${SHARED_REPORT_TYPES.join(", ")}.`);
215
227
  }
216
228
  const issue = error.issues[0];
217
229
  if (issue === undefined)
@@ -234,7 +246,7 @@ function parseSharedReportBody(schema, opts, operation) {
234
246
  name: opts.name,
235
247
  type: opts.type,
236
248
  filter: parseFilterJson(opts.filter),
237
- ...(opts.public === true ? { isPublic: true } : {}),
249
+ ...(opts.public !== undefined ? { isPublic: opts.public } : {}),
238
250
  };
239
251
  const result = schema.safeParse(candidate);
240
252
  if (!result.success) {
@@ -250,27 +262,39 @@ export const registerSharedReportsCommand = (program, services) => {
250
262
  .description("List the workspace's shared (public-link) reports.")
251
263
  .action(async function () {
252
264
  const { client, workspaceId, output } = await resolveContext(this, services);
253
- const result = await client.sharedReports.list({ workspaceId });
254
- printObject(result, output);
265
+ const response = await client.sharedReports.list({ workspaceId });
266
+ const rows = (response.reports ?? []).map((report) => ({
267
+ id: report.id ?? "",
268
+ name: report.name ?? "",
269
+ type: report.type ?? "",
270
+ isPublic: report.isPublic === true,
271
+ link: report.link ?? "",
272
+ }));
273
+ printRecords(rows, output);
255
274
  });
256
275
  leafCommand(shared, "view", "read")
257
276
  .argument("<id>", "Shared-report ID.")
258
277
  .option("--export-type <type>", "Export type: JSON_V1, JSON, CSV, XLSX, or PDF (default JSON_V1).")
259
278
  .description("View a shared report's rendered data by ID (reports host; not workspace-scoped).")
260
279
  .action(async function (id, opts) {
261
- const { client, output } = await resolveContext(this, services);
262
- const exportType = (opts.exportType ? String(opts.exportType).toUpperCase() : "JSON_V1");
280
+ const { client, output } = await resolveBaseContext(this, services);
281
+ const candidate = opts.exportType ? String(opts.exportType).toUpperCase() : "JSON_V1";
282
+ if (!SHARED_REPORT_EXPORT_TYPES.includes(candidate)) {
283
+ throw new Error(`Unknown --export-type "${String(opts.exportType)}". Provide one of: ${SHARED_REPORT_EXPORT_TYPES.join(", ")}.`);
284
+ }
285
+ const exportType = candidate;
263
286
  const response = await client.sharedReports.view({
264
287
  sharedReportId: id,
265
288
  exportType,
266
289
  });
267
- printObject(await readReportBody(response), output);
290
+ printObject(await readReportBody(response, exportType), output);
268
291
  });
269
292
  leafCommand(shared, "create", "write")
270
293
  .requiredOption("--name <text>", "Shared-report name.")
271
294
  .requiredOption("--type <type>", `Report type: ${SHARED_REPORT_TYPES.join(", ")}.`)
272
295
  .requiredOption("--filter <json>", "Report filter object as a JSON string.")
273
296
  .option("--public", "Make the report publicly accessible.")
297
+ .option("--no-public", "Make the report private (no public link).")
274
298
  .description("Create a shared (public-link) report.")
275
299
  .action(async function (opts) {
276
300
  const { client, workspaceId, output } = await resolveContext(this, services);
@@ -299,6 +323,7 @@ export const registerSharedReportsCommand = (program, services) => {
299
323
  .requiredOption("--type <type>", `Report type: ${SHARED_REPORT_TYPES.join(", ")}.`)
300
324
  .requiredOption("--filter <json>", "Report filter object as a JSON string (full replace).")
301
325
  .option("--public", "Make the report publicly accessible.")
326
+ .option("--no-public", "Make the report private (no public link).")
302
327
  .description("Replace a shared report by ID (full replace of name, type, and filter).")
303
328
  .action(async function (id, opts) {
304
329
  const { client, workspaceId, output } = await resolveContext(this, services);
@@ -1,4 +1,3 @@
1
- import { entityId } from "clockify-sdk-ts-115/operation-receipt";
2
1
  import { printReceipt } from "../receipt.js";
3
2
  import { resolveContext } from "./helpers.js";
4
3
  import { leafCommand } from "./leaf-command.js";
@@ -13,11 +12,6 @@ export const registerStartCommand = (program, services) => {
13
12
  .option("--billable", "Mark the entry as billable.", false)
14
13
  .action(async function (description, opts) {
15
14
  const { client, workspaceId, output } = await resolveContext(this, services);
16
- const user = await client.users.getCurrentUser();
17
- const userId = entityId(user);
18
- if (!userId) {
19
- throw new Error("could not determine user ID from getCurrentUser response");
20
- }
21
15
  const projectId = opts.project
22
16
  ? await resolveProjectId(client, workspaceId, opts.project)
23
17
  : undefined;
@@ -1,5 +1,4 @@
1
1
  import { entityId } from "clockify-sdk-ts-115/operation-receipt";
2
- import { printSuccess } from "../output.js";
3
2
  import { printReceipt } from "../receipt.js";
4
3
  import { resolveContext } from "./helpers.js";
5
4
  import { leafCommand } from "./leaf-command.js";
@@ -16,7 +15,15 @@ export const registerStopCommand = (program, services) => {
16
15
  const inProgress = (await client.timeEntries.listInProgress({ workspaceId }));
17
16
  const running = inProgress.find((entry) => entry.userId === userId && entry.id);
18
17
  if (!running) {
19
- printSuccess("no timer was running", output);
18
+ printReceipt({
19
+ ok: true,
20
+ action: "timer.stop",
21
+ entity: "time_entry",
22
+ ids: {},
23
+ data: { message: "no timer was running" },
24
+ changed: {},
25
+ next: [{ command: "clk115 start --json", reason: "Start a timer." }],
26
+ }, output);
20
27
  return;
21
28
  }
22
29
  const end = new Date().toISOString();
@@ -67,6 +67,9 @@ export const registerTagsCommand = (program, services) => {
67
67
  .option("--no-archived", "Unarchive the tag.")
68
68
  .description("Update a tag by ID.")
69
69
  .action(async function (id, opts) {
70
+ if (!opts.name && opts.archived === undefined) {
71
+ throw new Error("tags.update needs a change: provide at least one tag field.");
72
+ }
70
73
  const { client, workspaceId, output } = await resolveContext(this, services);
71
74
  const body = {};
72
75
  if (opts.name)
@@ -11,7 +11,7 @@ function requireTaskName(value, source) {
11
11
  function taskStatus(value, source) {
12
12
  const status = String(value).toUpperCase();
13
13
  if (status !== "ACTIVE" && status !== "DONE") {
14
- throw new Error(`${source} has unknown task status: ${String(value)}`);
14
+ throw new Error(`${source} has unknown task status: ${String(value)}; provide ACTIVE or DONE`);
15
15
  }
16
16
  return status;
17
17
  }
@@ -177,7 +177,7 @@ export const registerTasksCommand = (program, services) => {
177
177
  opts.billable !== undefined ||
178
178
  opts.assignee !== undefined;
179
179
  if (!hasChanges) {
180
- throw new Error("tasks.update requires at least one task field to change.");
180
+ throw new Error("tasks.update needs a change: provide at least one task field.");
181
181
  }
182
182
  const current = (await client.tasks.get({
183
183
  workspaceId,
@@ -204,7 +204,7 @@ export const registerTasksCommand = (program, services) => {
204
204
  body.assigneeIds = opts.assignee;
205
205
  }
206
206
  if (!changed) {
207
- throw new Error("tasks.update values are unchanged; refusing to mutate.");
207
+ throw new Error("tasks.update values are unchanged; provide a different value.");
208
208
  }
209
209
  const req = {
210
210
  workspaceId,
@@ -265,7 +265,11 @@ export const registerTasksCommand = (program, services) => {
265
265
  taskId: id,
266
266
  body: originalBody,
267
267
  };
268
- await client.tasks.update(rollbackRequest);
268
+ try {
269
+ await client.tasks.update(rollbackRequest);
270
+ }
271
+ catch {
272
+ }
269
273
  }
270
274
  throw error;
271
275
  }
@@ -10,7 +10,7 @@ export const registerTimeOffCommand = (program, services) => {
10
10
  .option("--limit <n>", "Items per page (default 50, max 200).", parseIntArg, 50)
11
11
  .option("--start <date>", "Window start (YYYY-MM-DD or RFC3339).")
12
12
  .option("--end <date>", "Window end (YYYY-MM-DD or RFC3339).")
13
- .option("--status <statuses>", "Comma-separated statuses (APPROVED, PENDING, REJECTED, WITHDRAWN).")
13
+ .option("--status <statuses>", "Comma-separated statuses (PENDING, APPROVED, REJECTED, ALL).")
14
14
  .option("--user <ids>", "Comma-separated user IDs to scope the search.")
15
15
  .action(async function (opts) {
16
16
  const { client, workspaceId, output } = await resolveContext(this, services);
@@ -24,11 +24,11 @@ export const registerTimeOffCommand = (program, services) => {
24
24
  if (opts.end)
25
25
  req.end = opts.end;
26
26
  if (opts.status) {
27
- const statuses = splitList(opts.status);
27
+ const statuses = splitList(opts.status).map((s) => s.toUpperCase());
28
28
  const known = new Set(["PENDING", "APPROVED", "REJECTED", "ALL"]);
29
29
  const invalid = statuses.filter((status) => !known.has(status));
30
30
  if (invalid.length > 0)
31
- throw new Error(`Unknown time-off status: ${invalid.join(", ")}`);
31
+ throw new Error(`Unknown time-off status: ${invalid.join(", ")}; provide PENDING, APPROVED, REJECTED, or ALL`);
32
32
  req.statuses = statuses;
33
33
  }
34
34
  if (opts.user)
@@ -66,6 +66,10 @@ export const registerTimeOffCommand = (program, services) => {
66
66
  if (opts.end === undefined && !Number.isFinite(opts.days)) {
67
67
  throw new Error("provide --end (date-range / HOURS-unit policies) or --days (DAYS-unit policies)");
68
68
  }
69
+ const halfDayPeriod = opts.halfDayPeriod === undefined ? "NOT_DEFINED" : String(opts.halfDayPeriod).toUpperCase();
70
+ if (!["FIRST_HALF", "SECOND_HALF", "NOT_DEFINED"].includes(halfDayPeriod)) {
71
+ throw new Error(`--half-day-period must be FIRST_HALF, SECOND_HALF, or NOT_DEFINED (got "${String(opts.halfDayPeriod)}").`);
72
+ }
69
73
  const { client, workspaceId, output } = await resolveContext(this, services);
70
74
  const period = { start: opts.start };
71
75
  if (opts.end !== undefined)
@@ -76,7 +80,7 @@ export const registerTimeOffCommand = (program, services) => {
76
80
  note: opts.note ?? "",
77
81
  timeOffPeriod: {
78
82
  isHalfDay: opts.halfDay === true,
79
- halfDayPeriod: opts.halfDayPeriod ?? "NOT_DEFINED",
83
+ halfDayPeriod: halfDayPeriod,
80
84
  period,
81
85
  },
82
86
  };
@@ -2,6 +2,24 @@ import { printObject, printRecords } from "../output.js";
2
2
  import { printReceipt } from "../receipt.js";
3
3
  import { clampPageSize, parseIntArg, resolveBaseContext, resolveContext } from "./helpers.js";
4
4
  import { leafCommand } from "./leaf-command.js";
5
+ const USER_DAYS = [
6
+ "MONDAY",
7
+ "TUESDAY",
8
+ "WEDNESDAY",
9
+ "THURSDAY",
10
+ "FRIDAY",
11
+ "SATURDAY",
12
+ "SUNDAY",
13
+ ];
14
+ const userDaysExhaustive = true;
15
+ void userDaysExhaustive;
16
+ function requireUserDay(value, message) {
17
+ const day = String(value).toUpperCase();
18
+ if (!USER_DAYS.includes(day)) {
19
+ throw new Error(message);
20
+ }
21
+ return day;
22
+ }
5
23
  export const registerUsersCommand = (program, services) => {
6
24
  const users = program.command("users").description("Inspect workspace users.");
7
25
  leafCommand(users, "me", "read")
@@ -45,11 +63,11 @@ export const registerUsersCommand = (program, services) => {
45
63
  .action(async function (email, opts) {
46
64
  const { client, workspaceId, output } = await resolveContext(this, services);
47
65
  const sendEmail = opts.sendEmail !== false;
48
- const workspace = (await client.workspaces.addUser({
66
+ await client.workspaces.addUser({
49
67
  workspaceId,
50
68
  "send-email": sendEmail ? "true" : "false",
51
69
  email,
52
- }));
70
+ });
53
71
  printReceipt({
54
72
  ok: true,
55
73
  action: "users.invite",
@@ -58,7 +76,7 @@ export const registerUsersCommand = (program, services) => {
58
76
  data: { email, sendEmail, message: `invited ${email}` },
59
77
  changed: {
60
78
  created: [
61
- { type: "workspace_member", id: workspace.id ?? "", name: email },
79
+ { type: "workspace_member", id: "", name: email },
62
80
  ],
63
81
  },
64
82
  next: [
@@ -74,9 +92,9 @@ export const registerUsersCommand = (program, services) => {
74
92
  .option("--name <text>", "Display name.")
75
93
  .option("--image-url <url>", "Profile image URL.")
76
94
  .option("--remove-image", "Remove the profile image.")
77
- .option("--week-start <day>", "Week start day, e.g. MONDAY.")
95
+ .option("--week-start <day>", "Week start day: MONDAY, TUESDAY, ... SUNDAY.")
78
96
  .option("--work-capacity <iso>", "Daily work capacity, ISO-8601 duration (e.g. PT8H).")
79
- .option("--working-days <days...>", "Working day enums, e.g. MONDAY TUESDAY.")
97
+ .option("--working-days <days...>", "Working days: MONDAY, TUESDAY, ... SUNDAY (space-separated).")
80
98
  .description("Update one user's member profile (name, image, week start, work capacity, working days).")
81
99
  .action(async function (userId, opts) {
82
100
  const { client, workspaceId, output } = await resolveContext(this, services);
@@ -87,12 +105,18 @@ export const registerUsersCommand = (program, services) => {
87
105
  body.imageUrl = opts.imageUrl;
88
106
  if (opts.removeImage)
89
107
  body.removeProfileImage = true;
90
- if (opts.weekStart !== undefined)
91
- body.weekStart = opts.weekStart;
108
+ if (opts.weekStart !== undefined) {
109
+ body.weekStart = requireUserDay(opts.weekStart, `--week-start must be one of: ${USER_DAYS.join(", ")}.`);
110
+ }
92
111
  if (opts.workCapacity !== undefined)
93
112
  body.workCapacity = opts.workCapacity;
94
- if (Array.isArray(opts.workingDays) && opts.workingDays.length > 0)
95
- body.workingDays = opts.workingDays;
113
+ if (Array.isArray(opts.workingDays) && opts.workingDays.length > 0) {
114
+ const days = [];
115
+ for (const raw of opts.workingDays) {
116
+ days.push(requireUserDay(raw, `--working-days entries must be one of: ${USER_DAYS.join(", ")}.`));
117
+ }
118
+ body.workingDays = days;
119
+ }
96
120
  const updated = (await client.memberProfiles.update({ workspaceId, userId, body }));
97
121
  printReceipt({
98
122
  ok: true,
@@ -82,18 +82,18 @@ function nonEmptyString(value, field) {
82
82
  function webhookEvent(value) {
83
83
  const event = String(value).toUpperCase();
84
84
  if (!WEBHOOK_EVENT_TYPES.includes(event)) {
85
- throw new Error(`Unknown webhook event: ${String(value)}`);
85
+ throw new Error(`Unknown webhook event: ${String(value)}. Provide a Clockify webhook event type such as NEW_PROJECT or NEW_TIME_ENTRY.`);
86
86
  }
87
87
  return event;
88
88
  }
89
89
  function webhookTriggerSourceType(value) {
90
90
  const raw = value ?? "WORKSPACE_ID";
91
91
  if (typeof raw !== "string") {
92
- throw new Error("Unknown trigger source type: expected a string.");
92
+ throw new Error("Unknown trigger source type. Provide one of: PROJECT_ID, USER_ID, TAG_ID, TASK_ID, WORKSPACE_ID, ASSIGNMENT_ID, EXPENSE_ID.");
93
93
  }
94
94
  const type = raw.toUpperCase();
95
95
  if (!WEBHOOK_TRIGGER_SOURCE_TYPES.includes(type)) {
96
- throw new Error(`Unknown trigger source type: ${raw}`);
96
+ throw new Error(`Unknown trigger source type: ${raw}. Provide one of: PROJECT_ID, USER_ID, TAG_ID, TASK_ID, WORKSPACE_ID, ASSIGNMENT_ID, EXPENSE_ID.`);
97
97
  }
98
98
  return type;
99
99
  }
@@ -108,7 +108,7 @@ export const registerWebhooksCommand = (program, services) => {
108
108
  if (opts.type) {
109
109
  const candidate = String(opts.type).toUpperCase();
110
110
  if (!WEBHOOK_LIST_TYPES.includes(candidate)) {
111
- throw new Error(`Unknown webhook type: ${opts.type}`);
111
+ throw new Error(`Unknown webhook type: ${opts.type}. Provide one of: WEBHOOK, ADDON_WEBHOOK.`);
112
112
  }
113
113
  type = candidate;
114
114
  }
package/dist/config.js CHANGED
@@ -38,27 +38,28 @@ function loadRcFile(env) {
38
38
  if (!existsSync(path)) {
39
39
  continue;
40
40
  }
41
+ let parsed = {};
41
42
  try {
42
43
  const raw = readFileSync(path, "utf8");
43
- const parsed = JSON.parse(raw);
44
- if (Object.prototype.hasOwnProperty.call(parsed, "apiKey")) {
45
- throw new Error("legacy rc-file secret detected: remove apiKey from the rc file and set CLOCKIFY_API_KEY in the process environment");
46
- }
47
- const out = {};
48
- if (typeof parsed.workspaceId === "string")
49
- out.workspaceId = parsed.workspaceId;
50
- if (typeof parsed.baseUrl === "string")
51
- out.baseUrl = parsed.baseUrl;
52
- if (typeof parsed.region === "string")
53
- out.region = parsed.region;
54
- if (typeof parsed.subdomain === "string")
55
- out.subdomain = parsed.subdomain;
56
- return out;
44
+ parsed = JSON.parse(raw);
57
45
  }
58
46
  catch (err) {
59
47
  const reason = err instanceof Error ? err.message : String(err);
60
48
  throw new Error(`failed to read Clockify rc file ${path}: ${reason}`);
61
49
  }
50
+ if (Object.prototype.hasOwnProperty.call(parsed, "apiKey")) {
51
+ throw new Error("legacy rc-file secret detected: remove apiKey from the rc file and set CLOCKIFY_API_KEY in the process environment");
52
+ }
53
+ const out = {};
54
+ if (typeof parsed.workspaceId === "string")
55
+ out.workspaceId = parsed.workspaceId;
56
+ if (typeof parsed.baseUrl === "string")
57
+ out.baseUrl = parsed.baseUrl;
58
+ if (typeof parsed.region === "string")
59
+ out.region = parsed.region;
60
+ if (typeof parsed.subdomain === "string")
61
+ out.subdomain = parsed.subdomain;
62
+ return out;
62
63
  }
63
64
  return {};
64
65
  }
package/dist/duration.js CHANGED
@@ -1,7 +1,7 @@
1
1
  export function parseDuration(input) {
2
2
  const trimmed = input.trim();
3
3
  if (trimmed === "") {
4
- throw new Error("duration is empty");
4
+ throw new Error('duration is missing; provide a form like "1h30m", "45m", "90", or ISO "PT1H30M"');
5
5
  }
6
6
  if (/^PT/i.test(trimmed)) {
7
7
  return parseIsoDuration(trimmed);
@@ -21,7 +21,7 @@ export function parseDuration(input) {
21
21
  consumed += match[0].length;
22
22
  }
23
23
  if (consumed === 0 || consumed < compact.length) {
24
- throw new Error(`cannot parse duration ${JSON.stringify(input)}; use forms like "1h30m", "45m", "90", or ISO "PT1H30M"`);
24
+ throw new Error(`could not parse duration ${JSON.stringify(input)}; use forms like "1h30m", "45m", "90", or ISO "PT1H30M"`);
25
25
  }
26
26
  return Math.round(total);
27
27
  }
@@ -29,7 +29,7 @@ function parseIsoDuration(input) {
29
29
  const re = /^PT(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?$/i;
30
30
  const match = re.exec(input);
31
31
  if (!match || (match[1] == null && match[2] == null && match[3] == null)) {
32
- throw new Error(`cannot parse ISO duration ${JSON.stringify(input)}`);
32
+ throw new Error(`could not parse ISO duration ${JSON.stringify(input)}; provide a form like "PT1H30M"`);
33
33
  }
34
34
  const hours = match[1] != null ? Number(match[1]) : 0;
35
35
  const minutes = match[2] != null ? Number(match[2]) : 0;
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = "0.4.0";
1
+ export const PACKAGE_VERSION = "0.5.0";
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { Command } from "commander";
2
+ import { Command, InvalidArgumentError } from "commander";
3
3
  import { buildClient } from "./client.js";
4
4
  import { registerApiCommand } from "./commands/api.js";
5
5
  import { registerAuditLogCommand } from "./commands/auditlog.js";
@@ -41,7 +41,7 @@ export function buildProgram(services = defaultServices) {
41
41
  .option("--region <name>", "Clockify routing region: global, eu, us, uk, au, or developer (or CLOCKIFY_REGION env var). Mutually exclusive with --base-url.")
42
42
  .option("--subdomain <label>", "Workspace subdomain for reports routing; requires --region eu/us/uk/au (or CLOCKIFY_SUBDOMAIN env var).")
43
43
  .option("--json", "Emit machine-readable JSON instead of human-friendly tables.", false)
44
- .option("--output <mode>", "Output mode: table, json, or ndjson.")
44
+ .option("--output <mode>", "Output mode: table, json, or ndjson.", parseOutputMode)
45
45
  .option("--compact", "Print compact JSON without indentation.", false)
46
46
  .option("--select <path>", "Select a dot-path before printing JSON or NDJSON.")
47
47
  .option("--no-color", "Disable ANSI color output.")
@@ -99,6 +99,14 @@ function resolveFlagsSafe(program) {
99
99
  };
100
100
  }
101
101
  }
102
+ function parseOutputMode(value) {
103
+ const modes = ["table", "json", "ndjson"];
104
+ const match = modes.find((mode) => mode === value);
105
+ if (!match) {
106
+ throw new InvalidArgumentError("Provide one of: table, json, ndjson.");
107
+ }
108
+ return match;
109
+ }
102
110
  function resolveMode(output, json) {
103
111
  if (output === undefined) {
104
112
  return json ? "json" : "table";
@@ -106,7 +114,7 @@ function resolveMode(output, json) {
106
114
  const modes = ["table", "json", "ndjson"];
107
115
  const match = modes.find((mode) => mode === output);
108
116
  if (!match) {
109
- throw new Error(`Unsupported output mode "${output}". Use table, json, or ndjson.`);
117
+ throw new Error(`Unsupported output mode "${output}". Provide one of: table, json, ndjson.`);
110
118
  }
111
119
  return match;
112
120
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apet97/clockify-cli-115",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Unofficial, community-built — not affiliated with CAKE.com or Clockify. Command-line interface for Clockify, built on clockify-sdk-ts-115.",
5
5
  "license": "MIT",
6
6
  "author": "Aleksandar Petković <petkovic.aleksandar037@gmail.com>",
@@ -51,7 +51,7 @@
51
51
  "cli-table3": "^0.6.5",
52
52
  "commander": "^15.0.0",
53
53
  "picocolors": "^1.1.1",
54
- "zod": "^3.25.0"
54
+ "zod": "^4.4.3"
55
55
  },
56
56
  "peerDependencies": {
57
57
  "clockify-sdk-ts-115": ">=0.13.0 <1"
@@ -60,11 +60,11 @@
60
60
  "@types/node": "^22",
61
61
  "@vitest/coverage-v8": "^4.1.10",
62
62
  "clockify-sdk-ts-115": "*",
63
- "eslint": "^10.5.0",
63
+ "eslint": "^10.8.0",
64
64
  "eslint-plugin-import-x": "^4.17.1",
65
- "tsx": "^4.19.2",
65
+ "tsx": "^4.23.1",
66
66
  "typescript": "^5.7.0",
67
- "typescript-eslint": "^8.64.0",
67
+ "typescript-eslint": "^8.65.0",
68
68
  "vitest": "^4.1.10"
69
69
  },
70
70
  "publishConfig": {