@apet97/clockify-cli-115 6.0.0 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +167 -21
  2. package/dist/client.js +30 -7
  3. package/dist/commands/api.js +44 -76
  4. package/dist/commands/approvals.js +2 -5
  5. package/dist/commands/auth.js +229 -0
  6. package/dist/commands/balanceAssignment.js +5 -12
  7. package/dist/commands/batch.js +226 -0
  8. package/dist/commands/clients.js +18 -79
  9. package/dist/commands/doctor.js +65 -66
  10. package/dist/commands/entries.js +5 -8
  11. package/dist/commands/expenses.js +29 -39
  12. package/dist/commands/helpers.js +68 -30
  13. package/dist/commands/invoices.js +3 -3
  14. package/dist/commands/leaf-command.js +7 -0
  15. package/dist/commands/manifest.js +63 -0
  16. package/dist/commands/operations.js +271 -0
  17. package/dist/commands/projects.js +17 -37
  18. package/dist/commands/reports.js +22 -7
  19. package/dist/commands/shared-report-body.js +14 -81
  20. package/dist/commands/sharedReports.js +8 -47
  21. package/dist/commands/skill.js +85 -0
  22. package/dist/commands/status.js +19 -13
  23. package/dist/commands/stop.js +3 -12
  24. package/dist/commands/tags.js +12 -21
  25. package/dist/commands/tasks.js +26 -134
  26. package/dist/commands/timeoff.js +1 -1
  27. package/dist/commands/users.js +4 -14
  28. package/dist/commands/webhook-delivery.js +331 -0
  29. package/dist/commands/webhooks.js +37 -110
  30. package/dist/completions.js +2 -1
  31. package/dist/config.js +166 -63
  32. package/dist/credentials.js +164 -0
  33. package/dist/failure.js +4 -9
  34. package/dist/flags.js +14 -4
  35. package/dist/generated/version.js +1 -1
  36. package/dist/index.js +38 -15
  37. package/dist/interrupts.js +28 -0
  38. package/dist/output.js +137 -48
  39. package/dist/receipt.js +2 -10
  40. package/dist/stdin.js +6 -0
  41. package/dist/stdout.js +38 -0
  42. package/dist/write-outcome.js +1 -1
  43. package/package.json +5 -3
  44. package/plugin/.claude-plugin/plugin.json +16 -0
  45. package/plugin/skills/clockify-cli/SKILL.md +88 -0
  46. package/plugin/skills/clockify-mcp/SKILL.md +48 -0
  47. package/plugin/skills/clockify-sdk/SKILL.md +85 -0
  48. package/dist/error-codes.js +0 -300
package/dist/config.js CHANGED
@@ -1,7 +1,11 @@
1
- import { existsSync, readFileSync } from "node:fs";
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
3
  import { homedir } from "node:os";
3
- import { join } from "node:path";
4
- const KNOWN_RC_FILE_KEYS = ["workspaceId", "baseUrl", "region", "subdomain"];
4
+ import { dirname, join } from "node:path";
5
+ import { UsageError } from "./failure.js";
6
+ const ROUTING_KEYS = ["workspaceId", "baseUrl", "region", "subdomain"];
7
+ const KNOWN_RC_FILE_KEYS = ["workspaceId", "baseUrl", "region", "subdomain", "profile", "profiles"];
8
+ const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
5
9
  const SECRET_RC_FILE_KEY = /api[-_]?key|token|secret|password|credential/i;
6
10
  function editDistance(left, right) {
7
11
  let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
@@ -15,42 +19,113 @@ function editDistance(left, right) {
15
19
  }
16
20
  return previous[right.length];
17
21
  }
