@apet97/clockify-cli-115 5.0.4 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +255 -39
  2. package/dist/client.js +43 -17
  3. package/dist/closed-pipe.js +3 -0
  4. package/dist/commands/api.js +192 -103
  5. package/dist/commands/approvals.js +9 -10
  6. package/dist/commands/auditlog.js +11 -8
  7. package/dist/commands/auth.js +229 -0
  8. package/dist/commands/balanceAssignment.js +10 -8
  9. package/dist/commands/batch.js +226 -0
  10. package/dist/commands/clients.js +27 -72
  11. package/dist/commands/doctor.js +98 -82
  12. package/dist/commands/entries.js +29 -14
  13. package/dist/commands/expenses.js +75 -36
  14. package/dist/commands/helpers.js +74 -9
  15. package/dist/commands/invoices.js +12 -16
  16. package/dist/commands/leaf-command.js +15 -0
  17. package/dist/commands/log.js +4 -2
  18. package/dist/commands/manifest.js +63 -0
  19. package/dist/commands/operations.js +271 -0
  20. package/dist/commands/projects.js +28 -32
  21. package/dist/commands/reports.js +54 -21
  22. package/dist/commands/resolve-refs.js +30 -53
  23. package/dist/commands/scheduling.js +94 -40
  24. package/dist/commands/shared-report-body.js +127 -0
  25. package/dist/commands/sharedReports.js +19 -235
  26. package/dist/commands/skill.js +85 -0
  27. package/dist/commands/start.js +6 -4
  28. package/dist/commands/status.js +69 -27
  29. package/dist/commands/stop.js +7 -18
  30. package/dist/commands/tags.js +11 -11
  31. package/dist/commands/tasks.js +27 -133
  32. package/dist/commands/timeoff.js +23 -16
  33. package/dist/commands/users.js +11 -19
  34. package/dist/commands/webhook-delivery.js +331 -0
  35. package/dist/commands/webhooks.js +40 -104
  36. package/dist/completions.js +291 -55
  37. package/dist/config.js +168 -61
  38. package/dist/credentials.js +164 -0
  39. package/dist/duration.js +5 -4
  40. package/dist/failure.js +82 -0
  41. package/dist/flags.js +84 -0
  42. package/dist/generated/version.js +1 -1
  43. package/dist/index.js +68 -108
  44. package/dist/interrupts.js +28 -0
  45. package/dist/output.js +189 -66
  46. package/dist/receipt.js +2 -10
  47. package/dist/stdin.js +6 -0
  48. package/dist/stdout.js +38 -0
  49. package/dist/write-outcome.js +84 -0
  50. package/package.json +6 -4
  51. package/plugin/.claude-plugin/plugin.json +16 -0
  52. package/plugin/skills/clockify-cli/SKILL.md +88 -0
  53. package/plugin/skills/clockify-mcp/SKILL.md +48 -0
  54. package/plugin/skills/clockify-sdk/SKILL.md +85 -0
  55. package/dist/error-codes.js +0 -272
