@tuanhv/op-cli 0.3.1 → 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.
@@ -1,14 +1,17 @@
1
- import { OpCliError, writeRefusal } from "../core/errors.js";
2
- import { buildWpFilters, filtersQuery, } from "../core/filters.js";
1
+ import { Option } from "commander";
2
+ import { OpCliError, refuseCombined, unknownIfUnfinished, writeFailure, } from "../core/errors.js";
3
+ import { applyScalars, SCALAR_OPTIONS, scalarFlag, validateScalars, } from "../core/scalars.js";
4
+ import { buildWpFilters, filtersQuery, parseSort, sortByQuery, } from "../core/filters.js";
3
5
  import { defineCollectionCommand, emitRows, PAGED_JSON_HELP, } from "../core/define.js";
4
6
  import { flattenHalRecord, isFlatLink, toFormattable } from "../core/hal.js";
5
- import { apiDelete, apiGet, apiPost, apiPatchRaw, apiPostRaw, authenticate, } from "../core/http.js";
7
+ import { apiDelete, apiDeleteRaw, apiGet, apiPost, apiPatchRaw, apiPostRaw, authenticate, } from "../core/http.js";
6
8
  import { allPageSize, DEFAULT_PAGE_SIZE, halElements, parsePageSize, withPageSize, } from "../core/paginate.js";
7
9
  import { explicitCustomFieldKey, isIdForm, matchByName, rankByCloseness, resolveName, } from "../context/resolve.js";
8
10
  import { parseProjectOverride, } from "../context/profile.js";
9
- import { resolveProjectRef } from "../context/projectref.js";
10
- import { loadProjectVocabulary, loadStoredMetadata, refreshStoredMetadata, } from "../context/metadata.js";
11
+ import { resolveProjectRef, withMovedRetry } from "../context/projectref.js";
12
+ import { loadProjectVocabulary, loadProjectVocabularyById, loadStoredMetadata, readStoredMetadata, refreshProjectVocabulary, refreshStoredMetadata, requireVocabulary, } from "../context/metadata.js";
11
13
  import { formatCell, renderTable } from "../output/table.js";
14
+ import { registerAttachmentCommands } from "./attachments.js";
12
15
  // Canonical row order for a single-record table; every other key of the
13
16
  // flattened record follows in server order.
