@tuanhv/op-cli 0.3.0 → 0.4.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.
@@ -6,6 +6,7 @@ import { apiGet, apiPost } from "../core/http.js";
6
6
  import { halElements } from "../core/paginate.js";
7
7
  import { OpCliError } from "../core/errors.js";
8
8
  import { ENV_PROFILE_NAME } from "./profile.js";
9
+ import { projectLinksOf, withMovedRetry, WORKSPACES_COLLECTION, } from "./projectref.js";
9
10
  function cacheRoot(env) {
10
11
  const root = env.OP_CLI_CACHE_DIR ??
11
12
  (env.HOME !== undefined ? join(env.HOME, ".cache", "op-cli") : undefined);
@@ -112,6 +113,32 @@ function toStoredCategory(element) {
112
113
  name: asString(element.name),
113
114
  };
114
115
  }
116
+ /**
117
+ * The stable status of a sprint resource: the tail of its status urn
118
+ * ("in_planning"), never the title, which the instance localizes. Shared
119
+ * by the stored vocabulary and the `project sprints` table so both show
120
+ * the same value. An element without a status link yields "".
121
+ */
122
+ export function sprintStatusKey(element) {
123
+ const links = (element._links ?? {});
124
+ const status = asString(links.status?.href);
125
+ return status.slice(status.lastIndexOf(":") + 1);
126
+ }
127
+ function toStoredSprint(element) {
128
+ return {
129
+ id: Number(element.id),
130
+ name: asString(element.name),
131
+ start_date: typeof element.startDate === "string" ? element.startDate : null,
132
+ finish_date: typeof element.finishDate === "string" ? element.finishDate : null,
133
+ status: sprintStatusKey(element),
134
+ };
135
+ }
136
+ function toStoredBucket(element) {
137
+ return {
138
+ id: Number(element.id),
139
+ name: asString(element.name),
140
+ };
141
+ }
115
142
  // Above this size an allowed-values list is noise in the store, not a
116
143
  // usable dropdown; the field keeps working, just without the list.
117
144
  const MAX_ALLOWED_VALUES = 50;
@@ -171,8 +198,8 @@ function customFieldEntries(schema) {
171
198
  continue;
172
199
  }
173
200
  // The schema `type` decides input validation downstream; anything
174
- // beyond Boolean/User/CustomOption stays unmarked and passes through
175
- // as text. A multi-valued field spells its kind "[]Kind".
201
+ // beyond Boolean/User/Formattable/CustomOption stays unmarked and
202
+ // passes through as text. A multi-valued field spells its kind "[]Kind".
176
203
  const kind = asString(property.type).toLowerCase();
177
204
  const single = kind.replace(/^\[\]/, "");
178
205
  const isUser = kind === "user";
@@ -193,24 +220,34 @@ function customFieldEntries(schema) {
193
220
  : {}),
194
221
  ...(kind === "boolean" ? { is_boolean: true } : {}),
195
222
  ...(isUser ? { is_user: true } : {}),
223
+ ...(kind === "formattable" ? { is_formattable: true } : {}),
196
224
  ...(isList ? { is_list: true, allowed_options: options } : {}),
197
225
  ...(kind.startsWith("[]") ? { is_multi: true } : {}),
198
226
  });
199
227
  }
200
228
  return fields;
201
229
  }