@@ -1,67 +1,303 @@
1
- export const COMMANDS = [
2
- "api",
3
- "status",
4
- "doctor",
5
- "start",
6
- "stop",
7
- "log",
8
- "entries",
9
- "projects",
10
- "clients",
11
- "tasks",
12
- "tags",
13
- "webhooks",
14
- "invoices",
15
- "expenses",
16
- "timeoff",
17
- "scheduling",
18
- "audit-log",
19
- "reports",
20
- "shared-reports",
21
- "users",
22
- "approvals",
23
- "completion",
24
- "help",
25
- ];
26
- export function renderCompletion(shell) {
27
- const commands = COMMANDS.join(" ");
1
+ import { InvalidArgumentError } from "commander";
2
+ import { KNOWN_REGIONS } from "./client.js";
3
+ import { TIME_VIEW_MODES } from "./commands/helpers.js";
4
+ import { OUTPUT_MODES } from "./flags.js";
5
+ export const COMPLETION_SHELLS = ["zsh", "bash", "fish"];
6
+ const BINARIES = ["clk115", "clockify115"];
7
+ const FLAG_VALUES = {
8
+ "--output": OUTPUT_MODES,
9
+ "--region": KNOWN_REGIONS,
10
+ "--time-view-mode": TIME_VIEW_MODES,
11
+ };
12
+ export function parseCompletionShell(value) {
13
+ const shell = (value ?? "zsh").toLowerCase();
14
+ const match = COMPLETION_SHELLS.find((candidate) => candidate === shell);
15
+ if (match === undefined) {
16
+ throw new InvalidArgumentError(`completion shell must be one of: ${COMPLETION_SHELLS.join(", ")}`);
17
+ }
18
+ return match;
19
+ }
20
+ export function renderCompletion(shell, program) {
21
+ const nodes = collectNodes(program);
28
22
  if (shell === "zsh")
29
- return renderZsh(commands);
23
+ return renderZsh(nodes);
30
24
  if (shell === "bash")
31
- return renderBash(commands);
32
- return renderFish();
25
+ return renderBash(nodes);
26
+ return renderFish(nodes);
33
27
  }
34
- export function parseCompletionShell(value) {
35
- const shell = (value ?? "zsh").toLowerCase();
36
- if (shell === "bash" || shell === "zsh" || shell === "fish")
37
- return shell;
38
- throw new Error("completion shell must be one of: bash, zsh, fish");
28
+ function oneLine(text) {
29
+ return (text.split("\n")[0] ?? "").replace(/\s+/g, " ").trim();
30
+ }
31
+ function toFlag(option) {
32
+ const names = [option.long, option.short].filter((name) => name != null);
33
+ const long = option.long ?? "";
34
+ return {
35
+ names,
36
+ description: oneLine(option.description),
37
+ takesValue: option.required || option.optional,
38
+ values: option.argChoices ?? FLAG_VALUES[long] ?? [],
39
+ };
40
+ }
41
+ const HELP_FLAG = {
42
+ names: ["--help", "-h"],
43
+ description: "display help for command",
44
+ takesValue: false,
45
+ values: [],
46
+ };
47
+ export function collectNodes(program) {
48
+ const nodes = [];
49
+ const visit = (command, path) => {
50
+ const isRoot = path.length === 0;
51
+ const subcommands = command.commands.map((child) => ({
52
+ name: child.name(),
53
+ description: oneLine(child.description()),
54
+ }));
55
+ if (isRoot)
56
+ subcommands.push({ name: "help", description: "display help for command" });
57
+ const flags = command.options.filter((option) => !option.hidden).map(toFlag);
58
+ if (isRoot) {
59
+ flags.push({
60
+ names: ["--version", "-V"],
61
+ description: "output the version number",
62
+ takesValue: false,
63
+ values: [],
64
+ });
65
+ }
66
+ flags.push(HELP_FLAG);
67
+ nodes.push({
68
+ path: path.join(" "),
69
+ subcommands,
70
+ flags: dedupeFlags(flags),
71
+ argumentValues: command.registeredArguments[0]?.argChoices ?? [],
72
+ });
73
+ for (const child of command.commands)
74
+ visit(child, [...path, child.name()]);
75
+ };
76
+ visit(program, []);
77
+ return nodes;
78
+ }
79
+ function dedupeFlags(flags) {
80
+ const seen = new Set();
81
+ return flags.filter((flag) => {
82
+ const key = flag.names[0] ?? "";
83
+ if (seen.has(key))
84
+ return false;
85
+ seen.add(key);
86
+ return true;
87
+ });
88
+ }
89
+ function flagsFor(node, root) {
90
+ return node === root ? node.flags : dedupeFlags([...node.flags, ...root.flags]);
91
+ }
92
+ function rootOf(nodes) {
93
+ const root = nodes.find((node) => node.path === "");
94
+ if (root === undefined)
95
+ throw new Error("completion tree has no root node");
96
+ return root;
97
+ }
98
+ function valueFlagNames(nodes) {
99
+ const names = new Set();
100
+ for (const node of nodes) {
101
+ for (const flag of node.flags) {
102
+ if (flag.takesValue)
103
+ for (const name of flag.names)
104
+ names.add(name);
105
+ }
106
+ }
107
+ return [...names].sort();
108
+ }
109
+ function flagValueTable(nodes) {
110
+ const byName = new Map();
111
+ for (const node of nodes) {
112
+ for (const flag of node.flags) {
113
+ if (flag.values.length === 0)
114
+ continue;
115
+ for (const name of flag.names)
116
+ byName.set(name, flag.values);
117
+ }
118
+ }
119
+ return [...byName].map(([name, values]) => ({ names: [name], values: [...values] }));
120
+ }
121
+ function shQuote(text) {
122
+ return `'${text.replaceAll("'", "'\\''")}'`;
123
+ }
124
+ function posixPathWalk(nodes, first, wordAt, limit) {
125
+ const paths = nodes.filter((node) => node.path !== "").map((node) => shQuote(node.path));
126
+ const valueFlags = valueFlagNames(nodes).map(shQuote).join("|");
127
+ return ` local cmdpath="" candidate word skip=0 i
128
+ for (( i = ${first}; i < ${limit}; i++ )); do
129
+ word="${wordAt}"
130
+ if (( skip )); then skip=0; continue; fi
131
+ case "$word" in
132
+ ${valueFlags}) skip=1; continue ;;
133
+ -*) continue ;;
134
+ esac
135
+ candidate="\${cmdpath:+$cmdpath }$word"
136
+ case "$candidate" in
137
+ ${paths.join("|")}) cmdpath="$candidate" ;;
138
+ esac
139
+ done`;
140
+ }
141
+ function renderBash(nodes) {
142
+ const root = rootOf(nodes);
143
+ const words = (items) => shQuote(items.join(" "));
144
+ const nodeCases = nodes
145
+ .map((node) => {
146
+ const commands = [...node.subcommands.map((sub) => sub.name), ...node.argumentValues];
147
+ const flags = flagsFor(node, root).flatMap((flag) => flag.names);
148
+ return ` ${shQuote(node.path)}) subcmds=${words(commands)}; flags=${words(flags)} ;;`;
149
+ })
150
+ .join("\n");
151
+ const valueCases = flagValueTable(nodes)
152
+ .map(({ names, values }) => ` ${names.map(shQuote).join("|")}) values=${words(values)} ;;`)
153
+ .join("\n");
154
+ const valueFlags = valueFlagNames(nodes).map(shQuote).join("|");
155
+ return `# bash completion for clk115 / clockify115.
156
+ # Generated by @apet97/clockify-cli-115 from its command tree.
157
+ _clk115_completion() {
158
+ local cur="\${COMP_WORDS[COMP_CWORD]}" prev="" subcmds="" flags="" values=""
159
+ if (( COMP_CWORD > 0 )); then prev="\${COMP_WORDS[COMP_CWORD-1]}"; fi
160
+ ${posixPathWalk(nodes, 1, "${COMP_WORDS[i]}", "COMP_CWORD")}
161
+ case "$prev" in
162
+ ${valueCases}
163
+ ${valueFlags}) COMPREPLY=(); return 0 ;;
164
+ esac
165
+ if [[ -n "$values" ]]; then
166
+ COMPREPLY=( $(compgen -W "$values" -- "$cur") )
167
+ return 0
168
+ fi
169
+ case "$cmdpath" in
170
+ ${nodeCases}
171
+ esac
172
+ if [[ "$cur" == -* ]]; then
173
+ COMPREPLY=( $(compgen -W "$flags" -- "$cur") )
174
+ else
175
+ COMPREPLY=( $(compgen -W "$subcmds" -- "$cur") )
176
+ fi
177
+ }
178
+ ${BINARIES.map((binary) => `complete -o default -F _clk115_completion ${binary}`).join("\n")}
179
+ `;
39
180
  }
40
- function renderZsh(commands) {
41
- return `#compdef clk115 clockify115
42
- # Generated by @apet97/clockify-cli-115.
181
+ function renderZsh(nodes) {
182
+ const root = rootOf(nodes);
183
+ const entry = (name, description) => shQuote(`${name.replaceAll(":", "\\:")}:${description}`);
184
+ const nodeCases = nodes
185
+ .map((node) => {
186
+ const commands = [
187
+ ...node.subcommands.map((sub) => entry(sub.name, sub.description)),
188
+ ...node.argumentValues.map((value) => entry(value, "")),
189
+ ];
190
+ const flags = flagsFor(node, root).flatMap((flag) => flag.names.map((name) => entry(name, flag.description)));
191
+ return ` ${shQuote(node.path)})
192
+ subcmds=(${commands.join(" ")})
193
+ flags=(${flags.join(" ")})
194
+ ;;`;
195
+ })
196
+ .join("\n");
197
+ const valueCases = flagValueTable(nodes)
198
+ .map(({ names, values }) => ` ${names.map(shQuote).join("|")}) compadd -- ${values.map(shQuote).join(" ")}; return ;;`)
199
+ .join("\n");
200
+ const valueFlags = valueFlagNames(nodes).map(shQuote).join("|");
201
+ return `#compdef ${BINARIES.join(" ")}
202
+ # zsh completion for clk115 / clockify115.
203
+ # Generated by @apet97/clockify-cli-115 from its command tree.
43
204
  _clk115() {
44
- local -a commands
45
- commands=(${commands})
46
- _describe 'command' commands
205
+ local -a subcmds flags
206
+ ${posixPathWalk(nodes, 2, "${words[i]}", "CURRENT")}
207
+ case "\${words[CURRENT-1]}" in
208
+ ${valueCases}
209
+ ${valueFlags}) _files; return ;;
210
+ esac
211
+ case "$cmdpath" in
212
+ ${nodeCases}
213
+ esac
214
+ if [[ "\${words[CURRENT]}" == -* ]]; then
215
+ _describe -t options 'option' flags
216
+ else
217
+ _describe -t commands 'command' subcmds
218
+ fi
47
219
  }