14
17
  const PREFERRED_FIELDS = [
@@ -21,9 +24,15 @@ const PREFERRED_FIELDS = [
21
24
  "author",
22
25
  "project",
23
26
  "version",
27
+ "targetVersions",
28
+ "observedInVersions",
24
29
  "category",
25
30
  "startDate",
26
31
  "dueDate",
32
+ "estimatedTime",
33
+ "remainingTime",
34
+ "percentageDone",
35
+ "storyPoints",
27
36
  "createdAt",
28
37
  "updatedAt",
29
38
  "lockVersion",
@@ -100,6 +109,10 @@ async function openProfile(runtime, options) {
100
109
  function collectValue(value, previous) {
101
110
  return [...previous, value];
102
111
  }
112
+ /** Like collectValue, but a flag left out stays undefined, not empty. */
113
+ function collectOptional(value, previous) {
114
+ return [...(previous ?? []), value];
115
+ }
103
116
  /**
104
117
  * Attach the shared filter surface of `wp list` and `wp count`. Both
105
118
  * commands accept exactly the same flags; repeating a value flag ORs.
@@ -109,32 +122,65 @@ function addFilterFlags(command) {
109
122
  .option("--status <name>", "status name or id; repeat to OR values", collectValue, [])
110
123
  .option("--type <name>", "type name or id; repeat to OR values", collectValue, [])
111
124
  .option("--assignee <name>", "user name, id, or me; repeat to OR values", collectValue, [])
125
+ .option("--accountable <name>", "Accountable (API field responsible): user name, id, or me; repeat to OR values", collectValue, [])
112
126
  .option("--author <name>", "user name, id, or me; repeat to OR values", collectValue, [])
127
+ .option("--watcher <name>", "user name, id, or me, watching the work package; repeat to OR values", collectValue, [])
113
128
  .option("--version <name>", "version name or id; repeat to OR values", collectValue, [])
129
+ .option("--observed-in <name>", "observed-in version name or id; repeat to OR values", collectValue, [])
114
130
  .option("--category <name>", "category name or id; repeat to OR values", collectValue, [])
131
+ .option("--sprint <name>", "sprint name or id; repeat to OR values", collectValue, [])
132
+ .option("--bucket <name>", "backlog bucket name or id; repeat to OR values", collectValue, [])
133
+ .option("--backlog-inbox", "only work packages in the backlog inbox: in neither a sprint nor a backlog bucket")
115
134
  .option("--priority <name>", "priority name or id; repeat to OR values", collectValue, [])
116
135
  .option("--parent <reference>", "parent work package id or exact subject", collectValue, [])
117
136
  .option("--updated-after <value>", "today, yesterday, days back such as 7d, or YYYY-MM-DD")
118
137
  .option("--created-after <value>", "only work packages created since; same date forms as --updated-after")
138
+ .option("--due-before <date>", "due on or before this date: YYYY-MM-DD, today, yesterday, or Nd; "
139
+ + "today/yesterday/Nd count back from today, only YYYY-MM-DD reaches the future")
140
+ .option("--due-after <date>", "due on or after this date; same date forms as --due-before")
141
+ .option("--overdue", "open work packages whose due date is before today")
119
142
  .option("--search <text>", "substring matched against work package subjects")
143
+ .option("--id <id>", "work package id; repeat to OR values", collectValue, [])
144
+ .option("--include-subprojects", "include subprojects in a --project listing (the default; an instance setting may change what a project clause covers)")
145
+ .option("--no-include-subprojects", "only the project's own work packages, not its subprojects' (needs a project)")
120
146
  .option("--open", "shorthand for every open status")
121
147
  .option("--closed", "shorthand for every closed status")
122
148
  .option("--profile <name>", "use this profile for this command only")
123
149
  .option("--project <name-or-id>", "override the profile default project");
124
150
  }
151
+ /** Normalise --id values ("12" or "#12") to digit strings. */
152
+ function parseIdValues(raw) {
153
+ return raw.map((value) => {
154
+ const id = value.trim().replace(/^#/, "");
155
+ if (!/^[1-9]\d*$/.test(id)) {
156
+ throw new OpCliError("USAGE_ERROR", `"${value}" is not a work package id.`, "--id takes a positive number such as 1234 or #1234.");
157
+ }
158
+ return id;
159
+ });
160
+ }
125
161
  function rawListFlags(options) {
126
162
  return {
127
163
  statuses: options.status,
128
164
  types: options.type,
129
165
  assignees: options.assignee,
166
+ accountables: options.accountable,
130
167
  authors: options.author,
168
+ watchers: options.watcher,
131
169
  versions: options.version,
170
+ observedIn: options.observedIn,
132
171
  categories: options.category,
172
+ sprints: options.sprint,
173
+ buckets: options.bucket,
174
+ backlogInbox: options.backlogInbox,
133
175
  priorities: options.priority,
134
176
  parents: options.parent,
135
177
  updatedAfter: options.updatedAfter,
136
178
  createdAfter: options.createdAfter,
179
+ dueBefore: options.dueBefore,
180
+ dueAfter: options.dueAfter,
181
+ overdue: options.overdue,
137
182
  search: options.search,
183
+ ids: parseIdValues(options.id ?? []),
138
184
  open: options.open,
139
185
  closed: options.closed,
140
186
  };
@@ -160,7 +206,7 @@ function projectSource(runtime, profile, flag, label, select, memo) {
160
206
  label,
161
207
  load: async () => {
162
208
  if (profile.project === undefined) {
163
- throw new OpCliError("USAGE_ERROR", `--${flag} needs a project to look names up in.`, "pass --project <name-or-id> or set a default project on the profile.");
209
+ throw new OpCliError("USAGE_ERROR", `--${flag} needs a project to look names up in.`, "pass --project <name-or-id> (or --workspace) or set a default project on the profile.");
164
210
  }
165
211
  return select(await (memo === undefined
166
212
  ? loadProjectVocabulary(runtime.env, profile)
@@ -172,6 +218,47 @@ function projectSource(runtime, profile, flag, label, select, memo) {
172
218
  },
173
219
  };
174
220
  }
221
+ /** The two backlog placements a work package link can name (#46). */
222
+ const BACKLOG_SOURCES = {
223
+ sprint: { source: "sprints", owner: "Sprint", plural: "sprints" },
224
+ bucket: { source: "buckets", owner: "Bucket", plural: "backlog buckets" },
225
+ };
226
+ /**
227
+ * The sprints or backlog buckets of the profile's project, on the same
228
+ * footing as the other project sources. A store from before #46 lacks
229
+ * them and an empty list may simply be stale, so an empty read re-reads
230
+ * this project once; a project that still has none fails naming the
231
+ * project instead of matching against nothing. Only this project is
232
+ * refreshed: the failure path would otherwise re-fetch every cached
233
+ * project on each call.
234
+ */
235
+ function backlogSource(runtime, profile, flag, memo) {
236
+ const { source, owner, plural } = BACKLOG_SOURCES[flag];
237
+ const project = projectSource(runtime, profile, flag, flag, (vocabulary) => {
238
+ const entries = requireVocabulary(vocabulary, source);
239
+ return entries.map((entry) => ({ name: entry.name, owner, value: entry.id }));
240
+ }, memo);
241
+ const refresh = async () => {
242
+ memo?.invalidate();
243
+ await refreshProjectVocabulary(runtime.env, profile, Number(profile.project));
244
+ };
245
+ return {
246
+ label: project.label,
247
+ load: async () => {
248
+ let entries = await project.load();
249
+ if (entries.length === 0) {
250
+ await refresh();
251
+ entries = await project.load();
252
+ }
253
+ if (entries.length === 0) {
254
+ throw new OpCliError("USAGE_ERROR", `--${flag}: project ${String(profile.project)} has no ${plural}.`, `run op-cli project ${source} ${String(profile.project)} to check, `
255
+ + `or leave --${flag} out.`);
256
+ }
257
+ return entries;
258
+ },
259
+ refresh,
260
+ };
261
+ }
175
262
  async function resolveValues(raws, source) {
176
263
  const ids = [];
177
264
  for (const raw of raws) {
@@ -218,6 +305,33 @@ function membersSource(runtime, profile, flag, memo) {
218
305
  value: member.user_id,
219
306
  })), memo);
220
307
  }
308
+ /**
309
+ * Every value flag, once. A key added to CreateValueFlags fails to compile
310
+ * until it is listed here, and this list feeds the stdin key check and the
311
+ * update "touches something" guard, so a new flag cannot be forgotten in
312
+ * either.
313
+ */
314
+ const VALUE_OPTIONS = {
315
+ type: true,
316
+ status: true,
317
+ priority: true,
318
+ assignee: true,
319
+ accountable: true,
320
+ version: true,
321
+ observedIn: true,
322
+ category: true,
323
+ sprint: true,
324
+ bucket: true,
325
+ parent: true,
326
+ description: true,
327
+ field: true,
328
+ start: true,
329
+ due: true,
330
+ estimate: true,
331
+ remaining: true,
332
+ done: true,
333
+ storyPoints: true,
334
+ };
221
335
  function newResolutionMemo(runtime, profile) {
222
336
  let metadata;
223
337
  let vocabulary;
@@ -287,18 +401,19 @@ async function submitCreate(runtime, profile, payload, refs, memo) {
287
401
  }
288
402
  return response.body;
289
403
  }
404
+ /**
405
+ * Kebab spellings a stdin item may use for a camelCase key, mirroring the
406
+ * flag. Both spell the same attribute; giving both is refused.
407
+ */
408
+ const BULK_KEY_ALIASES = {
409
+ "story-points": "storyPoints",
410
+ "observed-in": "observedIn",
411
+ };
290
412
  /** Keys one stdin item may carry; everything else is a loud usage error. */
291
413
  const BULK_ITEM_KEYS = [
292
414
  "subject",
293
- "type",
294
- "status",
295
- "priority",
296
- "assignee",
297
- "version",
298
- "category",
299
- "parent",
300
- "description",
301
- "field",
415
+ ...Object.keys(VALUE_OPTIONS),
416
+ ...Object.keys(BULK_KEY_ALIASES),
302
417
  ];
303
418
  /**
304
419
  * One element of the --stdin array. Mirrors the value flags of the
@@ -310,7 +425,18 @@ function parseBulkItem(raw, index) {
310
425
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
311
426
  throw usage('every input must be an object with a non-empty "subject".');
312
427
  }
313
- const record = raw;
428
+ // Normalise into a copy: the caller's parsed object stays as it came in.
429
+ const record = { ...raw };
430
+ for (const [alias, key] of Object.entries(BULK_KEY_ALIASES)) {
431
+ if (record[alias] === undefined) {
432
+ continue;
433
+ }
434
+ if (record[key] !== undefined) {
435
+ throw usage(`"${alias}" and "${key}" are the same key; give one.`);
436
+ }
437
+ record[key] = record[alias];
438
+ delete record[alias];
439
+ }
314
440
  const unknownKeys = Object.keys(record)
315
441
  .filter((key) => !BULK_ITEM_KEYS.includes(key));
316
442
  if (unknownKeys.length > 0) {
@@ -326,8 +452,10 @@ function parseBulkItem(raw, index) {
326
452
  "status",
327
453
  "priority",
328
454
  "assignee",
329
- "version",
455
+ "accountable",
330
456
  "category",
457
+ "sprint",
458
+ "bucket",
331
459
  "parent",
332
460
  "description",
333
461
  ];
@@ -341,6 +469,55 @@ function parseBulkItem(raw, index) {
341
469
  }
342
470
  values[key] = rawValue;
343
471
  }
472
+ try {
473
+ refuseTwoPlacements(values);
474
+ }
475
+ catch (error) {
476
+ if (error instanceof OpCliError) {
477
+ throw usage(error.message, error.hint);
478
+ }
479
+ throw error;
480
+ }
481
+ // A version key takes one name-or-id string or an array of them.
482
+ for (const key of ["version", "observedIn"]) {
483
+ const rawValue = record[key];
484
+ if (rawValue === undefined) {
485
+ continue;
486
+ }
487
+ const list = Array.isArray(rawValue) ? rawValue : [rawValue];
488
+ if (list.length === 0
489
+ || list.some((entry) => typeof entry !== "string" || entry === "")) {
490
+ throw usage(`"${key}" must be a non-empty name-or-id string or an array of them.`);
491
+ }
492
+ values[key] = list;
493
+ }
494
+ for (const key of SCALAR_OPTIONS) {
495
+ const rawValue = record[key];
496
+ if (rawValue === undefined) {
497
+ continue;
498
+ }
499
+ // Numbers are natural in JSON for done and story points, and hours
500
+ // for the durations; they travel as the text a flag would carry.
501
+ if (typeof rawValue === "number" && Number.isFinite(rawValue)) {
502
+ values[key] = String(rawValue);
503
+ }
504
+ else if (typeof rawValue === "string" && rawValue !== "") {
505
+ values[key] = rawValue;
506
+ }
507
+ else {
508
+ throw usage(`"${key}" must be a non-empty string or number.`);
509
+ }
510
+ }
511
+ try {
512
+ validateScalars(values);
513
+ }
514
+ catch (error) {
515
+ // Re-raised with the item index; only a usage error is ours to relabel.
516
+ if (error instanceof OpCliError && error.code === "USAGE_ERROR") {
517
+ throw usage(error.message, error.hint);
518
+ }
519
+ throw error;
520
+ }
344
521
  const field = record.field;
345
522
  if (field !== undefined) {
346
523
  if (!Array.isArray(field)
@@ -388,7 +565,7 @@ async function runBulkCreate(runtime, subjectArg, options) {
388
565
  project: parseProjectOverride(options.project),
389
566
  });
390
567
  if (profile.project === undefined) {
391
- throw new OpCliError("USAGE_ERROR", "wp create needs a project to create the work package in.", "pass --project <name-or-id> or set a default project on the profile.");
568
+ throw new OpCliError("USAGE_ERROR", "wp create needs a project to create the work package in.", "pass --project <name-or-id> (or --workspace) or set a default project on the profile.");
392
569
  }
393
570
  const memo = newResolutionMemo(runtime, profile);
394
571
  const dryRun = options.dryRun === true;
@@ -479,7 +656,7 @@ function customFieldRows(metadata, vocabulary) {
479
656
  }
480
657
  async function resolveFieldDefinition(runtime, profile, rawName, memo) {
481
658
  if (profile.project === undefined) {
482
- throw new OpCliError("USAGE_ERROR", "--field needs a project to look field names up in.", "pass --project <name-or-id> or set a default project on the profile.");
659
+ throw new OpCliError("USAGE_ERROR", "--field needs a project to look field names up in.", "pass --project <name-or-id> (or --workspace) or set a default project on the profile.");
483
660
  }
484
661
  const metadata = memo === undefined
485
662
  ? loadStoredMetadata(runtime.env, profile)
@@ -507,6 +684,86 @@ async function resolveFieldDefinition(runtime, profile, rawName, memo) {
507
684
  return field;
508
685
  }
509
686
  const CUSTOM_OPTIONS_HREF = "/api/v3/custom_options/";
687
+ /**
688
+ * The clearing convention for a link attribute: an empty value sends the
689
+ * link with a null href. Array links clear by sending an empty array
690
+ * instead (see listFieldValues).
691
+ */
692
+ function clearLink(links, attribute) {
693
+ links[attribute] = { href: null };
694
+ }
695
+ /** Flags whose empty value is refused: the attribute cannot be empty. */
696
+ const REQUIRED_VALUE_FLAGS = [
697
+ "type",
698
+ "status",
699
+ "priority",
700
+ ];
701
+ /** Flags whose empty value clears the link on update. */
702
+ const CLEARABLE_LINK_FLAGS = [
703
+ "assignee",
704
+ "accountable",
705
+ "category",
706
+ "sprint",
707
+ "bucket",
708
+ "parent",
709
+ ];
710
+ /**
711
+ * A work package sits in a sprint or in a backlog bucket, never both, so
712
+ * one command naming both is refused whatever the values (#46). Moving
713
+ * between the two is one command per placement.
714
+ */
715
+ function refuseTwoPlacements(options) {
716
+ refuseCombined([
717
+ options.sprint === undefined ? undefined : "--sprint",
718
+ options.bucket === undefined ? undefined : "--bucket",
719
+ ], "a work package sits in a sprint or in a backlog bucket; pass one of the two.");
720
+ }
721
+ /** The repeatable version flags; their empty value is `[""]`. */
722
+ const VERSION_FLAGS = [
723
+ { option: "version", flag: "--version" },
724
+ { option: "observedIn", flag: "--observed-in" },
725
+ ];
726
+ /**
727
+ * Refuse empty values that cannot mean anything, before any request: a
728
+ * required attribute never clears, and a create has nothing to clear.
729
+ * On update the clearable link flags pass through; the resolvers turn
730
+ * their empty value into a null href.
731
+ */
732
+ function refuseEmptyValues(options, mode) {
733
+ if (mode === "update" && options.subject === "") {
734
+ throw new OpCliError("USAGE_ERROR", "--subject cannot be empty.", "a work package always has a subject; give the new text.");
735
+ }
736
+ for (const flag of REQUIRED_VALUE_FLAGS) {
737
+ if (options[flag] === "") {
738
+ throw new OpCliError("USAGE_ERROR", `--${flag} cannot be empty.`, `a work package always has a ${flag}; give a name or id.`);
739
+ }
740
+ }
741
+ for (const { option, flag } of VERSION_FLAGS) {
742
+ const values = options[option];
743
+ if (values === undefined || !values.includes("")) {
744
+ continue;
745
+ }
746
+ if (mode === "create") {
747
+ throw new OpCliError("USAGE_ERROR", `${flag} cannot be empty on create.`, "there is nothing to clear on a new work package; leave the flag out.");
748
+ }
749
+ if (values.length > 1) {
750
+ throw new OpCliError("USAGE_ERROR", `${flag} mixes a clearing "" with other values.`, `either pass ${flag} "" alone to clear, or give every occurrence a value.`);
751
+ }
752
+ }
753
+ validateScalars(options);
754
+ if (mode === "create") {
755
+ for (const option of SCALAR_OPTIONS) {
756
+ if (options[option] === "") {
757
+ throw new OpCliError("USAGE_ERROR", `${scalarFlag(option)} cannot be empty on create.`, "there is nothing to clear on a new work package; leave the flag out.");
758
+ }
759
+ }
760
+ for (const flag of CLEARABLE_LINK_FLAGS) {
761
+ if (options[flag] === "") {
762
+ throw new OpCliError("USAGE_ERROR", `--${flag} cannot be empty on create.`, "there is nothing to clear on a new work package; leave the flag out.");
763
+ }
764
+ }
765
+ }
766
+ }
510
767
  /**
511
768
  * Resolve one link-valued option into the payload. An all-digits value is
512
769
  * an id and goes straight in; anything else is resolved here and
@@ -514,22 +771,37 @@ const CUSTOM_OPTIONS_HREF = "/api/v3/custom_options/";
514
771
  * retried after one real refresh.
515
772
  */
516
773
  async function resolveLinkOption(links, attribute, hrefBase, flag, raw, source, refs) {
517
- if (raw === undefined || raw === "") {
774
+ if (raw === undefined) {
518
775
  return;
519
776
  }
520
- let id;
521
- if (isIdForm(raw)) {
522
- id = Number(raw);
523
- }
524
- else {
525
- id = Number(await resolveName(raw, source));
526
- refs.push({ attribute, raw, idBefore: id, hrefBase, source, link: true });
777
+ if (raw === "") {
778
+ clearLink(links, attribute);
779
+ return;
527
780
  }
781
+ const id = await resolveOneLinkId(raw, attribute, hrefBase, source, refs);
528
782
  links[attribute] = { href: `${hrefBase}${String(id)}` };
529
783
  }
784
+ /**
785
+ * One link value to its id: an id-form value is the caller's own and goes
786
+ * straight through; a name is resolved and remembered in `refs`, so a
787
+ * rejection that blames this attribute can be retried with a fresh id
788
+ * (ADR-0002). Every link-valued flag records its refs here and only here.
789
+ */
790
+ async function resolveOneLinkId(raw, attribute, hrefBase, source, refs) {
791
+ if (isIdForm(raw)) {
792
+ return Number(raw);
793
+ }
794
+ const id = Number(await resolveName(raw, source));
795
+ refs.push({ attribute, raw, idBefore: id, hrefBase, source, link: true });
796
+ return id;
797
+ }
530
798
  /** Same contract as resolveLinkOption for members: names, ids, and me. */
531
799
  async function resolveUserOption(runtime, profile, links, attribute, hrefBase, flag, raw, refs, memo) {
532
- if (raw === undefined || raw === "") {
800
+ if (raw === undefined) {
801
+ return;
802
+ }
803
+ if (raw === "") {
804
+ clearLink(links, attribute);
533
805
  return;
534
806
  }
535
807
  let id;
@@ -538,13 +810,8 @@ async function resolveUserOption(runtime, profile, links, attribute, hrefBase, f
538
810
  ? (await authenticate(profile.instanceUrl, profile.apiKey)).id
539
811
  : await memo.me();
540
812
  }
541
- else if (isIdForm(raw)) {
542
- id = Number(raw);
543
- }
544
813
  else {
545
- const source = membersSource(runtime, profile, flag, memo);
546
- id = Number(await resolveName(raw, source));
547
- refs.push({ attribute, raw, idBefore: id, hrefBase, source, link: true });
814
+ id = await resolveOneLinkId(raw, attribute, hrefBase, membersSource(runtime, profile, flag, memo), refs);
548
815
  }
549
816
  links[attribute] = { href: `${hrefBase}${String(id)}` };
550
817
  }
@@ -653,65 +920,70 @@ function pointedAttribute(body) {
653
920
  // Link rejections sometimes spell the target "links/status".
654
921
  return name.replace(/^links[./]/i, "");
655
922
  }
923
+ /** What a work package write says when its outcome cannot be known. */
924
+ const WP_WRITES = {
925
+ create: {
926
+ action: "create",
927
+ unknown: "whether the work package was created is unknown",
928
+ check: "check whether the work package exists before repeating the command.",
929
+ },
930
+ update: {
931
+ action: "update",
932
+ unknown: "whether the change was applied is unknown",
933
+ check: "run op-cli wp get to see the stored values before repeating the command.",
934
+ },
935
+ move: {
936
+ action: "move",
937
+ unknown: "whether the change was applied is unknown",
938
+ check: "run op-cli wp get to see the stored values before repeating the command.",
939
+ },
940
+ };
656
941
  /**
657
942
  * Catalogue mapping for a write that survived the proof-carrying retry:
658
- * 404 stays NOT_FOUND, 5xx becomes the unknown-state NETWORK_ERROR, and
659
- * everything else is the shared refusal mapping.
943
+ * 409 is the optimistic-locking CONFLICT, everything else is the shared
944
+ * write mapping (404, the unknown-state 5xx, the refusal).
660
945
  */
661
946
  function writeRejection(status, body, verb = "create") {
662
- if (status === 404) {
663
- return new OpCliError("NOT_FOUND");
664
- }
665
947
  // A 409 is the optimistic-locking catalogue entry: the caller either
666
948
  // already handled the retry rule or has nothing safe left to try.
667
949
  if (status === 409) {
668
950
  return new OpCliError("CONFLICT");
669
951
  }
670
- // A 5xx means the request may still have been applied server-side, so
671
- // the honest answer is "unknown state", never a retry that could
672
- // duplicate the work package.
673
- if (status >= 500) {
674
- const unknownState = verb === "create"
675
- ? "whether the work package was created is unknown."
676
- : "whether the change was applied is unknown.";
677
- const hint = verb === "create"
678
- ? "check whether the work package exists before repeating the command."
679
- : "run op-cli wp get to see the stored values before repeating the command.";
680
- return new OpCliError("NETWORK_ERROR", `the ${verb} failed with HTTP ${status}; ${unknownState}`, hint);
681
- }
682
- return writeRefusal(verb, status, body);
952
+ return writeFailure(status, body, WP_WRITES[verb]);
683
953
  }
684
954
  /**
685
955
  * A create request whose failure to complete leaves the state unknown:
686
956
  * timeouts and network errors are never retried on writes, and exit 6
687
957
  * says so instead of inviting a duplicate.
688
958
  */
689
- async function postCreate(profile, payload) {
690
- try {
691
- return await apiPostRaw(profile.instanceUrl, profile.apiKey, "/api/v3/work_packages", payload);
692
- }
693
- catch (error) {
694
- if (error instanceof OpCliError && error.code === "NETWORK_ERROR") {
695
- throw new OpCliError("NETWORK_ERROR", "the create request did not complete; whether the work package was created is unknown.", "check whether the work package exists before repeating the command.");
696
- }
697
- throw error;
698
- }
959
+ function postCreate(profile, payload) {
960
+ return unknownIfUnfinished(() => apiPostRaw(profile.instanceUrl, profile.apiKey, "/api/v3/work_packages", payload), WP_WRITES.create);
699
961
  }
700
962
  /**
701
963
  * An update request whose failure to complete leaves the state unknown:
702
964
  * like create, timeouts and network errors are never retried on writes.
703
965
  */
704
- async function patchWp(profile, id, payload) {
705
- try {
706
- return await apiPatchRaw(profile.instanceUrl, profile.apiKey, `/api/v3/work_packages/${id}`, payload);
707
- }
708
- catch (error) {
709
- if (error instanceof OpCliError && error.code === "NETWORK_ERROR") {
710
- throw new OpCliError("NETWORK_ERROR", "the update request did not complete; whether the change was applied is unknown.", "run op-cli wp get to see the stored values before repeating the command.");
711
- }
712
- throw error;
713
- }
966
+ function patchWp(profile, id, payload) {
967
+ return unknownIfUnfinished(() => apiPatchRaw(profile.instanceUrl, profile.apiKey, `/api/v3/work_packages/${id}`, payload), WP_WRITES.update);
714
968
  }
969
+ /** What a comment write says when its outcome cannot be known. */
970
+ const COMMENT_WRITE = (reference) => ({
971
+ action: "comment",
972
+ unknown: "whether the comment was posted is unknown",
973
+ check: `run op-cli wp comments ${reference} before repeating the command.`,
974
+ });
975
+ /** What a comment edit says when its outcome cannot be known. */
976
+ const COMMENT_EDIT_WRITE = (activityId) => ({
977
+ action: "comment edit",
978
+ unknown: "whether the comment was changed is unknown",
979
+ check: `run op-cli wp comments to see comment ${activityId} before repeating the command.`,
980
+ });
981
+ /** What a watch or unwatch says when its outcome cannot be known. */
982
+ const WATCH_WRITE = (reference) => ({
983
+ action: "watch change",
984
+ unknown: "whether the watcher list changed is unknown",
985
+ check: `run op-cli wp watchers ${reference} before repeating the command.`,
986
+ });
715
987
  /** The lockVersion a stored record carries; without it there is no safe update. */
716
988
  function lockVersionOf(record) {
717
989
  const value = typeof record === "object" && record !== null
@@ -888,25 +1160,44 @@ async function resolveListFlags(runtime, profile, options) {
888
1160
  if (assignee.length > 0) {
889
1161
  flags.assignees = await resolveUserValues(runtime, profile, "assignee", assignee);
890
1162
  }
1163
+ const accountable = options.accountable ?? [];
1164
+ if (accountable.length > 0) {
1165
+ flags.accountables = await resolveUserValues(runtime, profile, "accountable", accountable);
1166
+ }
891
1167
  const author = options.author ?? [];
892
1168
  if (author.length > 0) {
893
1169
  flags.authors = await resolveUserValues(runtime, profile, "author", author);
894
1170
  }
1171
+ const watcher = options.watcher ?? [];
1172
+ if (watcher.length > 0) {
1173
+ flags.watchers = await resolveUserValues(runtime, profile, "watcher", watcher);
1174
+ }
895
1175
  const version = options.version ?? [];
896
1176
  if (version.length > 0) {
897
- flags.versions = await resolveValues(version, projectSource(runtime, profile, "version", "version", (vocabulary) => vocabulary.versions.map((entry) => ({
898
- name: entry.name,
899
- owner: "Version",
900
- value: entry.id,
901
- }))));
1177
+ flags.versions = await resolveValues(version, versionSource(runtime, profile, "version"));
1178
+ }
1179
+ const observedIn = options.observedIn ?? [];
1180
+ if (observedIn.length > 0) {
1181
+ if (profile.project !== undefined) {
1182
+ // A filter spans the whole project: the field is there when any type has it.
1183
+ const byType = await versionFieldsByType(runtime, profile, undefined, undefined, undefined);
1184
+ if (!Object.values(byType).some((fields) => fields.observedInVersions !== undefined)) {
1185
+ throw new OpCliError("USAGE_ERROR", "--observed-in is not available in this project.", "its work package schema has no observedInVersions field.");
1186
+ }
1187
+ }
1188
+ flags.observedIn = await resolveValues(observedIn, versionSource(runtime, profile, "observed-in"));
902
1189
  }
903
1190
  const category = options.category ?? [];
904
1191
  if (category.length > 0) {
905
- flags.categories = await resolveValues(category, projectSource(runtime, profile, "category", "category", (vocabulary) => vocabulary.categories.map((entry) => ({
906
- name: entry.name,
907
- owner: "Category",
908
- value: entry.id,
909
- }))));
1192
+ flags.categories = await resolveValues(category, categorySource(runtime, profile));
1193
+ }
1194
+ const sprint = options.sprint ?? [];
1195
+ if (sprint.length > 0) {
1196
+ flags.sprints = await resolveValues(sprint, backlogSource(runtime, profile, "sprint"));
1197
+ }
1198
+ const bucket = options.bucket ?? [];
1199
+ if (bucket.length > 0) {
1200
+ flags.buckets = await resolveValues(bucket, backlogSource(runtime, profile, "bucket"));
910
1201
  }
911
1202
  const priority = options.priority ?? [];
912
1203
  if (priority.length > 0) {
@@ -926,23 +1217,239 @@ async function resolveListFlags(runtime, profile, options) {
926
1217
  if (options.createdAfter !== undefined && options.createdAfter !== "") {
927
1218
  flags.createdAfter = options.createdAfter;
928
1219
  }
1220
+ if (options.dueBefore !== undefined && options.dueBefore !== "") {
1221
+ flags.dueBefore = options.dueBefore;
1222
+ }
1223
+ if (options.dueAfter !== undefined && options.dueAfter !== "") {
1224
+ flags.dueAfter = options.dueAfter;
1225
+ }
929
1226
  if (options.search !== undefined && options.search !== "") {
930
1227
  flags.search = options.search;
931
1228
  }
932
- return { ...flags, open: options.open, closed: options.closed };
1229
+ return {
1230
+ ...flags,
1231
+ ids: parseIdValues(options.id ?? []),
1232
+ includeSubprojects: options.includeSubprojects,
1233
+ open: options.open,
1234
+ closed: options.closed,
1235
+ overdue: options.overdue,
1236
+ backlogInbox: options.backlogInbox,
1237
+ };
1238
+ }
1239
+ /**
1240
+ * `subprojectId` is only valid on the project's own collection: the global
1241
+ * endpoint answers 500, so --no-include-subprojects reads from there.
1242
+ * `ownCollection` is that collection's path, see ownCollectionOf.
1243
+ */
1244
+ function workPackagesPath(filters, sort = [], ownCollection) {
1245
+ const sortBy = sort.length > 0 ? `&sortBy=${sortByQuery(sort)}` : "";
1246
+ const collection = ownCollection ?? "/api/v3/work_packages";
1247
+ return `${collection}?filters=${filtersQuery(filters)}${sortBy}`;
1248
+ }
1249
+ /**
1250
+ * The project's own work package collection, when subprojects are
1251
+ * excluded: the stored `workPackages` link of that project (#57), else the
1252
+ * projects path. Reads the local store only; no request is made to find a
1253
+ * link. A stored link can go stale, so it carries the projects path as the
1254
+ * fallback for readOwnPages.
1255
+ */
1256
+ async function ownCollectionOf(runtime, profile, flags) {
1257
+ if (flags.includeSubprojects !== false || flags.project === undefined) {
1258
+ return undefined;
1259
+ }
1260
+ const stored = await readStoredMetadata(runtime.env, profile);
1261
+ const id = Number(flags.project);
1262
+ const linked = stored?.projectScoped?.[flags.project]?.links?.work_packages
1263
+ ?? (stored?.project?.id === id ? stored.project.links?.work_packages : undefined);
1264
+ const projectsPath = `/api/v3/projects/${encodeURIComponent(flags.project)}/work_packages`;
1265
+ // The collection takes the filters as its query, so a link that already
1266
+ // carries one cannot be extended.
1267
+ return linked !== undefined && !linked.includes("?")
1268
+ ? { path: linked, fallback: projectsPath }
1269
+ : { path: projectsPath };
933
1270
  }
934
- function workPackagesPath(filters) {
935
- return `/api/v3/work_packages?filters=${filtersQuery(filters)}`;
1271
+ /**
1272
+ * A page reader for a listing that starts on a stored link: when that
1273
+ * first page answers NOT_FOUND the link is stale, and the same listing is
1274
+ * read once from the projects path instead. Later pages follow whichever
1275
+ * collection answered.
1276
+ */
1277
+ function readOwnPages(getPage, startPath, fallbackStartPath) {
1278
+ if (fallbackStartPath === undefined) {
1279
+ return getPage;
1280
+ }
1281
+ return (path) => path === startPath
1282
+ ? withMovedRetry(() => getPage(path), () => getPage(fallbackStartPath))
1283
+ : getPage(path);
936
1284
  }
937
1285
  function renderWorkPackages(records) {
938
1286
  return renderTable(LIST_COLUMNS.map((column) => column.title), records.map((record) => LIST_COLUMNS.map((column) => formatCell(record[column.field]))));
939
1287
  }
1288
+ /** The id at the end of a link's href, such as a type or project link. */
1289
+ function typeIdOf(link) {
1290
+ if (link === undefined || Array.isArray(link)) {
1291
+ return undefined;
1292
+ }
1293
+ const href = link.href;
1294
+ const match = href === null ? null : /(\d+)$/.exec(href);
1295
+ return match === null ? undefined : Number(match[1]);
1296
+ }
1297
+ /**
1298
+ * The version fields of every type of one project, as the cached schema
1299
+ * shape has them. A vocabulary stored before these fields were captured, or
1300
+ * one that predates the type being asked about, is refreshed once for that
1301
+ * project alone, so the decision always comes from the schema (ADR-0002).
1302
+ * The project is the work package's own when given, else the profile's.
1303
+ */
1304
+ async function versionFieldsByType(runtime, profile, typeId, memo, projectId) {
1305
+ const own = projectId !== undefined && projectId !== profile.project;
1306
+ const load = () => own
1307
+ ? loadProjectVocabularyById(runtime.env, profile, projectId)
1308
+ : memo === undefined
1309
+ ? loadProjectVocabulary(runtime.env, profile)
1310
+ : memo.vocabulary();
1311
+ let vocabulary = await load();
1312
+ const known = (candidate) => candidate.version_fields !== undefined
1313
+ && (typeId === undefined || candidate.version_fields[String(typeId)] !== undefined);
1314
+ if (!known(vocabulary)) {
1315
+ await refreshProjectVocabulary(runtime.env, profile, vocabulary.project_id);
1316
+ memo?.invalidate();
1317
+ vocabulary = await load();
1318
+ }
1319
+ return vocabulary.version_fields ?? {};
1320
+ }
1321
+ /**
1322
+ * The version fields the schema of this project and type exposes. A type of
1323
+ * unknown identity (a create without --type, whose default type the server
1324
+ * picks) is decided only when every type of the project agrees; otherwise
1325
+ * guessing would send a field the real type refuses.
1326
+ */
1327
+ async function versionFieldsFor(runtime, profile, typeId, memo, projectId,
1328
+ /** The fields the caller will write; only these must be agreed on. */
1329
+ needs) {
1330
+ const byType = await versionFieldsByType(runtime, profile, typeId, memo, projectId);
1331
+ const own = typeId === undefined ? undefined : byType[String(typeId)];
1332
+ if (own !== undefined) {
1333
+ return own;
1334
+ }
1335
+ const fields = Object.values(byType);
1336
+ // Only what every type marks deprecated is safe to warn about untyped.
1337
+ const deprecated = (fields[0]?.deprecated ?? []).filter((name) => fields.every((entry) => entry.deprecated?.includes(name) === true));
1338
+ const agreed = (name) => {
1339
+ const found = fields.map((entry) => entry[name]);
1340
+ const present = found.filter((entry) => entry !== undefined);
1341
+ if (present.length === 0) {
1342
+ return {};
1343
+ }
1344
+ const first = present[0];
1345
+ if (present.length < found.length
1346
+ || present.some((entry) => entry.multiple !== first?.multiple)) {
1347
+ throw new OpCliError("USAGE_ERROR", "the project's types disagree on its version fields, so --version and --observed-in cannot be judged without a type.", "pass --type <name-or-id> (or a type in the stdin item) so the schema of that type decides.");
1348
+ }
1349
+ return { [name]: { multiple: present[0]?.multiple === true } };
1350
+ };
1351
+ return {
1352
+ ...Object.assign({}, ...needs.map(agreed)),
1353
+ ...(deprecated.length === 0 ? {} : { deprecated }),
1354
+ };
1355
+ }
1356
+ function categorySource(runtime, profile, memo) {
1357
+ return projectSource(runtime, profile, "category", "category", (vocabulary) => requireVocabulary(vocabulary, "categories").map((entry) => ({
1358
+ name: entry.name,
1359
+ owner: "Category",
1360
+ value: entry.id,
1361
+ })), memo);
1362
+ }
1363
+ function versionSource(runtime, profile, flag, memo) {
1364
+ return projectSource(runtime, profile, flag, "version", (vocabulary) => requireVocabulary(vocabulary, "versions").map((entry) => ({
1365
+ name: entry.name,
1366
+ owner: "Version",
1367
+ value: entry.id,
1368
+ })), memo);
1369
+ }
1370
+ /**
1371
+ * Write one repeatable version flag into an array link: `[{href}]`, or
1372
+ * `[]` to clear.
1373
+ */
1374
+ async function resolveVersionList(runtime, profile, links, attribute, flag, values, refs, memo) {
1375
+ if (values.length === 1 && values[0] === "") {
1376
+ links[attribute] = [];
1377
+ return;
1378
+ }
1379
+ const source = versionSource(runtime, profile, flag.replace(/^--/, ""), memo);
1380
+ const hrefs = [];
1381
+ for (const value of values) {
1382
+ const id = await resolveOneLinkId(value, attribute, "/api/v3/versions/", source, refs);
1383
+ const href = `/api/v3/versions/${String(id)}`;
1384
+ if (!hrefs.some((entry) => entry.href === href)) {
1385
+ hrefs.push({ href });
1386
+ }
1387
+ }
1388
+ links[attribute] = hrefs;
1389
+ }
1390
+ /**
1391
+ * --version and --observed-in. The schema decides where --version lands:
1392
+ * `targetVersions` when the type exposes it, the deprecated `version`
1393
+ * otherwise; the server refuses both in one request, so exactly one is
1394
+ * ever sent.
1395
+ */
1396
+ async function resolveVersionLinks(runtime, profile, links, options, typeId, refs, memo, projectId) {
1397
+ if (options.version === undefined && options.observedIn === undefined) {
1398
+ return;
1399
+ }
1400
+ const fields = await versionFieldsFor(runtime, profile, typeId, memo, projectId, [
1401
+ ...(options.version === undefined ? [] : ["targetVersions"]),
1402
+ ...(options.observedIn === undefined ? [] : ["observedInVersions"]),
1403
+ ]);
1404
+ // The attributes this write actually sets, judged against the schema's
1405
+ // own `deprecated` marks once the values resolved.
1406
+ const written = [];
1407
+ if (options.version !== undefined) {
1408
+ const target = fields.targetVersions;
1409
+ if (target === undefined) {
1410
+ if (options.version.length > 1) {
1411
+ throw new OpCliError("USAGE_ERROR", "--version holds one value on this work package.", "its schema has no targetVersions, only the single version field.");
1412
+ }
1413
+ written.push("version");
1414
+ await resolveLinkOption(links, "version", "/api/v3/versions/", "--version", options.version[0], versionSource(runtime, profile, "version", memo), refs);
1415
+ }
1416
+ else {
1417
+ written.push("targetVersions");
1418
+ if (!target.multiple && options.version.length > 1) {
1419
+ throw new OpCliError("USAGE_ERROR", "--version holds one value for this work package.", "the schema's targetVersions takes a single version; pass --version once.");
1420
+ }
1421
+ await resolveVersionList(runtime, profile, links, "targetVersions", "--version", options.version, refs, memo);
1422
+ }
1423
+ }
1424
+ if (options.observedIn !== undefined) {
1425
+ const observed = fields.observedInVersions;
1426
+ if (observed === undefined) {
1427
+ throw new OpCliError("USAGE_ERROR", "--observed-in is not available for this work package.", "its schema has no observedInVersions field; leave the flag out.");
1428
+ }
1429
+ if (!observed.multiple && options.observedIn.length > 1) {
1430
+ throw new OpCliError("USAGE_ERROR", "--observed-in holds one value for this work package.", "the schema's observedInVersions takes a single version; pass --observed-in once.");
1431
+ }
1432
+ written.push("observedInVersions");
1433
+ await resolveVersionList(runtime, profile, links, "observedInVersions", "--observed-in", options.observedIn, refs, memo);
1434
+ }
1435
+ const deprecated = written.filter((name) => fields.deprecated?.includes(name) === true);
1436
+ if (deprecated.length > 0) {
1437
+ runtime.writeErr(deprecated.length === 1
1438
+ ? `warning: the ${deprecated[0] ?? ""} attribute is deprecated in this instance's schema; the write still goes through.\n`
1439
+ : `warning: the ${deprecated.join(", ")} attributes are deprecated in this instance's schema; the write still goes through.\n`);
1440
+ }
1441
+ }
940
1442
  /**
941
1443
  * Everything create and update share: every value flag resolved by name
942
1444
  * into payload entries, with the name-resolved ones remembered so a
943
1445
  * rejection can be retried with fresh ids (the ADR-0002 refs).
944
1446
  */
945
- async function resolveNamedValues(runtime, profile, options, memo) {
1447
+ async function resolveNamedValues(runtime, profile, options, memo,
1448
+ /**
1449
+ * What an update's work package already has: its type, when --type does
1450
+ * not name one, and its project, whose schema decides the version fields.
1451
+ */
1452
+ existing = {}) {
946
1453
  const refs = [];
947
1454
  const links = {};
948
1455
  await resolveLinkOption(links, "type", "/api/v3/types/", "--type", options.type, instanceSource(runtime, profile, "type", (metadata) => metadata.types.map((entry) => ({
@@ -961,20 +1468,19 @@ async function resolveNamedValues(runtime, profile, options, memo) {
961
1468
  value: entry.id,
962
1469
  })), memo), refs);
963
1470
  await resolveUserOption(runtime, profile, links, "assignee", "/api/v3/users/", "assignee", options.assignee, refs, memo);
964
- await resolveLinkOption(links, "version", "/api/v3/versions/", "--version", options.version, projectSource(runtime, profile, "version", "version", (vocabulary) => vocabulary.versions.map((entry) => ({
965
- name: entry.name,
966
- owner: "Version",
967
- value: entry.id,
968
- })), memo), refs);
969
- await resolveLinkOption(links, "category", "/api/v3/categories/", "--category", options.category, projectSource(runtime, profile, "category", "category", (vocabulary) => vocabulary.categories.map((entry) => ({
970
- name: entry.name,
971
- owner: "Category",
972
- value: entry.id,
973
- })), memo), refs);
1471
+ // Accountable is the API's `responsible` link.
1472
+ await resolveUserOption(runtime, profile, links, "responsible", "/api/v3/users/", "accountable", options.accountable, refs, memo);
1473
+ await resolveVersionLinks(runtime, profile, links, options, typeIdOf(links.type) ?? existing.typeId, refs, memo, existing.projectId);
1474
+ await resolveLinkOption(links, "category", "/api/v3/categories/", "--category", options.category, categorySource(runtime, profile, memo), refs);
1475
+ await resolveLinkOption(links, "sprint", "/api/v3/sprints/", "--sprint", options.sprint, backlogSource(runtime, profile, "sprint", memo), refs);
1476
+ await resolveLinkOption(links, "backlogBucket", "/api/v3/backlog_buckets/", "--bucket", options.bucket, backlogSource(runtime, profile, "bucket", memo), refs);
974
1477
  // The parent is a live lookup over work packages, not cached metadata,
975
1478
  // so it never joins the ADR-0002 refs: an id given here is already the
976
1479
  // caller's own, and a subject search re-runs against current state.
977
- if (options.parent !== undefined) {
1480
+ if (options.parent === "") {
1481
+ clearLink(links, "parent");
1482
+ }
1483
+ else if (options.parent !== undefined) {
978
1484
  const parentId = isIdForm(options.parent)
979
1485
  ? options.parent
980
1486
  : String(await searchParentByName(profile, options.parent));
@@ -986,6 +1492,7 @@ async function resolveNamedValues(runtime, profile, options, memo) {
986
1492
  if (options.description !== undefined) {
987
1493
  payload.description = { raw: options.description };
988
1494
  }
1495
+ applyScalars(payload, options);
989
1496
  const groups = new Map();
990
1497
  for (const pair of (options.field ?? []).map(splitFieldPair)) {
991
1498
  const field = await resolveFieldDefinition(runtime, profile, pair.name, memo);
@@ -1055,6 +1562,7 @@ export const COMMENT_COLUMNS = [
1055
1562
  { title: "ID", field: "id" },
1056
1563
  { title: "AUTHOR", field: "user" },
1057
1564
  { title: "COMMENT", field: "comment" },
1565
+ { title: "INTERNAL", field: "internal" },
1058
1566
  { title: "CREATED", field: "createdAt" },
1059
1567
  ];
1060
1568
  export const HISTORY_COLUMNS = [
@@ -1073,6 +1581,10 @@ export const RELATION_COLUMNS = [
1073
1581
  { title: "LAG", field: "lag" },
1074
1582
  { title: "DESCRIPTION", field: "description" },
1075
1583
  ];
1584
+ export const WATCHER_COLUMNS = [
1585
+ { title: "ID", field: "id" },
1586
+ { title: "NAME", field: "name" },
1587
+ ];
1076
1588
  export const SCHEMA_COLUMNS = [
1077
1589
  { title: "FIELD", field: "field" },
1078
1590
  { title: "NAME", field: "name" },
@@ -1122,6 +1634,10 @@ function linkIdOf(link) {
1122
1634
  * behind a system activity, one instance-spelled sentence per attribute
1123
1635
  * ("Status changed from New to In progress"). A comment activity changed
1124
1636
  * nothing, so its details render empty rather than absent.
1637
+ *
1638
+ * `internal` is the visibility flag of a comment: true when only users with
1639
+ * the internal-comment permission may read it. An activity the instance
1640
+ * does not flag reads as false.
1125
1641
  */
1126
1642
  export function activityRow(element) {
1127
1643
  const resource = element;
@@ -1135,6 +1651,7 @@ export function activityRow(element) {
1135
1651
  kind,
1136
1652
  user: record.user,
1137
1653
  comment: typeof comment?.raw === "string" ? comment.raw : "",
1654
+ internal: record.internal === true,
1138
1655
  details: activityDetails(record.details),
1139
1656
  createdAt: record.createdAt,
1140
1657
  };
@@ -1183,7 +1700,9 @@ async function principalName(getPage, id) {
1183
1700
  }
1184
1701
  catch (error) {
1185
1702
  if (error instanceof OpCliError
1186
- && (error.code === "AUTH_FAILED" || error.code === "NOT_FOUND")) {
1703
+ && (error.code === "AUTH_FAILED"
1704
+ || error.code === "PERMISSION_DENIED"
1705
+ || error.code === "NOT_FOUND")) {
1187
1706
  return null;
1188
1707
  }
1189
1708
  throw error;
@@ -1195,10 +1714,12 @@ async function principalName(getPage, id) {
1195
1714
  * show names rather than the ids the API speaks. Each id is looked up at
1196
1715
  * most once per run, and a row that already carries a name costs nothing.
1197
1716
  */
1198
- function authorResolver(getPage) {
1717
+ function authorResolver(getPage,
1718
+ /** The key of the row that holds the user link: comments use `user`. */
1719
+ key = "user") {
1199
1720
  const named = new Map();
1200
1721
  return async (row) => {
1201
- const user = row.user;
1722
+ const user = row[key];
1202
1723
  if (!isFlatLink(user) || user.id === null || user.name !== null) {
1203
1724
  return row;
1204
1725
  }
@@ -1207,7 +1728,7 @@ function authorResolver(getPage) {
1207
1728
  named.set(id, await principalName(getPage, id));
1208
1729
  }
1209
1730
  const name = named.get(id) ?? null;
1210
- return name === null ? row : { ...row, user: { id, name } };
1731
+ return name === null ? row : { ...row, [key]: { id, name } };
1211
1732
  };
1212
1733
  }
1213
1734
  /** Comments are the Comment-kind slice of the same activity stream. */
@@ -1215,6 +1736,10 @@ export function commentRow(element) {
1215
1736
  const row = activityRow(element);
1216
1737
  return row.kind === "Comment" ? row : undefined;
1217
1738
  }
1739
+ /** A watcher is a plain user resource; the whole flat record, `--fields` projects it. */
1740
+ export function watcherRow(element) {
1741
+ return flattenHalRecord(element);
1742
+ }
1218
1743
  /** Only the typed fields and both ends; the action links carry no data. */
1219
1744
  export function relationRow(element) {
1220
1745
  const record = flattenHalRecord(element);
@@ -1264,25 +1789,34 @@ export function registerWpCommands(wp, runtime) {
1264
1789
  addFilterFlags(wp.command("list")
1265
1790
  .description("List work packages by name-resolved filters")
1266
1791
  .option("--json", PAGED_JSON_HELP)
1792
+ .option("--sort <field[:asc|desc]>", "sort by updatedAt, createdAt, dueDate, startDate, priority, status, id or subject; "
1793
+ + "repeat for tie-breakers; the direction defaults to asc", collectValue, [])
1267
1794
  .option("--limit <n>", "maximum number of results to show")
1268
1795
  .option("--all", "fetch every page instead of one limited page")).action(async (options) => {
1269
1796
  runtime.setJsonMode(options.json === true);
1270
1797
  // Refuse impossible flag combinations before any traffic or resolution.
1271
1798
  buildWpFilters(rawListFlags(options), new Date());
1799
+ const sort = parseSort(options.sort ?? []);
1272
1800
  const profile = await runtime.resolve({
1273
1801
  profile: options.profile,
1274
1802
  project: parseProjectOverride(options.project),
1275
1803
  });
1276
1804
  const now = new Date();
1277
1805
  const limit = parsePageSize(options.limit);
1278
- const filters = buildWpFilters(await resolveListFlags(runtime, profile, options), now);
1806
+ const resolved = await resolveListFlags(runtime, profile, options);
1807
+ const filters = buildWpFilters(resolved, now);
1279
1808
  const getPage = (path) => apiGet(profile.instanceUrl, profile.apiKey, path);
1280
1809
  // --all sizes pages by the instance's advertised maximum; --limit
1281
1810
  // only ever sizes the single non-all page.
1282
- const startPath = withPageSize(workPackagesPath(filters), options.all === true ? await allPageSize(getPage) : limit);
1811
+ const own = await ownCollectionOf(runtime, profile, resolved);
1812
+ const pageSize = options.all === true ? await allPageSize(getPage) : limit;
1813
+ const startPath = withPageSize(workPackagesPath(filters, sort, own?.path), pageSize);
1814
+ const readPage = readOwnPages(getPage, startPath, own?.fallback === undefined
1815
+ ? undefined
1816
+ : withPageSize(workPackagesPath(filters, sort, own.fallback), pageSize));
1283
1817
  if (options.all === true) {
1284
1818
  const rows = [];
1285
- for await (const element of halElements(getPage, startPath)) {
1819
+ for await (const element of halElements(readPage, startPath)) {
1286
1820
  const record = flattenHalRecord(element);
1287
1821
  if (options.json === true) {
1288
1822
  runtime.write(`${JSON.stringify(record)}\n`);
@@ -1296,7 +1830,7 @@ export function registerWpCommands(wp, runtime) {
1296
1830
  }
1297
1831
  return;
1298
1832
  }
1299
- const page = (await getPage(startPath));
1833
+ const page = (await readPage(startPath));
1300
1834
  const records = (page._embedded?.elements ?? []).map((element) => flattenHalRecord(element));
1301
1835
  if (options.json === true) {
1302
1836
  runtime.write(`${JSON.stringify(records)}\n`);
@@ -1310,14 +1844,24 @@ export function registerWpCommands(wp, runtime) {
1310
1844
  + "Pass --all to fetch every result.\n");
1311
1845
  }
1312
1846
  });
1313
- addFilterFlags(wp.command("count").description("Count work packages matching the filters")).action(async (options) => {
1847
+ addFilterFlags(wp.command("count")
1848
+ .description("Count work packages matching the filters")
1849
+ .addOption(new Option("--sort <field>").hideHelp())).action(async (options) => {
1850
+ if (options.sort !== undefined) {
1851
+ throw new OpCliError("USAGE_ERROR", "wp count does not take --sort.", "a count has no order; use wp list --sort <field> instead.");
1852
+ }
1314
1853
  buildWpFilters(rawListFlags(options), new Date());
1315
1854
  const profile = await runtime.resolve({
1316
1855
  profile: options.profile,
1317
1856
  project: parseProjectOverride(options.project),
1318
1857
  });
1319
- const filters = buildWpFilters(await resolveListFlags(runtime, profile, options), new Date());
1320
- const body = (await apiGet(profile.instanceUrl, profile.apiKey, `${workPackagesPath(filters)}&pageSize=1`));
1858
+ const resolved = await resolveListFlags(runtime, profile, options);
1859
+ const filters = buildWpFilters(resolved, new Date());
1860
+ const own = await ownCollectionOf(runtime, profile, resolved);
1861
+ const countPath = `${workPackagesPath(filters, [], own?.path)}&pageSize=1`;
1862
+ const body = (await readOwnPages((path) => apiGet(profile.instanceUrl, profile.apiKey, path), countPath, own?.fallback === undefined
1863
+ ? undefined
1864
+ : `${workPackagesPath(filters, [], own.fallback)}&pageSize=1`)(countPath));
1321
1865
  if (typeof body.total !== "number") {
1322
1866
  throw new OpCliError("API_ERROR", "the response carried no total.", "check the instance version with op-cli doctor.");
1323
1867
  }
@@ -1352,10 +1896,20 @@ export function registerWpCommands(wp, runtime) {
1352
1896
  .option("--status <name-or-id>", "initial status, by name or id")
1353
1897
  .option("--priority <name-or-id>", "priority, by name or id")
1354
1898
  .option("--assignee <name-or-id>", "assignee, by name, id, or me")
1355
- .option("--version <name-or-id>", "version of the project, by name or id")
1899
+ .option("--accountable <name-or-id>", "Accountable (API field responsible), by name, id, or me")
1900
+ .option("--version <name-or-id>", "version of the project, by name or id; repeat when the schema allows several", collectOptional)
1901
+ .option("--observed-in <name-or-id>", "observed-in version, by name or id; repeat when the schema allows several", collectOptional)
1356
1902
  .option("--category <name-or-id>", "category of the project, by name or id")
1903
+ .option("--sprint <name-or-id>", "sprint of the project, by name or id; not with --bucket")
1904
+ .option("--bucket <name-or-id>", "backlog bucket of the project, by name or id; not with --sprint")
1357
1905
  .option("--parent <id-or-subject>", "parent work package, by id or exact subject")
1358
1906
  .option("--description <text>", "markdown description of the work package")
1907
+ .option("--start <date>", "start date, YYYY-MM-DD")
1908
+ .option("--due <date>", "due date, YYYY-MM-DD")
1909
+ .option("--estimate <duration>", "estimated time such as 4h, 1h30m, or PT4H")
1910
+ .option("--remaining <duration>", "remaining work such as 2h, 1h30m, or PT2H")
1911
+ .option("--done <percent>", "percent complete, 0-100")
1912
+ .option("--story-points <n>", "story points, a whole number")
1359
1913
  .option("--field <pair>", 'set a custom field by human name as "Name=Value"; repeat the flag '
1360
1914
  + 'for several values; "Name=" clears the field', collectValue, [])
1361
1915
  .option("--json", "emit a flat JSON record")
@@ -1377,12 +1931,14 @@ export function registerWpCommands(wp, runtime) {
1377
1931
  if (subject === undefined) {
1378
1932
  throw new OpCliError("USAGE_ERROR", "wp create needs a subject or --stdin with an array of work packages.", "give <subject> to create one, or pipe a JSON array with --stdin.");
1379
1933
  }
1934
+ refuseTwoPlacements(options);
1935
+ refuseEmptyValues(options, "create");
1380
1936
  const profile = await runtime.resolve({
1381
1937
  profile: options.profile,
1382
1938
  project: parseProjectOverride(options.project),
1383
1939
  });
1384
1940
  if (profile.project === undefined) {
1385
- throw new OpCliError("USAGE_ERROR", "wp create needs a project to create the work package in.", "pass --project <name-or-id> or set a default project on the profile.");
1941
+ throw new OpCliError("USAGE_ERROR", "wp create needs a project to create the work package in.", "pass --project <name-or-id> (or --workspace) or set a default project on the profile.");
1386
1942
  }
1387
1943
  const { payload, refs } = await prepareCreatePayload(runtime, profile, subject, options);
1388
1944
  const body = await submitCreate(runtime, profile, payload, refs);
@@ -1396,11 +1952,21 @@ export function registerWpCommands(wp, runtime) {
1396
1952
  .option("--type <name-or-id>", "work package type, by name or id")
1397
1953
  .option("--status <name-or-id>", "status, by name or id")
1398
1954
  .option("--priority <name-or-id>", "priority, by name or id")
1399
- .option("--assignee <name-or-id>", "assignee, by name, id, or me")
1400
- .option("--version <name-or-id>", "version of the project, by name or id")
1401
- .option("--category <name-or-id>", "category of the project, by name or id")
1402
- .option("--parent <id-or-subject>", "re-parent under this work package, by id or exact subject")
1955
+ .option("--assignee <name-or-id>", 'assignee, by name, id, or me; "" clears')
1956
+ .option("--accountable <name-or-id>", 'Accountable (API field responsible), by name, id, or me; "" clears')
1957
+ .option("--version <name-or-id>", 'version of the project, by name or id; repeat when the schema allows several; "" clears', collectOptional)
1958
+ .option("--observed-in <name-or-id>", 'observed-in version, by name or id; repeat when the schema allows several; "" clears', collectOptional)
1959
+ .option("--category <name-or-id>", 'category of the project, by name or id; "" clears')
1960
+ .option("--sprint <name-or-id>", 'sprint of the project, by name or id; "" clears; not with --bucket')
1961
+ .option("--bucket <name-or-id>", 'backlog bucket of the project, by name or id; "" clears; not with --sprint')
1962
+ .option("--parent <id-or-subject>", 're-parent under this work package, by id or exact subject; "" clears')
1403
1963
  .option("--description <text>", "new markdown description of the work package")
1964
+ .option("--start <date>", 'start date, YYYY-MM-DD; "" clears')
1965
+ .option("--due <date>", 'due date, YYYY-MM-DD; "" clears')
1966
+ .option("--estimate <duration>", 'estimated time such as 4h, 1h30m, or PT4H; "" clears')
1967
+ .option("--remaining <duration>", 'remaining work such as 2h, 1h30m, or PT2H; "" clears')
1968
+ .option("--done <percent>", 'percent complete, 0-100; "" clears')
1969
+ .option("--story-points <n>", 'story points, a whole number; "" clears')
1404
1970
  .option("--field <pair>", 'set a custom field by human name as "Name=Value"; repeat the flag '
1405
1971
  + 'for several values; "Name=" clears the field', collectValue, [])
1406
1972
  .option("--json", "emit a flat JSON record")
@@ -1410,19 +1976,16 @@ export function registerWpCommands(wp, runtime) {
1410
1976
  .action(async (reference, options) => {
1411
1977
  runtime.setJsonMode(options.json === true);
1412
1978
  requireWpId(reference);
1979
+ // A flag counts when it carries a value; --field defaults to [].
1413
1980
  const touchesSomething = options.subject !== undefined
1414
- || options.type !== undefined
1415
- || options.status !== undefined
1416
- || options.priority !== undefined
1417
- || options.parent !== undefined
1418
- || options.assignee !== undefined
1419
- || options.version !== undefined
1420
- || options.category !== undefined
1421
- || options.description !== undefined
1422
- || (options.field?.length ?? 0) > 0;
1981
+ || Object.keys(VALUE_OPTIONS).some((option) => option === "field"
1982
+ ? (options.field?.length ?? 0) > 0
1983
+ : options[option] !== undefined);
1423
1984
  if (!touchesSomething) {
1424
- throw new OpCliError("USAGE_ERROR", "wp update needs at least one value to change.", "pass --subject, an attribute flag like --status, or --field Name=Value.");
1985
+ throw new OpCliError("USAGE_ERROR", "wp update needs at least one value to change.", "pass --subject, an attribute flag like --status or --due, or --field Name=Value.");
1425
1986
  }
1987
+ refuseTwoPlacements(options);
1988
+ refuseEmptyValues(options, "update");
1426
1989
  const profile = await runtime.resolve({
1427
1990
  profile: options.profile,
1428
1991
  project: parseProjectOverride(options.project),
@@ -1434,7 +1997,17 @@ export function registerWpCommands(wp, runtime) {
1434
1997
  // The read already names every column, so a bad --fields name is
1435
1998
  // refused while the work package is still untouched.
1436
1999
  selectedFields(options.fields, flattenHalRecord(before));
1437
- const { payload, refs } = await resolveNamedValues(runtime, profile, options);
2000
+ const beforeLinks = before._links;
2001
+ const ownProject = typeIdOf(beforeLinks?.project);
2002
+ // Names are looked up in --project, else the profile's default; with
2003
+ // neither, the work package's own project is the one that can matter.
2004
+ const scope = profile.project === undefined && ownProject !== undefined
2005
+ ? { ...profile, project: ownProject }
2006
+ : profile;
2007
+ const { payload, refs } = await resolveNamedValues(runtime, scope, options, undefined, {
2008
+ typeId: typeIdOf(beforeLinks?.type),
2009
+ projectId: ownProject,
2010
+ });
1438
2011
  if (options.subject !== undefined) {
1439
2012
  payload.subject = options.subject;
1440
2013
  }
@@ -1456,7 +2029,7 @@ export function registerWpCommands(wp, runtime) {
1456
2029
  response = await patchWp(profile, reference, payload);
1457
2030
  }
1458
2031
  else {
1459
- response = await retryWithFreshIds(runtime, profile, response, payload, refs, () => patchWp(profile, reference, payload));
2032
+ response = await retryWithFreshIds(runtime, scope, response, payload, refs, () => patchWp(profile, reference, payload));
1460
2033
  }
1461
2034
  }
1462
2035
  if (response.status >= 400) {
@@ -1598,7 +2171,7 @@ export function registerWpCommands(wp, runtime) {
1598
2171
  };
1599
2172
  wp.addCommand(defineCollectionCommand({
1600
2173
  name: "comments",
1601
- description: "List comments of one work package",
2174
+ description: "List comments of one work package (API v3 has no comment delete)",
1602
2175
  path: (id) => `/api/v3/work_packages/${id}/activities`,
1603
2176
  row: commentRow,
1604
2177
  columns: COMMENT_COLUMNS,
@@ -1612,6 +2185,14 @@ export function registerWpCommands(wp, runtime) {
1612
2185
  columns: HISTORY_COLUMNS,
1613
2186
  resolve: authorResolver,
1614
2187
  }, collectionRuntime));
2188
+ registerAttachmentCommands(wp, runtime, {
2189
+ authorResolver,
2190
+ selectedFields,
2191
+ renderRecord,
2192
+ openProfile,
2193
+ requireWpId,
2194
+ collectionRuntime,
2195
+ });
1615
2196
  wp.addCommand(defineCollectionCommand({
1616
2197
  name: "relations",
1617
2198
  description: "List the relations of one work package",
@@ -1619,6 +2200,13 @@ export function registerWpCommands(wp, runtime) {
1619
2200
  row: relationRow,
1620
2201
  columns: RELATION_COLUMNS,
1621
2202
  }, collectionRuntime));
2203
+ wp.addCommand(defineCollectionCommand({
2204
+ name: "watchers",
2205
+ description: "List the watchers of one work package",
2206
+ path: (id) => `/api/v3/work_packages/${id}/watchers`,
2207
+ row: watcherRow,
2208
+ columns: WATCHER_COLUMNS,
2209
+ }, collectionRuntime));
1622
2210
  const recordOptions = {
1623
2211
  json: "--json",
1624
2212
  fields: "--fields <list>",
@@ -1629,6 +2217,7 @@ export function registerWpCommands(wp, runtime) {
1629
2217
  .description("Add a comment to one work package")
1630
2218
  .argument("<id>")
1631
2219
  .argument("<text>", "markdown body of the comment")
2220
+ .option("--internal", "post an internal comment, visible only to users who may see internal comments")
1632
2221
  .option(recordOptions.json, "emit a flat JSON record")
1633
2222
  .option(recordOptions.fields, "comma-separated columns to show")
1634
2223
  .option(recordOptions.profile, "use this profile for this command only")
@@ -1639,10 +2228,160 @@ export function registerWpCommands(wp, runtime) {
1639
2228
  // a caller who fixes the flag and retries cannot post it twice.
1640
2229
  selectedFields(options.fields, ACTIVITY_ROW_SHAPE);
1641
2230
  const profile = await openProfile(runtime, options);
1642
- const created = activityRow(await apiPost(profile.instanceUrl, profile.apiKey, `/api/v3/work_packages/${reference}/activities`, { comment: { raw: text } }));
2231
+ // The key is sent only with the flag: an instance without the
2232
+ // internal_comments feature then sees exactly the public request.
2233
+ const body = options.internal === true
2234
+ ? { comment: { raw: text }, internal: true }
2235
+ : { comment: { raw: text } };
2236
+ const response = await unknownIfUnfinished(() => apiPostRaw(profile.instanceUrl, profile.apiKey, `/api/v3/work_packages/${reference}/activities`, body), COMMENT_WRITE(reference));
2237
+ // The instance explains its own refusals (an internal comment with
2238
+ // the feature off is a 422, not a 403), so the status goes through
2239
+ // the shared write mapping instead of a bare API_ERROR.
2240
+ if (response.status < 200 || response.status >= 300) {
2241
+ throw writeFailure(response.status, response.body, COMMENT_WRITE(reference));
2242
+ }
2243
+ const created = activityRow(response.body);
2244
+ // An instance without internal comments ignores the key and stores a
2245
+ // public comment without any error. The POST itself succeeded, so
2246
+ // this stays a warning (exit 0): a failing exit would break the
2247
+ // outcome contract and read as "nothing was posted".
2248
+ if (options.internal === true && created.internal !== true) {
2249
+ runtime.writeErr("warning: the instance stored the comment as public; it may not support internal comments.\n");
2250
+ }
1643
2251
  const named = await authorResolver((path) => apiGet(profile.instanceUrl, profile.apiKey, path))(created);
1644
2252
  renderRecord(runtime, options, named);
1645
2253
  });
2254
+ // A separate command rather than `wp comment --edit`: the target is an
2255
+ // activity id, not a work package id, so the `<id>` of `wp comment`
2256
+ // would mean two different things. The API has no activity delete, so
2257
+ // there is deliberately no `comment-delete`.
2258
+ wp.command("comment-edit")
2259
+ .description("Edit an existing comment by activity id (see `wp comments`); API v3 has no comment delete")
2260
+ .argument("<activity-id>", "id of the comment, as listed by `wp comments`")
2261
+ .argument("<text>", "new markdown body of the comment")
2262
+ .option(recordOptions.json, "emit a flat JSON record")
2263
+ .option(recordOptions.fields, "comma-separated columns to show")
2264
+ .option(recordOptions.profile, "use this profile for this command only")
2265
+ // An activity id is global, so the project never matters here; the flag
2266
+ // stays so a call copied from `wp comment` is not refused.
2267
+ .option(recordOptions.project, "accepted and ignored: activity ids are global")
2268
+ .action(async (activityId, text, options) => {
2269
+ if (!isIdForm(activityId)) {
2270
+ throw new OpCliError("USAGE_ERROR", `activity "${activityId}" is not an id.`, "comments are addressed by the numeric id `wp comments` lists.");
2271
+ }
2272
+ if (text.trim() === "") {
2273
+ throw new OpCliError("USAGE_ERROR", "the new comment text is empty.", "an edit cannot blank a comment; the API has no comment delete either.");
2274
+ }
2275
+ // Writing: --fields misuse is refused before the comment changes.
2276
+ selectedFields(options.fields, ACTIVITY_ROW_SHAPE);
2277
+ const profile = await openProfile(runtime, options);
2278
+ const path = `/api/v3/activities/${activityId}`;
2279
+ const current = activityRow(await apiGet(profile.instanceUrl, profile.apiKey, path));
2280
+ if (current.kind !== "Comment" || current.comment === "") {
2281
+ throw new OpCliError("USAGE_ERROR", `activity ${activityId} is a change journal, not a comment.`, "only entries listed by `wp comments` can be edited.");
2282
+ }
2283
+ let updated;
2284
+ try {
2285
+ // PATCH takes the comment as a plain string; the {raw} object the
2286
+ // POST takes is a 400 here.
2287
+ const response = await unknownIfUnfinished(() => apiPatchRaw(profile.instanceUrl, profile.apiKey, path, { comment: text }), COMMENT_EDIT_WRITE(activityId));
2288
+ if (response.status < 200 || response.status >= 300) {
2289
+ throw writeFailure(response.status, response.body, COMMENT_EDIT_WRITE(activityId));
2290
+ }
2291
+ updated = activityRow(response.body);
2292
+ }
2293
+ catch (error) {
2294
+ // A 401 stays AUTH_FAILED as http.ts raised it; only a 403 is
2295
+ // this key lacking the right to edit someone else's comment.
2296
+ if (error instanceof OpCliError && error.code === "PERMISSION_DENIED") {
2297
+ throw new OpCliError("PERMISSION_DENIED", `this key may not edit comment ${activityId}.`, "only your own comments, or any comment with the \"Edit notes\" permission, can be edited.", error.details);
2298
+ }
2299
+ throw error;
2300
+ }
2301
+ const named = await authorResolver((lookup) => apiGet(profile.instanceUrl, profile.apiKey, lookup))(updated);
2302
+ renderRecord(runtime, options, named);
2303
+ });
2304
+ const watchTarget = async (reference, options) => {
2305
+ requireWpId(reference);
2306
+ const profile = await openProfile(runtime, options);
2307
+ const [userId] = await resolveUserValues(runtime, profile, "user", [options.user ?? "me"]);
2308
+ return {
2309
+ profile,
2310
+ userId: userId,
2311
+ path: `/api/v3/work_packages/${reference}/watchers`,
2312
+ myself: (options.user ?? "me").toLowerCase() === "me",
2313
+ };
2314
+ };
2315
+ /** `changed` is null when the outcome of the write was not observed. */
2316
+ const reportWatch = (reference, options, userId, name, watching, changed) => {
2317
+ if (options.json === true) {
2318
+ runtime.write(`${JSON.stringify({
2319
+ id: Number(reference),
2320
+ user: Number(userId),
2321
+ name,
2322
+ watching,
2323
+ changed,
2324
+ })}\n`);
2325
+ return;
2326
+ }
2327
+ const who = name === null ? `user ${userId}` : `${name} (${userId})`;
2328
+ const verdict = watching
2329
+ ? (changed === false ? "is already watching" : "now watches")
2330
+ : (changed === false ? "was not watching" : "no longer watches");
2331
+ runtime.write(`${who} ${verdict} work package ${reference}.\n`);
2332
+ };
2333
+ const watchOptions = (command) => command
2334
+ .argument("<id>")
2335
+ .option("--user <name-or-id>", "user name, id, or me", "me")
2336
+ .option(recordOptions.json, "emit a flat JSON record")
2337
+ .option(recordOptions.profile, "use this profile for this command only")
2338
+ .option(recordOptions.project, "override the profile default project");
2339
+ watchOptions(wp.command("watch")
2340
+ .description("Add a watcher to one work package (default: me); no-op when already watching"))
2341
+ .action(async (reference, options) => {
2342
+ const { profile, userId, path } = await watchTarget(reference, options);
2343
+ const response = await unknownIfUnfinished(() => apiPostRaw(profile.instanceUrl, profile.apiKey, path, { user: { href: `/api/v3/users/${userId}` } }), WATCH_WRITE(reference));
2344
+ if (response.status < 200 || response.status >= 300) {
2345
+ throw writeFailure(response.status, response.body, WATCH_WRITE(reference));
2346
+ }
2347
+ const watcher = watcherRow(response.body);
2348
+ reportWatch(reference, options, userId, typeof watcher.name === "string" ? watcher.name : null, true, response.status === 201);
2349
+ });
2350
+ watchOptions(wp.command("unwatch")
2351
+ .description("Remove a watcher from one work package (default: me); no-op when not watching"))
2352
+ .action(async (reference, options) => {
2353
+ const { profile, userId, path, myself } = await watchTarget(reference, options);
2354
+ const getPage = (lookup) => apiGet(profile.instanceUrl, profile.apiKey, lookup);
2355
+ let name = null;
2356
+ let present = false;
2357
+ try {
2358
+ for await (const element of halElements(getPage, withPageSize(path, DEFAULT_PAGE_SIZE))) {
2359
+ const watcher = watcherRow(element);
2360
+ if (String(watcher.id) === userId) {
2361
+ present = true;
2362
+ name = typeof watcher.name === "string" ? watcher.name : null;
2363
+ }
2364
+ }
2365
+ }
2366
+ catch (error) {
2367
+ // Reading the list needs a permission that removing oneself does
2368
+ // not: for oneself the read is only a courtesy, so go on and
2369
+ // report the outcome as unobserved.
2370
+ if (!(myself && error instanceof OpCliError && error.code === "PERMISSION_DENIED")) {
2371
+ throw error;
2372
+ }
2373
+ present = null;
2374
+ }
2375
+ if (present === false) {
2376
+ reportWatch(reference, options, userId, name, false, false);
2377
+ return;
2378
+ }
2379
+ const response = await unknownIfUnfinished(() => apiDeleteRaw(profile.instanceUrl, profile.apiKey, `${path}/${userId}`), WATCH_WRITE(reference));
2380
+ if (response.status < 200 || response.status >= 300) {
2381
+ throw writeFailure(response.status, response.body, WATCH_WRITE(reference));
2382
+ }
2383
+ reportWatch(reference, options, userId, name, false, present === null ? null : true);
2384
+ });
1646
2385
  wp.command("relate")
1647
2386
  .description("Relate one work package to another")
1648
2387
  .argument("<id>")