202
- async function fetchMembers(profile, projectId) {
230
+ async function fetchMembers(profile, projectId, links) {
203
231
  const filters = encodeURIComponent(JSON.stringify([{ project: { operator: "=", values: [String(projectId)] } }]));
204
- const members = await fetchVocabulary(profile, `/api/v3/memberships?filters=${filters}`, toStoredMember);
232
+ const members = await fetchVocabulary(profile, links?.memberships ?? `/api/v3/memberships?filters=${filters}`, toStoredMember);
205
233
  return sortByName(members);
206
234
  }
207
- async function fetchVersions(profile, projectId) {
208
- const versions = await fetchVocabulary(profile, `/api/v3/projects/${String(projectId)}/versions`, toStoredVersion);
209
- return sortByName(versions);
235
+ /**
236
+ * One name-sorted project collection: the shape every optional source
237
+ * except activities shares, so a new source is a path and a converter.
238
+ * `linked` is the path the project resource gave for it, when it did.
239
+ */
240
+ async function fetchProjectCollection(profile, projectId, collection, convert, linked) {
241
+ return sortByName(await fetchVocabulary(profile, linked ?? `/api/v3/projects/${String(projectId)}/${collection}`, convert));
210
242
  }
211
- async function fetchCategories(profile, projectId) {
212
- const categories = await fetchVocabulary(profile, `/api/v3/projects/${String(projectId)}/categories`, toStoredCategory);
213
- return sortByName(categories);
243
+ /**
244
+ * A collection the project resource has no link for (sprints, backlog
245
+ * buckets). The projects path is tried first; on a 404 the instance may
246
+ * have moved the route under /workspaces/, so that path is tried once
247
+ * before the source counts as unavailable (#57). Any other refusal stands.
248
+ */
249
+ async function fetchUnlinkedCollection(profile, projectId, collection, convert) {
250
+ return withMovedRetry(() => fetchProjectCollection(profile, projectId, collection, convert), () => fetchProjectCollection(profile, projectId, collection, convert, `${WORKSPACES_COLLECTION}/${String(projectId)}/${collection}`));
214
251
  }
215
252
  // The bare schema endpoint builds its values from TimeEntry.new, so its
216
253
  // activity list is never populated. Only the create form (form_embedded)
@@ -240,9 +277,10 @@ async function fetchActivities(profile, projectId) {
240
277
  * the form is asked first. A caller who may not open a create form still
241
278
  * gets every field, just without the options.
242
279
  */
243
- async function fetchTypeSchema(profile, projectId, typeId) {
280
+ async function fetchTypeSchema(profile, projectId, typeId, links) {
244
281
  try {
245
- const form = (await apiPost(profile.instanceUrl, profile.apiKey, `/api/v3/projects/${String(projectId)}/work_packages/form`, { _links: { type: { href: `/api/v3/types/${String(typeId)}` } } }));
282
+ const form = (await apiPost(profile.instanceUrl, profile.apiKey, links?.create_work_package
283
+ ?? `/api/v3/projects/${String(projectId)}/work_packages/form`, { _links: { type: { href: `/api/v3/types/${String(typeId)}` } } }));
246
284
  const embedded = (form._embedded ?? {});
247
285
  const schema = embedded.schema;
248
286
  if (typeof schema === "object" && schema !== null && !Array.isArray(schema)) {
@@ -254,14 +292,39 @@ async function fetchTypeSchema(profile, projectId, typeId) {
254
292
  }
255
293
  return (await apiGet(profile.instanceUrl, profile.apiKey, `/api/v3/work_packages/schemas/${String(projectId)}-${String(typeId)}`));
256
294
  }
257
- async function fetchCustomFields(profile, projectId) {
258
- const typeIds = await fetchVocabulary(profile, `/api/v3/projects/${String(projectId)}/types`, (element) => Number(element.id));
295
+ function versionFieldsOf(schema) {
296
+ const entry = (key) => {
297
+ const property = schema[key];
298
+ if (typeof property !== "object" || property === null) {
299
+ return {};
300
+ }
301
+ const options = (property.options ?? {});
302
+ const multiple = options.multiple === true
303
+ || asString(property.type).startsWith("[]");
304
+ return { [key]: { multiple } };
305
+ };
306
+ const deprecated = Object.entries(schema)
307
+ .filter(([key, property]) => !key.startsWith("_")
308
+ && typeof property === "object"
309
+ && property !== null
310
+ && property.deprecated === true)
311
+ .map(([key]) => key);
312
+ return {
313
+ ...entry("targetVersions"),
314
+ ...entry("observedInVersions"),
315
+ ...(deprecated.length === 0 ? {} : { deprecated }),
316
+ };
317
+ }
318
+ async function fetchTypeSchemas(profile, projectId, links) {
319
+ const typeIds = await fetchVocabulary(profile, links?.types ?? `/api/v3/projects/${String(projectId)}/types`, (element) => Number(element.id));
259
320
  const byType = {};
321
+ const versionFields = {};
260
322
  for (const typeId of typeIds) {
261
- const schema = await fetchTypeSchema(profile, projectId, typeId);
323
+ const schema = await fetchTypeSchema(profile, projectId, typeId, links);
262
324
  byType[String(typeId)] = sortByName(customFieldEntries(schema));
325
+ versionFields[String(typeId)] = versionFieldsOf(schema);
263
326
  }
264
- return byType;
327
+ return { custom_fields: byType, version_fields: versionFields };
265
328
  }
266
329
  async function fetchVocabulary(profile, path, convert) {
267
330
  const elements = [];
@@ -288,12 +351,17 @@ async function fetchInstanceInfo(profile) {
288
351
  fetched_at: new Date().toISOString(),
289
352
  };
290
353
  }
354
+ async function fetchProjectResource(profile, projectId) {
355
+ return (await apiGet(profile.instanceUrl, profile.apiKey, `/api/v3/projects/${String(projectId)}`));
356
+ }
291
357
  async function fetchProjectRef(profile, projectId) {
292
- const project = (await apiGet(profile.instanceUrl, profile.apiKey, `/api/v3/projects/${String(projectId)}`));
358
+ const project = await fetchProjectResource(profile, projectId);
359
+ const links = projectLinksOf(project);
293
360
  return {
294
361
  id: Number(project.id),
295
362
  identifier: asString(project.identifier),
296
363
  name: asString(project.name),
364
+ ...(links === undefined ? {} : { links }),
297
365
  };
298
366
  }
299
367
  export async function fetchStoredMetadata(profile) {
@@ -329,7 +397,7 @@ export async function refreshStoredMetadata(env, profile) {
329
397
  const dropped = [];
330
398
  for (const projectId of Object.keys(previousScoped)) {
331
399
  try {
332
- projectScoped[projectId] = await fetchProjectVocabulary(profile, Number(projectId));
400
+ projectScoped[projectId] = await fetchProjectVocabulary(profile, Number(projectId), next.project?.id === Number(projectId) ? next.project.links : undefined);
333
401
  }
334
402
  catch (error) {
335
403
  // A project deleted on the instance must not wedge the refresh for
@@ -363,22 +431,118 @@ export async function refreshStoredMetadata(env, profile) {
363
431
  }
364
432
  return changes;
365
433
  }
366
- export async function fetchProjectVocabulary(profile, projectId) {
434
+ /**
435
+ * One optional source, read so that a refusal empties it rather than
436
+ * failing the load. Only a 403 or 404 counts as a refusal; a 5xx, a
437
+ * timeout, or a 401 still fails, since an empty list there would hide an
438
+ * outage as "no values".
439
+ */
440
+ async function fetchOptional(source, unavailable, fetch) {
441
+ try {
442
+ return await fetch();
443
+ }
444
+ catch (error) {
445
+ if (error instanceof OpCliError
446
+ && (error.code === "PERMISSION_DENIED" || error.code === "NOT_FOUND")) {
447
+ unavailable[source] = {
448
+ status: error.code === "PERMISSION_DENIED" ? 403 : 404,
449
+ message: error.message,
450
+ };
451
+ return [];
452
+ }
453
+ throw error;
454
+ }
455
+ }
456
+ /**
457
+ * The links of one project resource, read once with its vocabulary. They
458
+ * only steer the paths that follow, so a failed read means "no links" and
459
+ * the fixed paths run; a real refusal surfaces from those requests.
460
+ */
461
+ async function fetchProjectLinks(profile, projectId) {
462
+ try {
463
+ return projectLinksOf(await fetchProjectResource(profile, projectId));
464
+ }
465
+ catch {
466
+ return undefined;
467
+ }
468
+ }
469
+ /**
470
+ * `knownLinks` are links the caller read from this very project resource a
471
+ * moment ago (a refresh has just fetched the default project), which spares
472
+ * a second GET of it.
473
+ */
474
+ export async function fetchProjectVocabulary(profile, projectId, knownLinks) {
475
+ const unavailable = {};
476
+ const links = knownLinks ?? await fetchProjectLinks(profile, projectId);
477
+ // Members come first and stay required: a deleted project answers 404
478
+ // there, which the refresh reads as "drop this project".
479
+ const members = await fetchMembers(profile, projectId, links);
480
+ const versions = await fetchOptional("versions", unavailable, () => fetchProjectCollection(profile, projectId, "versions", toStoredVersion, links?.versions));
481
+ const categories = await fetchOptional("categories", unavailable, () => fetchProjectCollection(profile, projectId, "categories", toStoredCategory, links?.categories));
482
+ const activities = await fetchOptional("activities", unavailable, () => fetchActivities(profile, projectId));
483
+ // A project without the backlogs module answers 404 on both.
484
+ const sprints = await fetchOptional("sprints", unavailable, () => fetchUnlinkedCollection(profile, projectId, "sprints", toStoredSprint));
485
+ const buckets = await fetchOptional("buckets", unavailable, () => fetchUnlinkedCollection(profile, projectId, "backlog_buckets", toStoredBucket));
367
486
  return {
368
487
  project_id: projectId,
369
488
  fetched_at: new Date().toISOString(),
370
- members: await fetchMembers(profile, projectId),
371
- versions: await fetchVersions(profile, projectId),
372
- categories: await fetchCategories(profile, projectId),
373
- activities: await fetchActivities(profile, projectId),
374
- custom_fields: await fetchCustomFields(profile, projectId),
489
+ ...(links === undefined ? {} : { links }),
490
+ members,
491
+ versions,
492
+ categories,
493
+ activities,
494
+ sprints,
495
+ buckets,
496
+ ...(await fetchTypeSchemas(profile, projectId, links)),
497
+ ...(Object.keys(unavailable).length > 0 ? { unavailable } : {}),
375
498
  };
376
499
  }
377
- export async function loadProjectVocabulary(env, profile) {
500
+ /**
501
+ * The entries of one optional source for a command that cannot proceed
502
+ * without them. A source the instance refused fails here with
503
+ * PERMISSION_DENIED naming it, instead of reading as an empty vocabulary
504
+ * where every name misses.
505
+ */
506
+ export function requireVocabulary(vocabulary, source) {
507
+ const refusal = vocabulary.unavailable?.[source];
508
+ if (refusal !== undefined) {
509
+ throw new OpCliError("PERMISSION_DENIED", `The ${source} of project ${String(vocabulary.project_id)} are unavailable`
510
+ + ` to this account (HTTP ${String(refusal.status)}): ${refusal.message}`, "ask a project administrator for the permission or module, then run op-cli meta refresh.", { source, project_id: vocabulary.project_id, status: refusal.status });
511
+ }
512
+ // A store from before a source was captured reads as empty here; the
513
+ // callers that need sprints or buckets refresh such a store first.
514
+ return vocabulary[source] ?? [];
515
+ }
516
+ export function unavailableSources(metadata) {
517
+ const entries = [];
518
+ for (const vocabulary of Object.values(metadata.projectScoped ?? {})) {
519
+ for (const [source, refusal] of Object.entries(vocabulary.unavailable ?? {})) {
520
+ entries.push({
521
+ project_id: vocabulary.project_id,
522
+ source: source,
523
+ status: refusal.status,
524
+ message: refusal.message,
525
+ });
526
+ }
527
+ }
528
+ return entries.sort((a, b) => a.project_id - b.project_id || a.source.localeCompare(b.source));
529
+ }
530
+ /**
531
+ * The vocabulary of the profile's project. A command that cannot work
532
+ * without some optional sources names them in `require`: a store written
533
+ * before a source was captured lacks it (the key is absent, which is not
534
+ * the same as empty), and that one project is re-read once instead of
535
+ * the source reading as "none". Other cached projects are left alone.
536
+ */
537
+ export async function loadProjectVocabulary(env, profile, options = {}) {
378
538
  if (profile.project === undefined) {
379
- throw new OpCliError("USAGE_ERROR", "the lookup needs a project to read its vocabulary from.", "pass --project <id> or set a default project on the profile.");
539
+ throw new OpCliError("USAGE_ERROR", "the lookup needs a project to read its vocabulary from.", "pass --project <id> (or --workspace) or set a default project on the profile.");
380
540
  }
381
- return loadProjectVocabularyById(env, profile, profile.project);
541
+ const vocabulary = await loadProjectVocabularyById(env, profile, profile.project);
542
+ const stale = (options.require ?? []).some((source) => vocabulary[source] === undefined);
543
+ return stale
544
+ ? refreshProjectVocabulary(env, profile, profile.project)
545
+ : vocabulary;
382
546
  }
383
547
  /**
384
548
  * The same cache-and-fetch flow for an explicit project id, used when the
@@ -391,6 +555,16 @@ export async function loadProjectVocabularyById(env, profile, projectId) {
391
555
  if (cached !== undefined) {
392
556
  return cached;
393
557
  }
558
+ return refreshProjectVocabulary(env, profile, projectId);
559
+ }
560
+ /**
561
+ * Re-fetch one project's vocabulary and store it, leaving every other
562
+ * cached project and the instance-wide lists alone. For a stale entry that
563
+ * concerns a single project (a type added after the cache was written), so
564
+ * the repair does not burst a request per stored project.
565
+ */
566
+ export async function refreshProjectVocabulary(env, profile, projectId) {
567
+ const stored = await readStoredMetadata(env, profile);
394
568
  const base = stored ?? (await fetchStoredMetadata(profile));
395
569
  const vocabulary = await fetchProjectVocabulary(profile, projectId);
396
570
  await persistMetadata(env, profile, {
@@ -488,7 +662,10 @@ function diffProject(before, after) {
488
662
  if (before === undefined || after === undefined) {
489
663
  return [];
490
664
  }
491
- const diffs = fieldDiffs(before, after);
665
+ // The links are routing, not identity: a refresh that only moved them is
666
+ // not a change of the project.
667
+ const identity = ({ id, identifier, name }) => ({ id, identifier, name });
668
+ const diffs = fieldDiffs(identity(before), identity(after));
492
669
  return diffs.length === 0
493
670
  ? []
494
671
  : [{ section: "project", kind: "changed", id: after.id, detail: diffs.join("; ") }];
@@ -519,10 +696,36 @@ function diffVocabulary(before, after) {
519
696
  const fields = (vocabulary) => Object.values(vocabulary?.custom_fields ?? {}).flat();
520
697
  return [
521
698
  ...diffEntries("members", before?.members.map(memberEntry), after.members.map(memberEntry)),
522
- ...diffEntries("versions", before?.versions, after.versions),
523
- ...diffEntries("categories", before?.categories, after.categories),
524
- ...diffEntries("activities", before?.activities, after.activities),
699
+ ...diffOptional("versions", before, after),
700
+ ...diffOptional("categories", before, after),
701
+ ...diffOptional("activities", before, after),
702
+ ...diffOptional("sprints", before, after),
703
+ ...diffOptional("buckets", before, after),
525
704
  ...diffEntries("fields", fields(before), fields(after)),
526
705
  ];
527
706
  }
707
+ /**
708
+ * The entry diff of one optional source, unless either side was refused:
709
+ * an emptied list is a lost permission, not every entry being removed, so
710
+ * it reports the flip once instead of one removal per entry.
711
+ */
712
+ function diffOptional(source, before, after) {
713
+ const was = before?.unavailable?.[source];
714
+ const is = after.unavailable?.[source];
715
+ if (was === undefined && is === undefined) {
716
+ return diffEntries(source, before?.[source], after[source] ?? []);
717
+ }
718
+ if (before === undefined || was?.status === is?.status) {
719
+ return [];
720
+ }
721
+ const project = String(after.project_id);
722
+ return [{
723
+ section: source,
724
+ kind: "changed",
725
+ id: null,
726
+ detail: is === undefined
727
+ ? `became available in project ${project}`
728
+ : `became unavailable in project ${project} (${String(is.status)})`,
729
+ }];
730
+ }
528
731
  //# sourceMappingURL=metadata.js.map
@@ -1,16 +1,82 @@
1
1
  import { apiGet } from "../core/http.js";
2
2
  import { OpCliError } from "../core/errors.js";
3
- import { DEFAULT_PAGE_SIZE, halElements, withPageSize, } from "../core/paginate.js";
3
+ import { DEFAULT_PAGE_SIZE, halElements, halNextPath, withPageSize, } from "../core/paginate.js";
4
4
  import { isIdForm, rankByCloseness } from "./resolve.js";
5
+ /** Link name on the project resource to the key kept for it. */
6
+ const PROJECT_LINK_KEYS = [
7
+ ["versions", "versions"],
8
+ ["categories", "categories"],
9
+ ["types", "types"],
10
+ ["workPackages", "work_packages"],
11
+ ["createWorkPackage", "create_work_package"],
12
+ ["memberships", "memberships"],
13
+ ];
14
+ const API_ROOT = "/api/v3/";
15
+ /**
16
+ * The path of a link relative to the instance URL. A link on an instance
17
+ * hosted under a subpath (https://host/openproject) carries that subpath,
18
+ * which the client prepends again from the instance URL, so everything
19
+ * before the API root is dropped.
20
+ */
21
+ function instancePathOf(href) {
22
+ const path = halNextPath(href);
23
+ const root = path?.indexOf(API_ROOT) ?? -1;
24
+ return path === undefined || root <= 0 ? path : path.slice(root);
25
+ }
26
+ /** The collection paths a project resource links to; undefined when it links none. */
27
+ export function projectLinksOf(project) {
28
+ const rawLinks = (project._links ?? {});
29
+ const found = {};
30
+ for (const [name, key] of PROJECT_LINK_KEYS) {
31
+ const href = rawLinks[name]?.href;
32
+ const path = typeof href === "string" ? instancePathOf(href) : undefined;
33
+ if (path !== undefined) {
34
+ found[key] = path;
35
+ }
36
+ }
37
+ return Object.keys(found).length === 0 ? undefined : found;
38
+ }
39
+ function linksField(element) {
40
+ const links = projectLinksOf(element);
41
+ return links === undefined ? {} : { links };
42
+ }
5
43
  export function hitOf(element) {
6
44
  const candidate = element;
7
45
  return typeof candidate.id === "number"
8
46
  && typeof candidate.identifier === "string"
9
47
  && typeof candidate.name === "string"
10
- ? { id: candidate.id, identifier: candidate.identifier, name: candidate.name }
48
+ ? {
49
+ id: candidate.id,
50
+ identifier: candidate.identifier,
51
+ name: candidate.name,
52
+ ...linksField(element),
53
+ }
11
54
  : undefined;
12
55
  }
13
56
  export const PROJECTS_COLLECTION = "/api/v3/projects";
57
+ /** Where instances that renamed projects to workspaces serve them (#57). */
58
+ export const WORKSPACES_COLLECTION = "/api/v3/workspaces";
59
+ /**
60
+ * Try `first`; when it answers NOT_FOUND the route may have moved, so
61
+ * `moved` is tried once (#57). Any other failure stands. When both routes
62
+ * are missing the first answer is the one reported.
63
+ */
64
+ export async function withMovedRetry(first, moved) {
65
+ try {
66
+ return await first();
67
+ }
68
+ catch (error) {
69
+ if (!(error instanceof OpCliError && error.code === "NOT_FOUND")) {
70
+ throw error;
71
+ }
72
+ try {
73
+ return await moved();
74
+ }
75
+ catch (retry) {
76
+ throw retry instanceof OpCliError && retry.code === "NOT_FOUND" ? error : retry;
77
+ }
78
+ }
79
+ }
14
80
  /**
15
81
  * Every visible project, page by page in server order. Resolution walks
16
82
  * instead of filtering server-side because the exact-match filter set
@@ -102,10 +102,10 @@ export function hoursToIso(hours) {
102
102
  * compound form ("1h30m"), or an ISO 8601 duration ("PT1H30M"). Every
103
103
  * accepted spelling of the same amount produces the identical result.
104
104
  */
105
- export function parseDuration(raw) {
105
+ export function parseDuration(raw, options = {}) {
106
106
  const token = raw.trim();
107
107
  if (/^\d+(?:\.\d+)?$/.test(token)) {
108
- return parsedFromHours(Number(token), raw);
108
+ return parsedFromHours(Number(token), raw, options);
109
109
  }
110
110
  const compound = token.toLowerCase().replace(/\s+/g, "");
111
111
  // Segments are consumed in whatever units the caller used, but the
@@ -133,18 +133,26 @@ export function parseDuration(raw) {
133
133
  rest = rest.slice(match[0].length);
134
134
  }
135
135
  if (!Number.isNaN(ms)) {
136
- return parsedFromHours(ms / 3_600_000, raw);
136
+ return parsedFromHours(ms / 3_600_000, raw, options);
137
137
  }
138
138
  const direct = isoTimeToMs(token);
139
139
  if (direct !== undefined) {
140
- return parsedFromHours(direct / 3_600_000, raw);
140
+ return parsedFromHours(direct / 3_600_000, raw, options);
141
141
  }
142
- throw new OpCliError("USAGE_ERROR", `cannot read "${raw}" as a duration.`, `--hours accepts ${ACCEPTED_FORMS}.`);
142
+ throw new OpCliError("USAGE_ERROR", `cannot read "${raw}" as a duration.`, `${options.flag ?? "--hours"} accepts ${ACCEPTED_FORMS}.`);
143
143
  }
144
- /** Shared tail of parseDuration: positive amounts only. */
145
- function parsedFromHours(hours, raw) {
146
- if (!(hours > 0)) {
147
- throw new OpCliError("USAGE_ERROR", `"${raw}" does not name a positive amount of time.`, `--hours accepts ${ACCEPTED_FORMS}, and logging needs more than zero.`);
144
+ /**
145
+ * Shared tail of parseDuration: positive amounts, or non-negative ones when
146
+ * the caller (an estimate, remaining work) may legitimately name zero.
147
+ */
148
+ function parsedFromHours(hours, raw, options) {
149
+ const flag = options.flag ?? "--hours";
150
+ if (options.allowZero === true ? !(hours >= 0) : !(hours > 0)) {
151
+ throw new OpCliError("USAGE_ERROR", options.allowZero === true
152
+ ? `"${raw}" does not name an amount of time of zero or more.`
153
+ : `"${raw}" does not name a positive amount of time.`, options.allowZero === true
154
+ ? `${flag} accepts ${ACCEPTED_FORMS}.`
155
+ : `${flag} accepts ${ACCEPTED_FORMS}, and logging needs more than zero.`);
148
156
  }
149
157
  return { hours, iso: hoursToIso(hours) };
150
158
  }
@@ -29,6 +29,13 @@ export const ERROR_CATALOGUE = {
29
29
  message: "Authentication failed.",
30
30
  hint: "run op-cli auth login.",
31
31
  },
32
+ // A 403: the credentials are fine, the account lacks a permission, so
33
+ // logging in again cannot help.
34
+ PERMISSION_DENIED: {
35
+ exitCode: 8,
36
+ message: "Permission denied.",
37
+ hint: "ask an administrator for the missing permission, or use an account that has it.",
38
+ },
32
39
  UNSUPPORTED_VERSION: {
33
40
  exitCode: 7,
34
41
  message: "The instance version is not supported.",
@@ -63,8 +70,20 @@ export class OpCliError extends Error {
63
70
  this.details = details;
64
71
  }
65
72
  }
73
+ /**
74
+ * Refuse flags that exclude one another: each entry is the flag's spelling
75
+ * when it was given and undefined when it was not. More than one given is
76
+ * a USAGE_ERROR naming them, so a mutual-exclusion rule is one call and
77
+ * one wording wherever it applies.
78
+ */
79
+ export function refuseCombined(given, hint) {
80
+ const flags = given.filter((flag) => flag !== undefined);
81
+ if (flags.length > 1) {
82
+ throw new OpCliError("USAGE_ERROR", `${flags.join(" and ")} cannot be combined.`, hint);
83
+ }
84
+ }
66
85
  /** OpenProject's own explanation of a refusal, when the body carries one. */
67
- function explanationOf(body) {
86
+ export function explanationOf(body) {
68
87
  const message = typeof body === "object" && body !== null
69
88
  ? body.message
70
89
  : undefined;
@@ -86,6 +105,38 @@ export function writeRefusal(subject, status, body) {
86
105
  }
87
106
  return new OpCliError("API_ERROR", message, "fix the rejected values and repeat the command.");
88
107
  }
108
+ /**
109
+ * The catalogue entry for a write that did not succeed, shared by every
110
+ * command that writes (ADR-0002): 404 is NOT_FOUND, a 5xx is the
111
+ * unknown-state NETWORK_ERROR because the request may still have been
112
+ * applied (never a retry that could write twice), and anything else is a
113
+ * refusal that quotes the instance's own explanation.
114
+ */
115
+ export function writeFailure(status, body, wording) {
116
+ if (status === 404) {
117
+ return new OpCliError("NOT_FOUND");
118
+ }
119
+ if (status >= 500) {
120
+ return new OpCliError("NETWORK_ERROR", `the ${wording.action} failed with HTTP ${String(status)}; ${wording.unknown}.`, wording.check);
121
+ }
122
+ return writeRefusal(wording.action, status, body);
123
+ }
124
+ /**
125
+ * Runs a write whose request may never complete: timeouts and network
126
+ * errors are never retried on writes, and exit 6 says the outcome is
127
+ * unknown instead of inviting a duplicate.
128
+ */
129
+ export async function unknownIfUnfinished(attempt, wording) {
130
+ try {
131
+ return await attempt();
132
+ }
133
+ catch (error) {
134
+ if (error instanceof OpCliError && error.code === "NETWORK_ERROR") {
135
+ throw new OpCliError("NETWORK_ERROR", `the ${wording.action} request did not complete; ${wording.unknown}.`, wording.check);
136
+ }
137
+ throw error;
138
+ }
139
+ }
89
140
  export function renderTextError(error) {
90
141
  return `[${error.code}] ${error.message} Hint: ${error.hint}\n`;
91
142
  }