48
- compdef _clk115 clk115
49
- compdef _clk115 clockify115
220
+ # Works both ways: autoloaded from $fpath (the file body IS the function, so
221
+ # run it), or sourced from ~/.zshrc (register it for both binaries).
222
+ if [[ "\${funcstack[1]}" == "_clk115" ]]; then
223
+ _clk115 "$@"
224
+ else
225
+ ${BINARIES.map((binary) => ` compdef _clk115 ${binary}`).join("\n")}
226
+ fi
50
227
  `;
51
228
  }
52
- function renderBash(commands) {
53
- return `_clk115_completion() {
54
- local cur
55
- cur="\${COMP_WORDS[COMP_CWORD]}"
56
- COMPREPLY=( $(compgen -W "${commands}" -- "$cur") )
229
+ function fishQuote(text) {
230
+ return `'${text.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
57
231
  }
58
- complete -F _clk115_completion clk115
59
- complete -F _clk115_completion clockify115
232
+ function renderFish(nodes) {
233
+ const root = rootOf(nodes);
234
+ const paths = nodes.filter((node) => node.path !== "").map((node) => fishQuote(node.path));
235
+ const valueFlags = valueFlagNames(nodes).map(fishQuote).join(" ");
236
+ const lines = [];
237
+ for (const binary of BINARIES) {
238
+ lines.push(`complete -c ${binary} -f`);
239
+ for (const node of nodes) {
240
+ const at = `-n ${fishQuote(`__clk115_at ${fishQuote(node.path)}`)}`;
241
+ for (const sub of node.subcommands) {
242
+ lines.push(`complete -c ${binary} ${at} -a ${fishQuote(sub.name)} -d ${fishQuote(sub.description)}`);
243
+ }
244
+ if (node.argumentValues.length > 0) {
245
+ lines.push(`complete -c ${binary} ${at} -a ${fishQuote(node.argumentValues.join(" "))}`);
246
+ }
247
+ for (const flag of node.flags) {
248
+ const condition = node === root ? "" : `${at} `;
249
+ if (node !== root && root.flags.some((global) => global.names[0] === flag.names[0])) {
250
+ continue;
251
+ }
252
+ lines.push(`complete -c ${binary} ${condition}${fishFlag(flag)}`);
253
+ }
254
+ }
255
+ }
256
+ return `# fish completion for clk115 / clockify115.
257
+ # Generated by @apet97/clockify-cli-115 from its command tree.
258
+ function __clk115_path
259
+ set -l tokens (commandline -opc)
260
+ set -e tokens[1]
261
+ set -l cmdpath
262
+ set -l skip 0
263
+ for token in $tokens
264
+ if test $skip -eq 1
265
+ set skip 0
266
+ continue
267
+ end
268
+ if contains -- $token ${valueFlags}
269
+ set skip 1
270
+ continue
271
+ end
272
+ if string match -q -- '-*' $token
273
+ continue
274
+ end
275
+ set -l candidate (string join ' ' $cmdpath $token)
276
+ if contains -- "$candidate" ${paths.join(" ")}
277
+ set cmdpath $cmdpath $token
278
+ end
279
+ end
280
+ string join ' ' $cmdpath
281
+ end
282
+ function __clk115_at
283
+ set -l current (__clk115_path)
284
+ test "$current" = "$argv[1]"
285
+ end
286
+ ${lines.join("\n")}
60
287
  `;
61
288
  }
62
- function renderFish() {
63
- return COMMANDS.map((command) => `complete -c clk115 -f -a ${command}`).join("\n") +
64
- "\n" +
65
- COMMANDS.map((command) => `complete -c clockify115 -f -a ${command}`).join("\n") +
66
- "\n";
289
+ function fishFlag(flag) {
290
+ const parts = [];
291
+ for (const name of flag.names) {
292
+ parts.push(name.startsWith("--") ? `-l ${name.slice(2)}` : `-s ${name.slice(1)}`);
293
+ }
294
+ if (flag.values.length > 0) {
295
+ parts.push(`-x -a ${fishQuote(flag.values.join(" "))}`);
296
+ }
297
+ else if (flag.takesValue) {
298
+ parts.push("-r");
299
+ }
300
+ if (flag.description)
301
+ parts.push(`-d ${fishQuote(flag.description)}`);
302
+ return parts.join(" ");
67
303
  }
package/dist/config.js CHANGED
@@ -1,7 +1,12 @@
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}$/;
9
+ const SECRET_RC_FILE_KEY = /api[-_]?key|token|secret|password|credential/i;
5
10
  function editDistance(left, right) {
6
11
  let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
7
12
  for (let leftIndex = 0; leftIndex < left.length; leftIndex += 1) {
@@ -14,42 +19,113 @@ function editDistance(left, right) {
14
19
  }
15
20
  return previous[right.length];
16
21
  }
17
- function nearestRcFileKey(input) {
18
- const normalized = input.toLowerCase();
19
- let nearest = KNOWN_RC_FILE_KEYS[0];
20
- let smallestDistance = editDistance(normalized, nearest.toLowerCase());
21
- for (const candidate of KNOWN_RC_FILE_KEYS.slice(1)) {
22
- const distance = editDistance(normalized, candidate.toLowerCase());
23
- if (distance < smallestDistance) {
24
- nearest = candidate;
25
- smallestDistance = distance;
26
- }
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`);
27
31
  }
