@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,66 +1,47 @@
1
1
  import { iterAll } from "clockify-sdk-ts-115/iter";
2
2
  import { looksLikeClockifyId, matchByName } from "clockify-sdk-ts-115/resolve";
3
- function asNamed(rows) {
4
- return rows.map((r) => {
5
- const row = r;
6
- return {
7
- id: row.id ?? "",
8
- name: row.name ?? "",
9
- ...(row.archived !== undefined ? { archived: row.archived } : {}),
10
- };
11
- });
12
- }
13
- function pickIdByName(rows, ref, noun) {
14
- const match = matchByName(asNamed(rows), ref);
15
- if (match.kind === "many") {
16
- throw new Error(`multiple ${noun}s named ${JSON.stringify(ref)}; provide the 24-character id instead`);
17
- }
18
- if (match.kind === "none") {
19
- throw new Error(`${noun} ${JSON.stringify(ref)} not found in workspace`);
20
- }
21
- return match.entity.id;
22
- }
23
- async function collectPaged(fetcher, baseRequest) {
24
- const rows = [];
25
- for await (const row of iterAll(fetcher, baseRequest, { pageSize: 200, maxPages: 1000 })) {
26
- rows.push(row);
3
+ import { LookupError } from "../failure.js";
4
+ async function resolveName(fetcher, baseRequest, ref, noun, projectId) {
5
+ const name = JSON.stringify(ref);
6
+ const scope = projectId === undefined ? "in workspace" : `on project ${projectId}`;
7
+ const options = {
8
+ pageSize: 200,
9
+ maxPages: 1000,
10
+ onTruncated: () => {
11
+ throw new LookupError("capped", `${noun} lookup for ${name} reached the page cap; provide the 24-character id instead`);
12
+ },
13
+ };
14
+ let id;
15
+ for await (const row of iterAll(fetcher, baseRequest, options)) {
16
+ if (!row.id || !row.name)
17
+ continue;
18
+ const candidate = { name: row.name, archived: row.archived === true };
19
+ if (matchByName([candidate], ref).kind === "none")
20
+ continue;
21
+ if (id !== undefined && row.id !== id) {
22
+ const location = projectId === undefined ? "" : ` ${scope}`;
23
+ throw new LookupError("ambiguous", `multiple ${noun}s named ${name}${location}; provide the 24-character id instead`);
24
+ }
25
+ id = row.id;
27
26
  }
28
- return rows;
27
+ if (id === undefined)
28
+ throw new LookupError("not_found", `${noun} ${name} not found ${scope}`);
29
+ return id;
29
30
  }
30
31
  export async function resolveProjectId(client, workspaceId, ref) {
31
32
  if (looksLikeClockifyId(ref))
32
33
  return ref;
33
- const list = await collectPaged(client.projects.list.bind(client.projects), {
34
- workspaceId,
35
- name: ref,
36
- });
37
- return pickIdByName(list, ref, "project");
34
+ return resolveName(client.projects.list.bind(client.projects), { workspaceId, name: ref }, ref, "project");
38
35
  }
39
36
  export async function resolveClientId(client, workspaceId, ref) {
40
37
  if (looksLikeClockifyId(ref))
41
38
  return ref;
42
- const list = await collectPaged(client.clients.list.bind(client.clients), {
43
- workspaceId,
44
- name: ref,
45
- });
46
- return pickIdByName(list, ref, "client");
39
+ return resolveName(client.clients.list.bind(client.clients), { workspaceId, name: ref }, ref, "client");
47
40
  }
48
41
  export async function resolveTaskId(client, workspaceId, projectId, ref) {
49
42
  if (looksLikeClockifyId(ref))
50
43
  return ref;
51
- const list = await collectPaged(client.tasks.list.bind(client.tasks), {
52
- workspaceId,
53
- projectId,
54
- name: ref,
55
- });
56
- const match = matchByName(asNamed(list), ref);
57
- if (match.kind === "many") {
58
- throw new Error(`multiple tasks named ${JSON.stringify(ref)} on project ${projectId}; provide the 24-character id`);
59
- }
60
- if (match.kind === "none") {
61
- throw new Error(`task ${JSON.stringify(ref)} not found on project ${projectId}`);
62
- }
63
- return match.entity.id;
44
+ return resolveName(client.tasks.list.bind(client.tasks), { workspaceId, projectId, name: ref }, ref, "task", projectId);
64
45
  }
65
46
  export async function resolveTagIds(client, workspaceId, refs) {
66
47
  const ids = [];
@@ -69,11 +50,7 @@ export async function resolveTagIds(client, workspaceId, refs) {
69
50
  ids.push(ref);
70
51
  continue;
71
52
  }
72
- const list = await collectPaged(client.tags.list.bind(client.tags), {
73
- workspaceId,
74
- name: ref,
75
- });
76
- ids.push(pickIdByName(list, ref, "tag"));
53
+ ids.push(await resolveName(client.tags.list.bind(client.tags), { workspaceId, name: ref }, ref, "tag"));
77
54
  }
78
55
  return ids;
79
56
  }
@@ -1,7 +1,27 @@
1
- import { AlreadyReportedError, printRecords } from "../output.js";
1
+ import { AlreadyReportedError, printRecords, printWarning } from "../output.js";
2
2
  import { printReceipt } from "../receipt.js";
3
+ import { dispatchedWrite, writeFailure } from "../write-outcome.js";
3
4
  import { clampPageSize, parseFloatArg, parseIntArg, promoteDateBoundary, requireRfc3339Timestamp, resolveContext, } from "./helpers.js";
4
5
  import { leafCommand } from "./leaf-command.js";
6
+ const PUBLISH_SCOPE_WARNING = "Publishing this window includes all other drafts for the same user.";
7
+ async function readPublication(client, window, id) {
8
+ try {
9
+ const rows = await client.scheduling.list(window);
10
+ const row = rows.find((item) => item.id === id);
11
+ return row && "published" in row && typeof row.published === "boolean"
12
+ ? row.published
13
+ : undefined;
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ }
19
+ function identifiedAssignment(rows) {
20
+ const first = Array.isArray(rows) ? rows[0] : undefined;
21
+ if (first === null || typeof first !== "object" || !("id" in first))
22
+ return undefined;
23
+ return typeof first.id === "string" && first.id.trim() !== "" ? first : undefined;
24
+ }
5
25
  export const registerSchedulingCommand = (program, services) => {
6
26
  const scheduling = program
7
27
  .command("scheduling")
@@ -16,11 +36,13 @@ export const registerSchedulingCommand = (program, services) => {
16
36
  .option("--page <n>", "Page number.", parseIntArg, 1)
17
37
  .option("--name <text>", "Filter by assignment name substring.")
18
38
  .action(async function (opts) {
39
+ const start = promoteDateBoundary(opts.from, "from", "start");
40
+ const end = promoteDateBoundary(opts.to, "to", "end");
19
41
  const { client, workspaceId, output } = await resolveContext(this, services);
20
42
  const req = {
21
43
  workspaceId,
22
- start: promoteDateBoundary(opts.from, "from", "start"),
23
- end: promoteDateBoundary(opts.to, "to", "end"),
44
+ start,
45
+ end,
24
46
  page: opts.page,
25
47
  "page-size": clampPageSize(opts.limit, 200),
26
48
  };
@@ -57,7 +79,7 @@ export const registerSchedulingCommand = (program, services) => {
57
79
  .option("--note <text>", "Assignment note.")
58
80
  .option("--billable", "Mark assignment as billable.", false)
59
81
  .option("--include-non-working-days", "Include weekends/non-working days.", false)
60
- .option("--publish", "Publish immediately (default is draft).", false)
82
+ .option("--publish", "Publish all drafts for this user in the start/end window, including other drafts.", false)
61
83
  .action(async function (opts) {
62
84
  const start = requireRfc3339Timestamp(opts.start, "start");
63
85
  const end = requireRfc3339Timestamp(opts.end, "end");
@@ -78,11 +100,13 @@ export const registerSchedulingCommand = (program, services) => {
78
100
  if (opts.includeNonWorkingDays)
79
101
  body.includeNonWorkingDays = true;
80
102
  const req = { workspaceId, body };
81
- const createdList = (await client.scheduling.createRecurring(req));
82
- const created = createdList[0] ?? {};
83
- let published = false;
84
- let publishWarning;
85
- let failedPublishRequest;
103
+ const created = identifiedAssignment(await dispatchedWrite(this, client.scheduling.createRecurring(req)));
104
+ if (created === undefined) {
105
+ throw new Error("Clockify accepted the request, but its response identifies no created assignment. " +
106
+ (opts.publish === true ? "Nothing was published. " : "") +
107
+ `Check the window with: clk115 scheduling list --from ${start} --to ${end} --json`);
108
+ }
109
+ let publication = { kind: "draft" };
86
110
  if (opts.publish === true) {
87
111
  const publishRequest = {
88
112
  start,
@@ -90,58 +114,88 @@ export const registerSchedulingCommand = (program, services) => {
90
114
  userFilter: { contains: "CONTAINS", ids: [opts.user] },
91
115
  };
92
116
  try {
93
- await client.scheduling.publish({ workspaceId, body: publishRequest });
94
- published = true;
117
+ await dispatchedWrite(this, client.scheduling.publish({ workspaceId, body: publishRequest }));
118
+ publication = { kind: "published" };
95
119
  }
96
120
  catch (err) {
97
121
  const detail = err instanceof Error ? err.message : String(err);
98
- publishWarning = `The assignment was created but publishing it failed: ${detail}. It remains an unpublished draft.`;
99
- failedPublishRequest = publishRequest;
122
+ const { classifyWriteOutcome } = await import("clockify-sdk-ts-115/errors");
123
+ const published = classifyWriteOutcome(err) === "definitely-failed"
124
+ ? false
125
+ : await readPublication(client, { workspaceId, start, end }, created.id);
126
+ if (published === undefined) {
127
+ publication = {
128
+ kind: "unknown",
129
+ cause: err,
130
+ warning: `Assignment created. Publication state is unknown after the publish error: ${detail}`,
131
+ };
132
+ }
133
+ else if (published) {
134
+ publication = { kind: "published" };
135
+ }
136
+ else {
137
+ publication = {
138
+ kind: "publish_failed",
139
+ cause: err,
140
+ warning: `The assignment was created but publishing it failed: ${detail}. It remains an unpublished draft.`,
141
+ publishRequest,
142
+ };
143
+ }
100
144
  }
101
145
  }
102
- const data = {
103
- id: created.id ?? "",
146
+ const baseData = {
147
+ id: created.id,
104
148
  user: created.userId ?? "",
105
149
  project: created.projectId ?? "",
106
150
  hoursPerDay: created.hoursPerDay ?? 0,
107
151
  start: created.start ?? created.period?.start ?? start,
108
152
  end: created.end ?? created.period?.end ?? end,
109
- published,
110
- ...(failedPublishRequest
111
- ? {
112
- warningCode: "publish_failed",
113
- publishRequest: failedPublishRequest,
114
- }
115
- : {}),
153
+ published: publication.kind === "unknown" ? "unknown" : publication.kind === "published",
116
154
  };
117
- const recoveryCommand = "clk115 api PUT /workspaces/{workspaceId}/scheduling/assignments/publish --body -";
118
- const recoveryReason = "Pipe the stored publishRequest JSON to stdin to publish the created draft.";
119
- const receiptData = failedPublishRequest
120
- ? { ...data, recoveryCommand, recovery: recoveryReason }
121
- : data;
155
+ const recoveryCommand = publication.kind === "unknown"
156
+ ? `clk115 api GET /workspaces/{workspaceId}/scheduling/assignments/all -q start=${start} -q end=${end} --all`
157
+ : "clk115 api PUT /workspaces/{workspaceId}/scheduling/assignments/publish --body -";
158
+ const recoveryReason = publication.kind === "unknown"
159
+ ? `Check assignment ${baseData.id} before retrying publication.`
160
+ : "Pipe the stored publishRequest JSON to stdin to publish the created draft.";
161
+ const needsRecovery = publication.kind === "publish_failed" || publication.kind === "unknown";
162
+ const warnings = [];
163
+ if ("warning" in publication)
164
+ warnings.push(`${publication.warning} ${PUBLISH_SCOPE_WARNING}`);
165
+ else if (publication.kind === "published")
166
+ warnings.push(PUBLISH_SCOPE_WARNING);
167
+ if (output.mode === "table") {
168
+ for (const warning of warnings)
169
+ printWarning(warning, output);
170
+ }
122
171
  printReceipt({
123
172
  ok: true,
124
173
  action: "scheduling.create",
125
174
  entity: "scheduling_assignment",
126
- ids: { assignmentId: data.id },
127
- data: receiptData,
128
- changed: { created: [{ type: "scheduling_assignment", id: data.id }] },
129
- ...(publishWarning ? { warnings: [publishWarning] } : {}),
130
- next: publishWarning
131
- ? [
132
- {
133
- command: recoveryCommand,
134
- reason: recoveryReason,
135
- },
136
- ]
175
+ ids: { assignmentId: baseData.id },
176
+ data: {
177
+ ...baseData,
178
+ ...(opts.publish && { publishScope: { userId: opts.user, start, end } }),
179
+ ...("cause" in publication && {
180
+ ...await writeFailure(this, publication.cause),
181
+ warningCode: publication.kind === "unknown" ? "publish_unknown" : "publish_failed",
182
+ recoveryCommand,
183
+ recovery: `Read back the assignment before repeating any write. ${recoveryReason}`,
184
+ }),
185
+ ...(publication.kind === "publish_failed" && { publishRequest: publication.publishRequest }),
186
+ },
187
+ changed: { created: [{ type: "scheduling_assignment", id: baseData.id }] },
188
+ warnings,
189
+ next: needsRecovery
190
+ ? [{ command: recoveryCommand, reason: recoveryReason }]
137
191
  : [
138
192
  {
139
- command: `clk115 scheduling list --from ${data.start} --to ${data.end} --json`,
193
+ command: `clk115 scheduling list --from ${baseData.start} --to ${baseData.end} --json`,
140
194
  reason: "Verify the assignment appears.",
141
195
  },
142
196
  ],
143
197
  }, output);
144
- if (failedPublishRequest) {
198
+ if (needsRecovery) {
145
199
  throw new AlreadyReportedError();
146
200
  }
147
201
  });
@@ -0,0 +1,127 @@
1
+ import { defined, SHARED_REPORT_TYPES, } from "clockify-sdk-ts-115/requests";
2
+ import { z } from "zod";
3
+ import { UsageError } from "../failure.js";
4
+ import { SHARED_REPORT_FILTER_EXPORT_TYPES, SUMMARY_GROUPS } from "./sharedReports.js";
5
+ const nonEmptyStringSchema = z
6
+ .string()
7
+ .refine((value) => value.trim() !== "", "must be a non-empty string.");
8
+ const dateStringSchema = nonEmptyStringSchema.refine((value) => !Number.isNaN(Date.parse(value)), "must be a valid date string.");
9
+ const upperCaseString = (value) => typeof value === "string" ? value.toUpperCase() : value;
10
+ const sharedReportTypeSchema = z.preprocess(upperCaseString, z.enum(SHARED_REPORT_TYPES));
11
+ const sharedReportExportTypeSchema = z.preprocess(upperCaseString, z.enum(SHARED_REPORT_FILTER_EXPORT_TYPES));
12
+ const openObjectSchema = z.record(z.string(), z.unknown());
13
+ const INT_MESSAGE = { error: "provide a whole integer" };
14
+ const sharedUsersFilterSchema = z
15
+ .object({
16
+ contains: z.enum(["CONTAINS", "DOES_NOT_CONTAIN", "CONTAINS_ONLY"]).optional(),
17
+ ids: z.array(z.string()).optional(),
18
+ status: z.enum(["ALL", "ACTIVE", "INACTIVE"]).optional(),
19
+ })
20
+ .strict();
21
+ const sharedAttendanceFilterSchema = z
22
+ .object({
23
+ page: z.number().int(INT_MESSAGE).optional(),
24
+ pageSize: z.number().int(INT_MESSAGE).optional(),
25
+ users: sharedUsersFilterSchema.optional(),
26
+ })
27
+ .strict();
28
+ const sharedDetailedFilterSchema = z
29
+ .object({
30
+ auditFilter: openObjectSchema.optional(),
31
+ options: openObjectSchema.optional(),
32
+ page: z.number().int(INT_MESSAGE).optional(),
33
+ pageSize: z.number().int(INT_MESSAGE).optional(),
34
+ sortColumn: nonEmptyStringSchema.optional(),
35
+ sortOrder: z.enum(["ASCENDING", "DESCENDING"]).optional(),
36
+ })
37
+ .strict();
38
+ const sharedSummaryFilterSchema = z
39
+ .object({
40
+ groups: z
41
+ .array(z.enum(SUMMARY_GROUPS))
42
+ .min(1, { error: `provide 1-3 of: ${SUMMARY_GROUPS.join(", ")}` })
43
+ .max(3, { error: `provide at most 3 of: ${SUMMARY_GROUPS.join(", ")}` }),
44
+ sortColumn: nonEmptyStringSchema.optional(),
45
+ })
46
+ .strict();
47
+ const sharedWeeklyFilterSchema = z
48
+ .object({
49
+ group: z.enum(["PROJECT", "USER"]),
50
+ subgroup: z.literal("TIME"),
51
+ })
52
+ .strict();
53
+ const sharedReportFilterSchema = z
54
+ .object({
55
+ attendanceFilter: sharedAttendanceFilterSchema.optional(),
56
+ dateRangeEnd: dateStringSchema,
57
+ dateRangeStart: dateStringSchema,
58
+ detailedFilter: sharedDetailedFilterSchema.optional(),
59
+ exportType: sharedReportExportTypeSchema,
60
+ summaryFilter: sharedSummaryFilterSchema.optional(),
61
+ weeklyFilter: sharedWeeklyFilterSchema.optional(),
62
+ })
63
+ .strict();
64
+ const sharedReportBodySchema = z
65
+ .object({
66
+ filter: sharedReportFilterSchema,
67
+ isPublic: z.boolean().optional(),
68
+ name: nonEmptyStringSchema,
69
+ type: sharedReportTypeSchema,
70
+ })
71
+ .strict();
72
+ function parseFilterJson(raw) {
73
+ if (typeof raw !== "string") {
74
+ throw new UsageError("--filter must be a JSON object.");
75
+ }
76
+ try {
77
+ return JSON.parse(raw);
78
+ }
79
+ catch {
80
+ throw new UsageError(`--filter must be a JSON object, e.g. '{"dateRangeStart":"…","dateRangeEnd":"…"}'`);
81
+ }
82
+ }
83
+ function schemaIssueLabel(issue, operation) {
84
+ const [root, ...path] = issue.path;
85
+ if (root === "filter") {
86
+ return path.length > 0 ? `--filter ${path.join(".")}` : "--filter";
87
+ }
88
+ if (root === "name")
89
+ return "--name";
90
+ if (root === "type")
91
+ return "--type";
92
+ return operation;
93
+ }
94
+ function sharedReportValidationError(error, operation, rawType) {
95
+ const invalidTypeIssue = error.issues.find((issue) => issue.path[0] === "type" && issue.code === "invalid_value");
96
+ if (invalidTypeIssue !== undefined) {
97
+ return new UsageError(`Unknown --type "${String(rawType)}". Provide one of: ${SHARED_REPORT_TYPES.join(", ")}.`);
98
+ }
99
+ const issue = error.issues[0];
100
+ if (issue === undefined)
101
+ return new UsageError(`${operation}: invalid request.`);
102
+ if (issue.path.length === 1 &&
103
+ issue.path[0] === "filter" &&
104
+ issue.code === "invalid_type" &&
105
+ issue.expected === "object") {
106
+ return new UsageError("--filter must be a JSON object.");
107
+ }
108
+ const label = schemaIssueLabel(issue, operation);
109
+ if (issue.code === "unrecognized_keys") {
110
+ const fieldKind = issue.path[0] === "filter" ? "filter field(s)" : "field(s)";
111
+ return new UsageError(`${label} has unknown ${fieldKind}: ${issue.keys.join(", ")}.`);
112
+ }
113
+ return new UsageError(`${label}: ${issue.message}`);
114
+ }
115
+ export function parseSharedReportBody(opts, operation) {
116
+ const candidate = {
117
+ name: opts.name,
118
+ type: opts.type,
119
+ filter: parseFilterJson(opts.filter),
120
+ ...(opts.public !== undefined ? { isPublic: opts.public } : {}),
121
+ };
122
+ const result = sharedReportBodySchema.safeParse(candidate);
123
+ if (!result.success) {
124
+ throw sharedReportValidationError(result.error, operation, opts.type);
125
+ }
126
+ return defined(result.data);
127
+ }