18
- function nearestRcFileKey(input) {
19
- const normalized = input.toLowerCase();
20
- let nearest = KNOWN_RC_FILE_KEYS[0];
21
- let smallestDistance = editDistance(normalized, nearest.toLowerCase());
22
- for (const candidate of KNOWN_RC_FILE_KEYS.slice(1)) {
23
- const distance = editDistance(normalized, candidate.toLowerCase());
24
- if (distance < smallestDistance) {
25
- nearest = candidate;
26
- smallestDistance = distance;
27
- }
22
+ function nearestKey(input, known) {
23
+ const distance = (candidate) => editDistance(input.toLowerCase(), candidate.toLowerCase());
24
+ return known.reduce((nearest, candidate) => (distance(candidate) < distance(nearest) ? candidate : nearest));
25
+ }
26
+ function warnUnknownKeys(value, known) {
27
+ for (const key of Object.keys(value)) {
28
+ if (known.includes(key))
29
+ continue;
30
+ process.stderr.write(`WARN clk115: ignoring unknown rc-file key ${JSON.stringify(key)}. Did you mean ${JSON.stringify(nearestKey(key, known))}?\n`);
28
31
  }
29
- return nearest;
32
+ }
33
+ function routed(flags, env, file) {
34
+ const named = firstPresent(flags.baseUrl, env.baseUrl, flags.region, env.region) !== undefined;
35
+ const out = {};
36
+ for (const key of ROUTING_KEYS) {
37
+ const value = firstPresent(flags[key], env[key], named && key !== "workspaceId" ? undefined : file[key]);
38
+ if (value !== undefined)
39
+ out[key] = value;
40
+ }
41
+ return out;
42
+ }
43
+ function routingFlags({ workspace, baseUrl, region, subdomain }) {
44
+ return {
45
+ ...(workspace !== undefined && { workspaceId: workspace }),
46
+ ...(baseUrl !== undefined && { baseUrl }),
47
+ ...(region !== undefined && { region }),
48
+ ...(subdomain !== undefined && { subdomain }),
49
+ };
50
+ }
51
+ function routingEnv(env) {
52
+ return {
53
+ ...(env.CLOCKIFY_WORKSPACE_ID !== undefined && { workspaceId: env.CLOCKIFY_WORKSPACE_ID }),
54
+ ...(env.CLOCKIFY_BASE_URL !== undefined && { baseUrl: env.CLOCKIFY_BASE_URL }),
55
+ ...(env.CLOCKIFY_REGION !== undefined && { region: env.CLOCKIFY_REGION }),
56
+ ...(env.CLOCKIFY_SUBDOMAIN !== undefined && { subdomain: env.CLOCKIFY_SUBDOMAIN }),
57
+ };
58
+ }
59
+ export function selectedProfile(flags, current, env = process.env) {
60
+ return firstPresent(flags.profile, env.CLOCKIFY_PROFILE, current);
30
61
  }
31
62
  export function loadConfig(flags = {}, env = process.env) {
32
63
  const file = loadRcFile(env);
33
64
  const apiKey = firstPresent(env.CLOCKIFY_API_KEY);
34
- const workspaceId = firstPresent(flags.workspace, env.CLOCKIFY_WORKSPACE_ID, file.workspaceId);
35
- const baseUrl = firstPresent(flags.baseUrl, env.CLOCKIFY_BASE_URL, file.baseUrl);
36
- const region = firstPresent(flags.region, env.CLOCKIFY_REGION, file.region);
37
- const subdomain = firstPresent(flags.subdomain, env.CLOCKIFY_SUBDOMAIN, file.subdomain);
38
- return {
39
- ...(apiKey !== undefined ? { apiKey } : {}),
40
- ...(workspaceId !== undefined ? { workspaceId } : {}),
41
- ...(baseUrl !== undefined ? { baseUrl } : {}),
42
- ...(region !== undefined ? { region } : {}),
43
- ...(subdomain !== undefined ? { subdomain } : {}),
65
+ if (flags.profile === undefined && apiKey !== undefined) {
66
+ if (selectedProfile(flags, undefined, env) !== undefined) {
67
+ throw new Error("CLOCKIFY_API_KEY and CLOCKIFY_PROFILE are both set; provide only one of them.");
68
+ }
69
+ return { apiKey, ...routed(routingFlags(flags), routingEnv(env), file) };
70
+ }
71
+ const profile = selectedProfile(flags, file.profile, env);
72
+ if (profile === undefined)
73
+ return routed(routingFlags(flags), routingEnv(env), file);
74
+ const ambient = flags.profile === undefined ? routingEnv(env) : {};
75
+ return { profile, ...routed(routingFlags(flags), ambient, requireProfile(file.profiles, profile)) };
76
+ }
77
+ export function requireProfile(profiles, name) {
78
+ if (Object.hasOwn(profiles, name))
79
+ return profiles[name];
80
+ const known = Object.keys(profiles);
81
+ throw new UsageError(`Unknown profile "${name}". ` +
82
+ (known.length > 0 ? `Provide one of: ${known.join(", ")}.` : "Run `clk115 auth login` to create one."));
83
+ }
84
+ export function loginConfig(profile, flags, profiles) {
85
+ return { profile, ...routed(routingFlags(flags), {}, profiles[profile] ?? {}) };
86
+ }
87
+ export function loadProfiles(env = process.env) {
88
+ const { profile, profiles } = loadRcFile(env);
89
+ return { current: profile, profiles };
90
+ }
91
+ export function requireProfileName(name) {
92
+ if (!PROFILE_NAME.test(name)) {
93
+ throw new UsageError(`"${name}" is not a profile name; provide letters, digits, - or _ (64 at most).`);
94
+ }
95
+ return name;
96
+ }
97
+ export function saveProfiles({ current, profiles }, env = process.env) {
98
+ const path = rcFilePath(env);
99
+ const { profile: _profile, profiles: _profiles, ...rest } = existsSync(path) ? readRcObject(path) : {};
100
+ const next = {
101
+ ...rest,
102
+ ...(current !== undefined && { profile: current }),
103
+ ...(Object.keys(profiles).length > 0 && { profiles }),
44
104
  };
105
+ mkdirSync(dirname(path), { recursive: true });
106
+ const target = existsSync(path) ? realpathSync(path) : path;
107
+ const temporary = `${target}.${randomUUID()}.tmp`;
108
+ try {
109
+ writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, flag: "wx" });
110
+ renameSync(temporary, target);
111
+ }
112
+ finally {
113
+ rmSync(temporary, { force: true });
114
+ }
115
+ return path;
116
+ }
117
+ export function saveProfile(name, routing) {
118
+ const { current = name, profiles } = loadProfiles();
119
+ saveProfiles({ current, profiles: { ...profiles, [name]: routing } });
120
+ return { current, previous: Object.hasOwn(profiles, name) ? profiles[name] : undefined };
45
121
  }
46
122
  function firstPresent(...values) {
47
123
  return values.find((value) => typeof value === "string" && value.trim().length > 0);
48
124
  }
49
- export function requireApiKey(config) {
50
- if (!config.apiKey) {
51
- throw new Error("Clockify API key not set. Set CLOCKIFY_API_KEY in the process environment.");
52
- }
53
- return config.apiKey;
125
+ export function missingApiKey({ profile }) {
126
+ return new Error(profile === undefined
127
+ ? "Clockify API key not set. Set CLOCKIFY_API_KEY in the process environment, or run `clk115 auth login`."
128
+ : `Clockify API key not set: profile "${profile}" has no stored key for this host. Run \`clk115 auth login --profile ${profile}\`.`);
54
129
  }
55
130
  export function requireWorkspaceId(config) {
56
131
  if (!config.workspaceId) {
@@ -58,41 +133,69 @@ export function requireWorkspaceId(config) {
58
133
  }
59
134
  return config.workspaceId;
60
135
  }
61
- function loadRcFile(env) {
136
+ function rcFilePath(env) {
62
137
  const root = firstPresent(env.CLOCKIFY_HOME) ?? homedir();
63
138
  const candidates = [join(root, "clockifyrc.json"), join(root, ".clockifyrc.json")];
64
- for (const path of candidates) {
65
- if (!existsSync(path)) {
66
- continue;
67
- }
68
- let parsed;
69
- try {
70
- parsed = JSON.parse(readFileSync(path, "utf8"));
71
- }
72
- catch (err) {
73
- const reason = err instanceof Error ? err.message : String(err);
74
- throw new Error(`failed to read Clockify rc file ${path}: ${reason}`);
75
- }
76
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
77
- throw new Error(`Clockify rc file ${path} must contain a JSON object such as {"workspaceId":"..."}; fix or remove the file`);
78
- }
79
- const secretKeys = Object.keys(parsed).filter((key) => SECRET_RC_FILE_KEY.test(key));
80
- if (secretKeys.length > 0) {
81
- throw new Error(`legacy rc-file secret detected: remove ${secretKeys.join(", ")} from the rc file and set CLOCKIFY_API_KEY in the process environment`);
82
- }
83
- for (const key of Object.keys(parsed)) {
84
- if (KNOWN_RC_FILE_KEYS.includes(key))
85
- continue;
86
- const suggestion = nearestRcFileKey(key);
87
- process.stderr.write(`WARN clk115: ignoring unknown rc-file key ${JSON.stringify(key)}. Did you mean ${JSON.stringify(suggestion)}?\n`);
88
- }
89
- const out = {};
90
- for (const key of KNOWN_RC_FILE_KEYS) {
91
- const value = parsed[key];
92
- if (typeof value === "string")
93
- out[key] = value;
94
- }
95
- return out;
139
+ return candidates.find((path) => existsSync(path)) ?? candidates[1];
140
+ }
141
+ function readRcObject(path) {
142
+ let parsed;
143
+ try {
144
+ parsed = JSON.parse(readFileSync(path, "utf8"));
145
+ }
146
+ catch (err) {
147
+ const reason = err instanceof Error ? err.message : String(err);
148
+ throw new Error(`failed to read Clockify rc file ${path}: ${reason}`);
96
149
  }
97
- return {};
150
+ if (!isObject(parsed)) {
151
+ throw new Error(`Clockify rc file ${path} must contain a JSON object such as {"workspaceId":"..."}; fix or remove the file`);
152
+ }
153
+ return parsed;
154
+ }
155
+ function isObject(value) {
156
+ return value !== null && typeof value === "object" && !Array.isArray(value);
157
+ }
158
+ function refuseSecrets(value) {
159
+ const secretKeys = Object.keys(value).filter((key) => SECRET_RC_FILE_KEY.test(key));
160
+ if (secretKeys.length > 0) {
161
+ throw new Error(`legacy rc-file secret detected: remove ${secretKeys.join(", ")} from the rc file and set CLOCKIFY_API_KEY in the process environment`);
162
+ }
163
+ }
164
+ function readRouting(value) {
165
+ const out = {};
166
+ for (const key of ROUTING_KEYS) {
167
+ const text = value[key];
168
+ if (typeof text === "string")
169
+ out[key] = text;
170
+ }
171
+ return out;
172
+ }
173
+ function readProfiles(value) {
174
+ if (value === undefined)
175
+ return {};
176
+ if (!isObject(value))
177
+ throw new Error("rc file: `profiles` must be an object of named profiles");
178
+ const profiles = {};
179
+ for (const [name, profile] of Object.entries(value)) {
180
+ requireProfileName(name);
181
+ if (!isObject(profile))
182
+ throw new Error(`rc file: profile "${name}" must be an object`);
183
+ refuseSecrets(profile);
184
+ warnUnknownKeys(profile, ROUTING_KEYS);
185
+ profiles[name] = readRouting(profile);
186
+ }
187
+ return profiles;
188
+ }
189
+ function loadRcFile(env) {
190
+ const path = rcFilePath(env);
191
+ if (!existsSync(path))
192
+ return { profiles: {} };
193
+ const parsed = readRcObject(path);
194
+ refuseSecrets(parsed);
195
+ warnUnknownKeys(parsed, KNOWN_RC_FILE_KEYS);
196
+ return {
197
+ ...readRouting(parsed),
198
+ ...(typeof parsed.profile === "string" && parsed.profile !== "" && { profile: parsed.profile }),
199
+ profiles: readProfiles(parsed.profiles),
200
+ };
98
201
  }
@@ -0,0 +1,164 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createInterface } from "node:readline";
3
+ import { Writable } from "node:stream";
4
+ import { UsageError } from "./failure.js";
5
+ import { signalExitCode } from "./interrupts.js";
6
+ import { AlreadyReportedError } from "./output.js";
7
+ import { readStdin } from "./stdin.js";
8
+ const SERVICE = "clockify115-cli";
9
+ const ITEM_NOT_FOUND = 44;
10
+ const PROMPT_TIMEOUT_MS = 120_000;
11
+ const NOTHING_READ = "No API key was read; provide it on stdin or at the prompt.";
12
+ const ACCOUNT = /^[A-Za-z0-9_-]+@(?:https?:\/\/)?[A-Za-z0-9.:[\]-]+$/;
13
+ export function credentialHost({ baseUrl, region, subdomain }) {
14
+ if (baseUrl !== undefined)
15
+ return URL.canParse(baseUrl) ? new URL(baseUrl).origin : "invalid-base-url";
16
+ return subdomain === undefined ? (region ?? "global") : `${subdomain}.${region ?? "global"}`;
17
+ }
18
+ export function credentialAccount(config) {
19
+ const account = `${config.profile ?? ""}@${credentialHost(config)}`;
20
+ return ACCOUNT.test(account) ? account : undefined;
21
+ }
22
+ async function run(command, args, input = "") {
23
+ const { CLOCKIFY_API_KEY: _key, CLOCKIFY_ADDON_TOKEN: _token, ...env } = process.env;
24
+ const child = spawn(command, args, { env, stdio: ["pipe", "pipe", "pipe"] });
25
+ const timer = setTimeout(() => child.kill(), PROMPT_TIMEOUT_MS);
26
+ let stdout = "";
27
+ let stderr = "";
28
+ child.stdout.setEncoding("utf8").on("data", (text) => (stdout += text));
29
+ child.stderr.setEncoding("utf8").on("data", (text) => (stderr += text));
30
+ child.stdin.on("error", () => undefined);
31
+ child.stdin.end(input);
32
+ try {
33
+ return await new Promise((resolve, reject) => {
34
+ child.on("error", (err) => {
35
+ reject(new Error(`Could not run ${command}: ${err.message}. Set CLOCKIFY_API_KEY instead.`));
36
+ });
37
+ child.on("close", (code) => {
38
+ resolve({ code, stdout, stderr });
39
+ });
40
+ });
41
+ }
42
+ finally {
43
+ clearTimeout(timer);
44
+ }
45
+ }
46
+ function failed(store, action, { code, stderr }) {
47
+ const reason = stderr.trim().slice(0, 300) || `exit ${code ?? "by signal"}`;
48
+ return new Error(`Could not ${action} the API key in ${store}: ${reason}`);
49
+ }
50
+ export function macosKeychain(command = "/usr/bin/security", keychain = []) {
51
+ const name = "the macOS keychain";
52
+ const item = (account) => ["-s", SERVICE, "-a", account];
53
+ return {
54
+ name,
55
+ async get(account) {
56
+ const result = await run(command, ["find-generic-password", ...item(account), "-w", ...keychain]);
57
+ if (result.code === ITEM_NOT_FOUND)
58
+ return undefined;
59
+ if (result.code !== 0)
60
+ throw failed(name, "read", result);
61
+ return result.stdout.replace(/\n$/, "");
62
+ },
63
+ async set(account, secret) {
64
+ const words = ["add-generic-password", "-U", ...item(account), "-w", secret, ...keychain];
65
+ const result = await run(command, ["-i"], `${words.map((word) => `"${word}"`).join(" ")}\n`);
66
+ if (result.code !== 0)
67
+ throw failed(name, "store", result);
68
+ },
69
+ async delete(account) {
70
+ const result = await run(command, ["delete-generic-password", ...item(account), ...keychain]);
71
+ if (result.code === ITEM_NOT_FOUND)
72
+ return false;
73
+ if (result.code !== 0)
74
+ throw failed(name, "delete", result);
75
+ return true;
76
+ },
77
+ };
78
+ }
79
+ export function secretService(command = "secret-tool") {
80
+ const name = "the Secret Service keyring";
81
+ const item = (account) => ["service", SERVICE, "account", account];
82
+ const get = async (account) => {
83
+ const result = await run(command, ["lookup", ...item(account)]);
84
+ if (result.code === 0 && result.stdout !== "")
85
+ return result.stdout;
86
+ if (result.code === 1 && result.stderr.trim() === "")
87
+ return undefined;
88
+ throw failed(name, "read", result);
89
+ };
90
+ return {
91
+ name,
92
+ get,
93
+ async set(account, secret) {
94
+ const result = await run(command, ["store", "--label", `clk115 ${account}`, ...item(account)], secret);
95
+ if (result.code !== 0)
96
+ throw failed(name, "store", result);
97
+ },
98
+ async delete(account) {
99
+ if ((await get(account)) === undefined)
100
+ return false;
101
+ const result = await run(command, ["clear", ...item(account)]);
102
+ if (result.code !== 0)
103
+ throw failed(name, "delete", result);
104
+ return true;
105
+ },
106
+ };
107
+ }
108
+ export function systemCredentialStore(platform = process.platform) {
109
+ if (platform === "darwin")
110
+ return macosKeychain();
111
+ if (platform === "linux")
112
+ return secretService();
113
+ throw new UsageError(`clk115 has no credential store on ${platform}; set CLOCKIFY_API_KEY in the environment.`);
114
+ }
115
+ export function requireStorableKey(text) {
116
+ const key = text.trim();
117
+ if (key === "")
118
+ throw new UsageError(NOTHING_READ);
119
+ if (!/^[A-Za-z0-9+/=_.-]{8,512}$/.test(key)) {
120
+ throw new UsageError("That does not look like a Clockify API key; provide the key exactly as Clockify shows it.");
121
+ }
122
+ return key;
123
+ }
124
+ export async function storeVerified(store, account, key) {
125
+ const previous = await store.get(account);
126
+ const undo = async () => {
127
+ await (previous === undefined ? store.delete(account) : store.set(account, previous)).catch(() => undefined);
128
+ };
129
+ await store.set(account, key);
130
+ if ((await store.get(account)) === key)
131
+ return undo;
132
+ await undo();
133
+ throw new Error(`Could not read the API key back from ${store.name}, so it was not kept. Set CLOCKIFY_API_KEY instead.`);
134
+ }
135
+ export async function storedApiKey(config, store) {
136
+ const account = credentialAccount(config);
137
+ return account === undefined ? undefined : await store().get(account);
138
+ }
139
+ export async function readSecret() {
140
+ if (!process.stdin.isTTY)
141
+ return await readStdin();
142
+ const silent = new Writable({
143
+ write(_chunk, _encoding, done) {
144
+ done();
145
+ },
146
+ });
147
+ const reader = createInterface({ input: process.stdin, output: silent, terminal: true });
148
+ process.stderr.write("Clockify API key (hidden): ");
149
+ try {
150
+ return await new Promise((resolve, reject) => {
151
+ reader.once("line", resolve);
152
+ reader.once("SIGINT", () => {
153
+ reject(new AlreadyReportedError(signalExitCode("SIGINT")));
154
+ });
155
+ reader.once("close", () => {
156
+ reject(new UsageError(NOTHING_READ));
157
+ });
158
+ });
159
+ }
160
+ finally {
161
+ reader.close();
162
+ process.stderr.write("\n");
163
+ }
164
+ }
package/dist/failure.js CHANGED
@@ -1,6 +1,7 @@
1
- import { recoveryForCode } from "./error-codes.js";
2
- import { AlreadyReportedError, printError, } from "./output.js";
1
+ import { recoveryForCode } from "clockify-sdk-ts-115/error-codes";
2
+ import { AlreadyReportedError, printError, UsageError, } from "./output.js";
3
3
  import { failureStatus, writeFailure } from "./write-outcome.js";
4
+ export { UsageError } from "./output.js";
4
5
  export class LookupError extends Error {
5
6
  lookupState;
6
7
  constructor(lookupState, message) {
@@ -8,12 +9,6 @@ export class LookupError extends Error {
8
9
  this.lookupState = lookupState;
9
10
  }
10
11
  }
11
- export class UsageError extends Error {
12
- constructor(message) {
13
- super(message);
14
- this.name = "UsageError";
15
- }
16
- }
17
12
  export class PartialDeleteError extends Error {
18
13
  completedStage;
19
14
  next;
@@ -63,7 +58,7 @@ export async function reportFailure(err, output, failedCommand) {
63
58
  return 2;
64
59
  }
65
60
  if (err instanceof AlreadyReportedError)
66
- return 1;
61
+ return err.exitCode;
67
62
  if (err instanceof UsageError && (!write || write.stage === "before_dispatch")) {
68
63
  printError(err.message, output, undefined, usage(failedCommand), undefined, write);
69
64
  return 2;
package/dist/flags.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { InvalidArgumentError } from "commander";
2
2
  import { UsageError } from "./failure.js";
3
- const OUTPUT_MODES = ["table", "json", "ndjson"];
3
+ export const OUTPUT_MODES = ["table", "json", "ndjson", "csv"];
4
4
  export function colorEnabled(colorFlag, stream, env = process.env) {
5
5
  if (colorFlag === false)
6
6
  return false;
@@ -15,9 +15,9 @@ export function resolveFlags(program) {
15
15
  const opts = program.opts();
16
16
  const jsonShaping = opts.select !== undefined || opts.compact === true;
17
17
  let mode = resolveMode(opts.output, opts.json);
18
- if (jsonShaping && mode === "table") {
19
- if (opts.output === "table") {
20
- throw new UsageError("--select and --compact shape JSON output; use them with --output json or ndjson, not --output table.");
18
+ if (jsonShaping && (mode === "table" || mode === "csv")) {
19
+ if (opts.output !== undefined) {
20
+ throw new UsageError(`--select and --compact shape JSON output; use them with --output json or ndjson, not --output ${mode}.`);
21
21
  }
22
22
  mode = "json";
23
23
  }
@@ -26,6 +26,8 @@ export function resolveFlags(program) {
26
26
  resolved.compact = true;
27
27
  if (opts.select !== undefined)
28
28
  resolved.select = opts.select;
29
+ if (opts.fields !== undefined)
30
+ resolved.fields = opts.fields;
29
31
  return resolved;
30
32
  }
31
33
  export function resolveFlagsSafe(program) {
@@ -59,6 +61,12 @@ function resolveMode(output, json) {
59
61
  }
60
62
  return match;
61
63
  }
64
+ export function parseFields(value) {
65
+ const fields = value.split(",").map((field) => field.trim()).filter(Boolean);
66
+ if (fields.length === 0)
67
+ throw new InvalidArgumentError("Provide at least one field name.");
68
+ return fields;
69
+ }
62
70
  export function globalFlags(program) {
63
71
  const opts = program.opts();
64
72
  const out = {};
@@ -70,5 +78,7 @@ export function globalFlags(program) {
70
78
  out.region = opts.region;
71
79
  if (opts.subdomain)
72
80
  out.subdomain = opts.subdomain;
81
+ if (opts.profile)
82
+ out.profile = opts.profile;
73
83
  return out;
74
84
  }
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = "6.0.0";
1
+ export const PACKAGE_VERSION = "8.0.0";
package/dist/index.js CHANGED
@@ -7,6 +7,8 @@ import { isClosedPipeError } from "./closed-pipe.js";
7
7
  import { registerApiCommand } from "./commands/api.js";
8
8
  import { registerApprovalsCommand } from "./commands/approvals.js";
9
9
  import { registerAuditLogCommand } from "./commands/auditlog.js";
10
+ import { registerAuthCommand } from "./commands/auth.js";
11
+ import { registerBatchCommand } from "./commands/batch.js";
10
12
  import { registerClientsCommand } from "./commands/clients.js";
11
13
  import { registerDoctorCommand } from "./commands/doctor.js";
12
14
  import { registerEntriesCommand } from "./commands/entries.js";
@@ -14,10 +16,13 @@ import { registerExpensesCommand } from "./commands/expenses.js";
14
16
  import { registerInvoicesCommand } from "./commands/invoices.js";
15
17
  import { leafCommand } from "./commands/leaf-command.js";
16
18
  import { registerLogCommand } from "./commands/log.js";
19
+ import { registerCommandsCommand } from "./commands/manifest.js";
20
+ import { registerOperationsCommand } from "./commands/operations.js";
17
21
  import { registerProjectsCommand } from "./commands/projects.js";
18
22
  import { registerReportsCommand } from "./commands/reports.js";
19
23
  import { registerSchedulingCommand } from "./commands/scheduling.js";
20
24
  import { registerSharedReportsCommand } from "./commands/sharedReports.js";
25
+ import { registerSkillCommand } from "./commands/skill.js";
21
26
  import { registerStartCommand } from "./commands/start.js";
22
27
  import { registerStatusCommand } from "./commands/status.js";
23
28
  import { registerStopCommand } from "./commands/stop.js";
@@ -27,12 +32,12 @@ import { registerTimeOffCommand } from "./commands/timeoff.js";
27
32
  import { registerUsersCommand } from "./commands/users.js";
28
33
  import { registerWebhooksCommand } from "./commands/webhooks.js";
29
34
  import { COMPLETION_SHELLS, parseCompletionShell, renderCompletion } from "./completions.js";
30
- import { loadConfig } from "./config.js";
35
+ import { loadConfig, requireProfileName } from "./config.js";
31
36
  import { reportFailure } from "./failure.js";
32
- import { parseOutputMode, resolveFlags, resolveFlagsSafe } from "./flags.js";
37
+ import { parseFields, parseOutputMode, resolveFlags, resolveFlagsSafe } from "./flags.js";
33
38
  import { PACKAGE_VERSION } from "./generated/version.js";
34
- import { printJson } from "./output.js";
35
- export { globalFlags, resolveFlags } from "./flags.js";
39
+ import { printData } from "./output.js";
40
+ import { outputWasAbandoned, writeFilesInFull } from "./stdout.js";
36
41
  const defaultServices = {
37
42
  loadConfig,
38
43
  buildClient,
@@ -47,13 +52,18 @@ export function buildProgram(services = defaultServices) {
47
52
  .option("--base-url <url>", "Override Clockify API base URL (or CLOCKIFY_BASE_URL env var). Only a Clockify host or a loopback host is accepted; arbitrary hosts are rejected.")
48
53
  .option("--region <name>", "Clockify routing region: global, eu, us, uk, au, or developer (or CLOCKIFY_REGION env var). Mutually exclusive with --base-url.")
49
54
  .option("--subdomain <label>", "Workspace subdomain for reports routing; requires --region eu/us/uk/au (or CLOCKIFY_SUBDOMAIN env var).")
55
+ .option("--profile <name>", "Profile from `clk115 auth login` (or CLOCKIFY_PROFILE env var).", requireProfileName)
50
56
  .option("--json", "Emit machine-readable JSON instead of human-friendly tables.", false)
51
- .option("--output <mode>", "Output mode: table, json, or ndjson.", parseOutputMode)
57
+ .option("--output <mode>", "Output mode: table, json, ndjson, or csv.", parseOutputMode)
58
+ .option("--fields <list>", "Comma-separated fields to print, in that order; dots reach nested fields.", parseFields)
52
59
  .option("--compact", "Print compact JSON without indentation (implies --output json).", false)
53
60
  .option("--select <path>", "Select a dot-path before printing JSON or NDJSON (implies --output json).")
54
61
  .option("--no-color", "Disable ANSI color output (NO_COLOR and FORCE_COLOR are also honored).");
55
62
  registerApiCommand(program, services);
63
+ registerOperationsCommand(program, services);
64
+ registerBatchCommand(program, services);
56
65
  registerStatusCommand(program, services);
66
+ registerAuthCommand(program, services);
57
67
  registerDoctorCommand(program, services);
58
68
  registerStartCommand(program, services);
59
69
  registerStopCommand(program, services);
@@ -73,6 +83,8 @@ export function buildProgram(services = defaultServices) {
73
83
  registerSharedReportsCommand(program, services);
74
84
  registerUsersCommand(program, services);
75
85
  registerApprovalsCommand(program, services);
86
+ registerCommandsCommand(program, services);
87
+ registerSkillCommand(program, services);
76
88
  leafCommand(program, "completion", "read")
77
89
  .addArgument(new Argument("[shell]", "Shell to generate completion for: zsh, bash, or fish.")
78
90
  .choices(COMPLETION_SHELLS)
@@ -85,10 +97,10 @@ export function buildProgram(services = defaultServices) {
85
97
  .action((shell) => {
86
98
  const output = resolveFlags(program);
87
99
  const script = renderCompletion(parseCompletionShell(shell), program);
88
- if (output.mode === "table")
89
- console.log(script);
100
+ if (output.mode === "json" || output.mode === "ndjson")
101
+ printData(script, output);
90
102
  else
91
- printJson(script, output);
103
+ console.log(script);
92
104
  });
93
105
  return program;
94
106
  }
@@ -127,15 +139,26 @@ function isDirectInvocation(argv1) {
127
139
  return false;
128
140
  }
129
141
  }
142
+ function leaveAfterStderr() {
143
+ const leave = () => {
144
+ process.exit();
145
+ };
146
+ process.stderr.write("", leave);
147
+ setTimeout(leave, 3000);
148
+ }
130
149
  if (isDirectInvocation(process.argv[1])) {
131
- for (const stream of [process.stdout, process.stderr]) {
132
- stream.on("error", (err) => {
133
- if (!isClosedPipeError(err))
134
- throw err;
135
- });
136
- }
150
+ writeFilesInFull();
151
+ process.stderr.on("error", () => undefined);
152
+ process.stdout.on("error", (err) => {
153
+ if (isClosedPipeError(err) || process.exitCode === 1)
154
+ return;
155
+ console.error(`fatal: the output could not be written: ${err.message}`);
156
+ process.exitCode = 1;
157
+ });
137
158
  main(process.argv).then((code) => {
138
- process.exitCode = code;
159
+ process.exitCode ||= code;
160
+ if (outputWasAbandoned())
161
+ leaveAfterStderr();
139
162
  }, (err) => {
140
163
  console.error(`fatal: ${err instanceof Error ? err.message : String(err)}`);
141
164
  process.exitCode = 1;
@@ -0,0 +1,28 @@
1
+ import { constants } from "node:os";
2
+ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
3
+ const UNREAD_OUTPUT_MS = 1000;
4
+ export const signalExitCode = (signal) => 128 + constants.signals[signal];
5
+ export function watchInterrupts(onStop, onQuit) {
6
+ let exitCode;
7
+ const abandoned = new AbortController();
8
+ const release = () => {
9
+ for (const signal of SIGNALS)
10
+ process.off(signal, handle);
11
+ };
12
+ const handle = (signal) => {
13
+ if (exitCode === undefined) {
14
+ exitCode = signalExitCode(signal);
15
+ onStop();
16
+ }
17
+ else if (signal !== "SIGHUP") {
18
+ release();
19
+ onQuit();
20
+ setTimeout(() => {
21
+ abandoned.abort();
22
+ }, UNREAD_OUTPUT_MS).unref();
23
+ }
24
+ };
25
+ for (const signal of SIGNALS)
26
+ process.on(signal, handle);
27
+ return { exitCode: () => exitCode, abandoned: abandoned.signal, release };
28
+ }