28
- 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);
29
61
  }
30
62
  export function loadConfig(flags = {}, env = process.env) {
31
63
  const file = loadRcFile(env);
32
64
  const apiKey = firstPresent(env.CLOCKIFY_API_KEY);
33
- const workspaceId = firstPresent(flags.workspace, env.CLOCKIFY_WORKSPACE_ID, file.workspaceId);
34
- const baseUrl = firstPresent(flags.baseUrl, env.CLOCKIFY_BASE_URL, file.baseUrl);
35
- const region = firstPresent(flags.region, env.CLOCKIFY_REGION, file.region);
36
- const subdomain = firstPresent(flags.subdomain, env.CLOCKIFY_SUBDOMAIN, file.subdomain);
37
- return {
38
- ...(apiKey !== undefined ? { apiKey } : {}),
39
- ...(workspaceId !== undefined ? { workspaceId } : {}),
40
- ...(baseUrl !== undefined ? { baseUrl } : {}),
41
- ...(region !== undefined ? { region } : {}),
42
- ...(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 }),
43
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 };
44
121
  }
45
122
  function firstPresent(...values) {
46
123
  return values.find((value) => typeof value === "string" && value.trim().length > 0);
47
124
  }
48
- export function requireApiKey(config) {
49
- if (!config.apiKey) {
50
- throw new Error("Clockify API key not set. Set CLOCKIFY_API_KEY in the process environment.");
51
- }
52
- 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}\`.`);
53
129
  }
54
130
  export function requireWorkspaceId(config) {
55
131
  if (!config.workspaceId) {
@@ -57,38 +133,69 @@ export function requireWorkspaceId(config) {
57
133
  }
58
134
  return config.workspaceId;
59
135
  }
60
- function loadRcFile(env) {
61
- const root = env.CLOCKIFY_HOME ?? homedir();
136
+ function rcFilePath(env) {
137
+ const root = firstPresent(env.CLOCKIFY_HOME) ?? homedir();
62
138
  const candidates = [join(root, "clockifyrc.json"), join(root, ".clockifyrc.json")];
63
- for (const path of candidates) {
64
- if (!existsSync(path)) {
65
- continue;
66
- }
67
- let parsed = {};
68
- try {
69
- const raw = readFileSync(path, "utf8");
70
- parsed = JSON.parse(raw);
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 (Object.prototype.hasOwnProperty.call(parsed, "apiKey")) {
77
- throw new Error("legacy rc-file secret detected: remove apiKey from the rc file and set CLOCKIFY_API_KEY in the process environment");
78
- }
79
- for (const key of Object.keys(parsed)) {
80
- if (KNOWN_RC_FILE_KEYS.includes(key))
81
- continue;
82
- const suggestion = nearestRcFileKey(key);
83
- process.stderr.write(`WARN clk115: ignoring unknown rc-file key ${JSON.stringify(key)}. Did you mean ${JSON.stringify(suggestion)}?\n`);
84
- }
85
- const out = {};
86
- for (const key of KNOWN_RC_FILE_KEYS) {
87
- const value = parsed[key];
88
- if (typeof value === "string")
89
- out[key] = value;
90
- }
91
- 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}`);
149
+ }
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`);
92
152
  }
93
- return {};
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
+ };
94
201
  }