@tuanhv/op-cli 0.4.0 → 0.5.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.
package/README.md CHANGED
@@ -39,6 +39,7 @@ points beyond the quickstart:
39
39
 
40
40
  ```sh
41
41
  op-cli wp create "Fix login bug" --type Bug --priority High
42
+ op-cli wp create "Quiet task" --no-watch # also unsubscribe yourself (creators are auto-watchers)
42
43
  op-cli wp update 123 --start 2026-09-01 --due 2026-09-30 --estimate 4h --done 40 --story-points 5
43
44
  op-cli wp list --search login # server-side subject search
44
45
  op-cli wp list --sort updatedAt:desc # repeatable; also --id <id>, --no-include-subprojects
@@ -51,6 +52,9 @@ op-cli time log 42 --hours 1h30m --activity Development
51
52
  op-cli time report --from 2026-08-01 --to 2026-08-31 # closed period
52
53
  op-cli project member add web alice Manager # join members so assignment works
53
54
  op-cli project list --search web
55
+ op-cli query list --starred # saved work package views; `query get <id-or-name>` shows one
56
+ op-cli query create Roadmap --open --assignee me --sort dueDate:desc --public # filter flags as in wp list
57
+ op-cli query update Roadmap --name Plan --clear-filters # change only the flags you pass
54
58
  op-cli wp move 42 archive # move a work package to another project
55
59
  op-cli doctor # diagnose connectivity, credentials, versions
56
60
  op-cli update # self-update; prints the right command for Volta/Homebrew
@@ -3,6 +3,7 @@ import { OpCliError, writeRefusal } from "../core/errors.js";
3
3
  import { filtersQuery } from "../core/filters.js";
4
4
  import { emitRows, PAGED_JSON_HELP, } from "../core/define.js";
5
5
  import { flattenHalRecord, toFormattable } from "../core/hal.js";
6
+ import { readDate } from "../core/scalars.js";
6
7
  import { apiDelete, apiGet, apiPatchRaw, apiPost, apiPostRaw, authenticate, } from "../core/http.js";
7
8
  import { DEFAULT_PAGE_SIZE, allPageSize, halElements, parsePageSize, withPageSize, } from "../core/paginate.js";
8
9
  import { isIdForm, rankByCloseness, resolveName, } from "../context/resolve.js";
@@ -55,6 +56,19 @@ async function connect(runtime, options) {
55
56
  function collectValue(value, previous) {
56
57
  return [...previous, value];
57
58
  }
59
+ const VERSIONS_COLLECTION = "/api/v3/versions";
60
+ const VERSION_STATUSES = ["open", "locked", "closed"];
61
+ const VERSION_SHARINGS = ["none", "descendants", "hierarchy", "tree", "system"];
62
+ /** One closed-vocabulary flag: absent stays undefined; empty or unknown is misuse. */
63
+ function readChoice(raw, flag, choices) {
64
+ if (raw === undefined) {
65
+ return undefined;
66
+ }
67
+ if (!choices.includes(raw)) {
68
+ throw new OpCliError("USAGE_ERROR", `${flag} "${raw}" is not one of ${choices.join(", ")}.`, `pass ${flag} with one of: ${choices.join(", ")}.`);
69
+ }
70
+ return raw;
71
+ }
58
72
  const PRINCIPALS_COLLECTION = "/api/v3/principals";
59
73
  const ROLES_COLLECTION = "/api/v3/roles";
60
74
  const MEMBERSHIPS_COLLECTION = "/api/v3/memberships";
@@ -128,13 +142,16 @@ async function resolveRoleIds(profile, raws) {
128
142
  * The shared tail of every single-record command: --fields validated
129
143
  * against the actual record, then the FIELD/VALUE table or picked JSON.
130
144
  */
131
- function selectedRecordFields(raw, record) {
145
+ function selectedRecordFields(raw, record,
146
+ /** What a completed write already did; a bad name must not invite a repeat. */
147
+ done) {
132
148
  const requested = [
133
149
  ...new Set(raw.split(",").map((name) => name.trim()).filter((name) => name !== "")),
134
150
  ];
135
151
  const first = requested.find((name) => !(name in record));
136
152
  if (first !== undefined) {
137
- throw new OpCliError("USAGE_ERROR", `field "${first}" is not a column. Valid fields, closest first: `
153
+ throw new OpCliError("USAGE_ERROR", `${done === undefined ? "" : `${done}; `}`
154
+ + `field "${first}" is not a column. Valid fields, closest first: `
138
155
  + `${rankByCloseness(first, Object.keys(record)).join(", ")}.`, "run the command without --fields to list every available field.");
139
156
  }
140
157
  return requested;
@@ -142,9 +159,9 @@ function selectedRecordFields(raw, record) {
142
159
  function renderFieldTable(fields, record) {
143
160
  return renderTable(["FIELD", "VALUE"], fields.map((field) => [field, formatCell(record[field])]));
144
161
  }
145
- function renderRecord(runtime, options, record) {
162
+ function renderRecord(runtime, options, record, done) {
146
163
  const fields = typeof options.fields === "string"
147
- ? selectedRecordFields(options.fields, record)
164
+ ? selectedRecordFields(options.fields, record, done)
148
165
  : Object.keys(record);
149
166
  if (options.json === true) {
150
167
  const picked = {};
@@ -163,16 +180,19 @@ function renderRecord(runtime, options, record) {
163
180
  * catalogue: 404 stays NOT_FOUND, 5xx becomes the unknown-state
164
181
  * NETWORK_ERROR, everything else carries the server's message.
165
182
  */
166
- async function projectWrite(attempt, verb) {
183
+ async function projectWrite(attempt, verb,
184
+ /** What to check before repeating, when "the project exists" is the wrong advice. */
185
+ check) {
186
+ const hint = check ?? (verb === "update"
187
+ ? "run op-cli project get to see the stored values before repeating the command."
188
+ : "check whether the project exists before repeating the command.");
167
189
  let response;
168
190
  try {
169
191
  response = await attempt();
170
192
  }
171
193
  catch (error) {
172
194
  if (error instanceof OpCliError && error.code === "NETWORK_ERROR") {
173
- throw new OpCliError("NETWORK_ERROR", `the ${verb} request did not complete; whether it was applied is unknown.`, verb === "update"
174
- ? "run op-cli project get to see the stored values before repeating the command."
175
- : "check whether the project exists before repeating the command.");
195
+ throw new OpCliError("NETWORK_ERROR", `the ${verb} request did not complete; whether it was applied is unknown.`, hint);
176
196
  }
177
197
  throw error;
178
198
  }
@@ -184,9 +204,7 @@ async function projectWrite(attempt, verb) {
184
204
  }
185
205
  if (response.status >= 500) {
186
206
  throw new OpCliError("NETWORK_ERROR", `the ${verb} failed with HTTP ${String(response.status)}; `
187
- + "whether it was applied is unknown.", verb === "update"
188
- ? "run op-cli project get to see the stored values before repeating the command."
189
- : "check whether the project exists before repeating the command.");
207
+ + "whether it was applied is unknown.", hint);
190
208
  }
191
209
  throw writeRefusal(verb, response.status, response.body);
192
210
  }
@@ -500,6 +518,69 @@ export function registerProjectCommands(project, runtime) {
500
518
  registerVocabulary("buckets", "List the backlog buckets a work package in this project may use", (hit) => `${PROJECTS_COLLECTION}/${String(hit.id)}/backlog_buckets`, BUCKET_COLUMNS, { moved: (projectId) => `${WORKSPACES_COLLECTION}/${String(projectId)}/backlog_buckets` });
501
519
  registerVocabulary("types", "List the work package types usable in this project", (hit) => hit.links?.types ?? `${PROJECTS_COLLECTION}/${String(hit.id)}/types`, TYPE_COLUMNS);
502
520
  // ---------------------------------------------------------------------------
521
+ // project version create
522
+ project
523
+ .command("version")
524
+ .description("Manage the versions of one project")
525
+ .command("create")
526
+ .description("Create one version in a project")
527
+ .argument("<reference>", "project, by id, identifier, or name")
528
+ .argument("<name>", "name of the new version")
529
+ .option("--description <text>", 'markdown description; "" stores an empty one')
530
+ .option("--status <status>", "open, locked, or closed (default open)")
531
+ .option("--sharing <mode>", "none, descendants, hierarchy, tree, or system (instance default if omitted)")
532
+ .option("--start <date>", 'start date YYYY-MM-DD; "" leaves it empty')
533
+ .option("--end <date>", 'end date YYYY-MM-DD; "" leaves it empty')
534
+ .option("--json", "emit a flat JSON record")
535
+ .option("--fields <list>", "comma-separated fields to show")
536
+ .option("--profile <name>", "use this profile for this command only")
537
+ .option("--project <name-or-id>", "override the profile default project")
538
+ .action(async (reference, name, options) => {
539
+ // Misuse is refused before any traffic, JSON mode included.
540
+ runtime.setJsonMode(options.json === true);
541
+ if (name.trim() === "") {
542
+ throw new OpCliError("USAGE_ERROR", "the version name is empty.", "give the new version a non-empty <name>.");
543
+ }
544
+ const status = readChoice(options.status ?? "open", "--status", VERSION_STATUSES);
545
+ const sharing = readChoice(options.sharing, "--sharing", VERSION_SHARINGS);
546
+ const start = options.start === undefined || options.start === ""
547
+ ? options.start
548
+ : readDate(options.start, "--start");
549
+ const end = options.end === undefined || options.end === ""
550
+ ? options.end
551
+ : readDate(options.end, "--end");
552
+ if (start !== undefined && end !== undefined && start !== "" && end !== "" && start > end) {
553
+ throw new OpCliError("USAGE_ERROR", `--start ${start} is after --end ${end}.`, "give a start date on or before the end date.");
554
+ }
555
+ const { getPage } = await connect(runtime, options);
556
+ const profile = await runtime.resolve({
557
+ profile: options.profile,
558
+ project: parseProjectOverride(options.project),
559
+ });
560
+ const hit = await resolveProjectRef(getPage, reference);
561
+ const payload = {
562
+ name: name.trim(),
563
+ status,
564
+ _links: { definingProject: { href: `${PROJECTS_COLLECTION}/${String(hit.id)}` } },
565
+ };
566
+ if (options.description !== undefined) {
567
+ payload.description = toFormattable(options.description);
568
+ }
569
+ if (sharing !== undefined) {
570
+ payload.sharing = sharing;
571
+ }
572
+ if (start !== undefined) {
573
+ payload.startDate = start === "" ? null : start;
574
+ }
575
+ if (end !== undefined) {
576
+ payload.endDate = end === "" ? null : end;
577
+ }
578
+ const body = await projectWrite(() => apiPostRaw(profile.instanceUrl, profile.apiKey, VERSIONS_COLLECTION, payload), "create", `run op-cli project versions ${reference} before repeating the command, `
579
+ + "so the version is not created twice.");
580
+ const created = flattenHalRecord(body);
581
+ renderRecord(runtime, options, created, `version ${String(created.id)} was created`);
582
+ });
583
+ // ---------------------------------------------------------------------------
503
584
  // project member add / remove
504
585
  const member = project
505
586
  .command("member")
@@ -0,0 +1,67 @@
1
+ import { OpCliError, unknownIfUnfinished, writeFailure } from "../core/errors.js";
2
+ import { apiDeleteRaw, apiPatchRaw } from "../core/http.js";
3
+ import { addQueryScopeOptions, connectQuery, flattenQueryRecord, QUERIES_COLLECTION, refuseDefault, renderQueryRecord, resolveSavedQuery, } from "./query.js";
4
+ function registerStar(query, runtime, verb) {
5
+ const past = verb === "star" ? "starred" : "unstarred";
6
+ addQueryScopeOptions(query
7
+ .command(verb)
8
+ .description(verb === "star"
9
+ ? "Mark one saved query as a favourite of the current user"
10
+ : "Remove one saved query from the current user's favourites")
11
+ .argument("<id-or-name>", "query id or exact name")
12
+ .option("--json", "emit a flat JSON record")
13
+ .option("--fields <list>", "comma-separated fields to show")).action(async (reference, options) => {
14
+ // JSON mode is set first so the refusal below is shaped for the caller.
15
+ runtime.setJsonMode(options.json === true);
16
+ refuseDefault(reference);
17
+ const connection = await connectQuery(runtime, options);
18
+ const { id } = await resolveSavedQuery(connection, reference);
19
+ const { instanceUrl, apiKey } = connection.profile;
20
+ const wording = {
21
+ action: verb,
22
+ unknown: `whether the query was ${past} is unknown`,
23
+ check: `run op-cli query get ${String(id)} to check its starred state before repeating the command.`,
24
+ };
25
+ const response = await unknownIfUnfinished(() => apiPatchRaw(instanceUrl, apiKey, `${QUERIES_COLLECTION}/${String(id)}/${verb}`, {}), wording);
26
+ if (response.status >= 400) {
27
+ throw writeFailure(response.status, response.body, wording);
28
+ }
29
+ renderQueryRecord(runtime, options, flattenQueryRecord(response.body), `query ${String(id)} was ${past}`);
30
+ });
31
+ }
32
+ function registerDelete(query, runtime) {
33
+ addQueryScopeOptions(query
34
+ .command("delete")
35
+ .description("Delete one saved query after explicit confirmation")
36
+ .argument("<id-or-name>", "query id or exact name")
37
+ .option("--yes", "confirm the deletion")).action(async (reference, options) => {
38
+ // The guard fires before any resolution or traffic.
39
+ if (options.yes !== true) {
40
+ throw new OpCliError("USAGE_ERROR", `query delete refuses to remove "${reference}" without confirmation; `
41
+ + "deleting a query is irreversible.", "repeat the command with --yes to confirm the deletion.");
42
+ }
43
+ refuseDefault(reference);
44
+ const connection = await connectQuery(runtime, options);
45
+ const ref = await resolveSavedQuery(connection, reference);
46
+ const { id } = ref;
47
+ const wording = {
48
+ action: "delete",
49
+ unknown: "whether the query was deleted is unknown",
50
+ check: "run op-cli query list before repeating the command.",
51
+ };
52
+ const { instanceUrl, apiKey } = connection.profile;
53
+ const response = await unknownIfUnfinished(() => apiDeleteRaw(instanceUrl, apiKey, `${QUERIES_COLLECTION}/${String(id)}`), wording);
54
+ if (response.status >= 400) {
55
+ throw writeFailure(response.status, response.body, wording);
56
+ }
57
+ runtime.write(ref.name === undefined
58
+ ? `Deleted query ${String(id)}.\n`
59
+ : `Deleted query ${ref.name} (${String(id)}).\n`);
60
+ });
61
+ }
62
+ export function registerQueryManage(query, runtime) {
63
+ registerStar(query, runtime, "star");
64
+ registerStar(query, runtime, "unstar");
65
+ registerDelete(query, runtime);
66
+ }
67
+ //# sourceMappingURL=query-manage.js.map
@@ -0,0 +1,115 @@
1
+ import { OpCliError } from "../core/errors.js";
2
+ import { PAGED_JSON_HELP } from "../core/define.js";
3
+ import { flattenHalRecord } from "../core/hal.js";
4
+ import { allPageSize, halElements, parsePageSize, withPageSize } from "../core/paginate.js";
5
+ import { rankByCloseness } from "../context/resolve.js";
6
+ import { instancePathOf } from "../context/projectref.js";
7
+ import { formatCell, renderTable } from "../output/table.js";
8
+ import { addQueryScopeOptions, connectQuery, fetchQuery, lastSegment, resolveQueryRef, } from "./query.js";
9
+ import { LIST_COLUMNS } from "./wp.js";
10
+ /** The href without its pageSize, so the page size is set exactly once. */
11
+ function withoutPageSize(path) {
12
+ const [base = "", query] = path.split("?", 2);
13
+ const kept = (query ?? "").split("&").filter((part) => part !== "" && !part.startsWith("pageSize="));
14
+ return kept.length === 0 ? base : `${base}?${kept.join("&")}`;
15
+ }
16
+ /**
17
+ * The results path of a Query resource: the link the server gave, cut to
18
+ * start at /api/v3 so an instance subpath is not added twice. Without that
19
+ * link the filters of the query would be lost, so it fails loudly.
20
+ */
21
+ function resultsEndpointOf(query) {
22
+ const links = (query._links ?? {});
23
+ const href = links.results?.href;
24
+ const path = typeof href === "string" && href !== "" ? instancePathOf(href) : undefined;
25
+ if (path === undefined) {
26
+ throw new OpCliError("API_ERROR", "the query response carried no results link.", "check the instance version with op-cli doctor.");
27
+ }
28
+ return withoutPageSize(path);
29
+ }
30
+ /** The columns the query shows; the fixed work package columns when it defines none. */
31
+ function queryColumns(query) {
32
+ const links = (query._links ?? {});
33
+ const defined = Array.isArray(links.columns) ? links.columns : [];
34
+ const columns = defined.flatMap((link) => {
35
+ if (typeof link.href !== "string" || link.href === "") {
36
+ return [];
37
+ }
38
+ const field = lastSegment(link.href);
39
+ if (field === undefined) {
40
+ return [];
41
+ }
42
+ const title = typeof link.title === "string" && link.title !== "" ? link.title : field;
43
+ return [{ title: title.toUpperCase(), field }];
44
+ });
45
+ return columns.length === 0 ? LIST_COLUMNS : columns;
46
+ }
47
+ function fieldList(raw) {
48
+ return [...new Set(raw.split(",").map((name) => name.trim()).filter((name) => name !== ""))];
49
+ }
50
+ function requireFields(record, fields) {
51
+ const missing = fields.find((name) => !(name in record));
52
+ if (missing !== undefined) {
53
+ throw new OpCliError("USAGE_ERROR", `field "${missing}" is not a column. Valid fields, closest first: `
54
+ + `${rankByCloseness(missing, Object.keys(record)).join(", ")}.`, "run the command without --fields to list every available column.");
55
+ }
56
+ }
57
+ function pick(record, fields) {
58
+ return Object.fromEntries(fields.map((field) => [field, record[field]]));
59
+ }
60
+ export function registerQueryRun(query, runtime) {
61
+ addQueryScopeOptions(query
62
+ .command("run")
63
+ .description('Run a query and show its work packages, by id, name, or "default"')
64
+ .argument("<id-or-name>", 'query id, exact name, or "default"')
65
+ .option("--json", PAGED_JSON_HELP)
66
+ .option("--fields <list>", "comma-separated columns to show")
67
+ .option("--limit <n>", "maximum number of results to show")
68
+ .option("--all", "fetch every page instead of one limited page")).action(async (reference, options) => {
69
+ runtime.setJsonMode(options.json === true);
70
+ // Flag misuse is refused before any traffic.
71
+ const limit = parsePageSize(options.limit);
72
+ const connection = await connectQuery(runtime, options);
73
+ const resource = await fetchQuery(connection, await resolveQueryRef(connection, reference));
74
+ const endpoint = resultsEndpointOf(resource);
75
+ const { getPage: readPage } = connection;
76
+ const size = options.all === true ? await allPageSize(readPage) : limit;
77
+ const first = withPageSize(endpoint, size);
78
+ const requested = options.fields === undefined ? undefined : fieldList(options.fields);
79
+ const view = requested === undefined
80
+ ? queryColumns(resource)
81
+ : requested.map((field) => ({ title: field.toUpperCase(), field }));
82
+ const flatten = (element) => {
83
+ const record = flattenHalRecord(element);
84
+ if (requested !== undefined) {
85
+ requireFields(record, requested);
86
+ }
87
+ return record;
88
+ };
89
+ const table = (records) => renderTable(view.map((column) => column.title), records.map((record) => view.map((column) => formatCell(record[column.field]))));
90
+ const shaped = (record) => requested === undefined ? record : pick(record, requested);
91
+ if (options.all === true) {
92
+ if (options.json === true) {
93
+ for await (const element of halElements(readPage, first)) {
94
+ runtime.write(`${JSON.stringify(shaped(flatten(element)))}\n`);
95
+ }
96
+ return;
97
+ }
98
+ const records = [];
99
+ for await (const element of halElements(readPage, first)) {
100
+ records.push(flatten(element));
101
+ }
102
+ runtime.write(table(records));
103
+ return;
104
+ }
105
+ const page = (await readPage(first));
106
+ const records = (page._embedded?.elements ?? []).map(flatten);
107
+ runtime.write(options.json === true ? `${JSON.stringify(records.map(shaped))}\n` : table(records));
108
+ const total = typeof page.total === "number" ? page.total : records.length;
109
+ if (total > records.length) {
110
+ runtime.writeErr(`Showing ${String(records.length)} of ${String(total)} work packages. `
111
+ + "Pass --all to fetch every result.\n");
112
+ }
113
+ });
114
+ }
115
+ //# sourceMappingURL=query-run.js.map
@@ -0,0 +1,309 @@
1
+ import { OpCliError, refuseCombined, unknownIfUnfinished, writeFailure } from "../core/errors.js";
2
+ import { buildWpFilters, parseSort } from "../core/filters.js";
3
+ import { apiPatchRaw, apiPostRaw } from "../core/http.js";
4
+ import { halRefId } from "../core/hal.js";
5
+ import { parseProjectOverride } from "../context/profile.js";
6
+ import { addFilterFlags, collectOptional, rawListFlags, resolveListFlags, } from "./wp.js";
7
+ import { addQueryScopeOptions, connectQuery, fetchQuery, flattenQueryRecord, QUERIES_COLLECTION, refuseDefault, renderQueryRecord, resolveSavedQuery, } from "./query.js";
8
+ const QUERY_FIELDS = Object.keys(flattenQueryRecord({}));
9
+ const CREATE_WORDING = {
10
+ action: "create",
11
+ unknown: "whether the query was created is unknown",
12
+ check: "run op-cli query list to see whether the query exists before repeating the command.",
13
+ };
14
+ /** What to say when an update may or may not have landed. */
15
+ function updateWording(id) {
16
+ return {
17
+ action: "update",
18
+ unknown: "whether the query was changed is unknown",
19
+ check: `run op-cli query get ${String(id)} to see the stored values before repeating the command.`,
20
+ };
21
+ }
22
+ /** The view flags every write accepts; one spelling for both commands. */
23
+ function addViewOptions(command) {
24
+ return command
25
+ .option("--public [bool]", "visible to everybody: true or false (bare means true)")
26
+ .option("--starred [bool]", "starred for you: true or false (bare means true)")
27
+ .option("--sums [bool]", "show sums: true or false (bare means true)")
28
+ .option("--hierarchies [bool]", "show the work package hierarchy: true or false (bare means true)")
29
+ .option("--sort <field[:asc|desc]>", "sort order; repeat for more fields", collectOptional)
30
+ .option("--columns <list>", "comma-separated column names, in order")
31
+ .option("--group-by <field>", "group results by this field")
32
+ .option("--json", "emit a flat JSON record")
33
+ .option("--fields <list>", "comma-separated fields to show");
34
+ }
35
+ function booleanFlag(raw, flag) {
36
+ if (raw === undefined || raw === true) {
37
+ return raw;
38
+ }
39
+ const lowered = String(raw).trim().toLowerCase();
40
+ if (lowered !== "true" && lowered !== "false") {
41
+ throw new OpCliError("USAGE_ERROR", `--${flag} accepts true or false, not "${String(raw)}".`, `pass --${flag}, --${flag} true, or --${flag} false.`);
42
+ }
43
+ return lowered === "true";
44
+ }
45
+ function viewOf(options, mode) {
46
+ const attributes = {};
47
+ const links = {};
48
+ const flags = [
49
+ ["public", "public", options.public],
50
+ ["starred", "starred", options.starred],
51
+ ["sums", "sums", options.sums],
52
+ ["hierarchies", "showHierarchies", options.hierarchies],
53
+ ];
54
+ for (const [flag, attribute, raw] of flags) {
55
+ const value = booleanFlag(raw, flag);
56
+ if (value !== undefined) {
57
+ attributes[attribute] = value;
58
+ }
59
+ }
60
+ const sort = options.sort;
61
+ if (sort !== undefined) {
62
+ const clears = mode === "update" && sort.length === 1 && sort[0]?.trim() === "";
63
+ links.sortBy = clears
64
+ ? []
65
+ : parseSort(sort).map(([field, direction]) => ({
66
+ href: `${QUERIES_COLLECTION}/sort_bys/${field}-${direction}`,
67
+ }));
68
+ }
69
+ if (options.columns !== undefined) {
70
+ if (options.columns.trim() === "" && mode === "update") {
71
+ links.columns = [];
72
+ }
73
+ else {
74
+ const names = options.columns.split(",").map((name) => name.trim());
75
+ if (names.some((name) => name === "")) {
76
+ throw new OpCliError("USAGE_ERROR", "--columns needs a comma-separated list of column names, none empty.", "pass e.g. --columns id,subject,status.");
77
+ }
78
+ links.columns = names.map((name) => ({
79
+ href: `${QUERIES_COLLECTION}/columns/${name}`,
80
+ }));
81
+ }
82
+ }
83
+ if (options.groupBy !== undefined) {
84
+ const field = options.groupBy.trim();
85
+ if (field === "") {
86
+ if (mode === "create") {
87
+ throw new OpCliError("USAGE_ERROR", "--group-by needs a field name.", "pass e.g. --group-by status; leave the flag out for no grouping.");
88
+ }
89
+ links.groupBy = { href: null };
90
+ }
91
+ else {
92
+ links.groupBy = { href: `${QUERIES_COLLECTION}/group_bys/${field}` };
93
+ }
94
+ }
95
+ return { attributes, links };
96
+ }
97
+ /** The Query filter id a work package filter name goes by. */
98
+ function queryFilterId(name) {
99
+ switch (name) {
100
+ case "assigned_to":
101
+ return "assignee";
102
+ case "created_at":
103
+ return "createdAt";
104
+ case "updated_at":
105
+ return "updatedAt";
106
+ default:
107
+ return name;
108
+ }
109
+ }
110
+ /** Filters whose values are linked resources, by the collection they live in. */
111
+ const LINKED_VALUES = {
112
+ status: "statuses",
113
+ type: "types",
114
+ assignee: "users",
115
+ responsible: "users",
116
+ author: "users",
117
+ watcher: "users",
118
+ version: "versions",
119
+ observedInVersion: "versions",
120
+ category: "categories",
121
+ sprint: "sprints",
122
+ backlogBucket: "backlog_buckets",
123
+ priority: "priorities",
124
+ parent: "work_packages",
125
+ };
126
+ /** One filter clause as a Query filter instance in HAL form. */
127
+ export function queryFilterInstance(clause) {
128
+ const id = queryFilterId(clause.name);
129
+ const links = {
130
+ filter: { href: `${QUERIES_COLLECTION}/filters/${id}` },
131
+ operator: {
132
+ href: `${QUERIES_COLLECTION}/operators/${encodeURIComponent(clause.operator)}`,
133
+ },
134
+ };
135
+ const collection = LINKED_VALUES[id];
136
+ if (collection !== undefined) {
137
+ links.values = clause.values.map((value) => ({ href: `/api/v3/${collection}/${value}` }));
138
+ return { _links: links };
139
+ }
140
+ return {
141
+ values: id === "backlogInbox" ? [true] : [...clause.values],
142
+ _links: links,
143
+ };
144
+ }
145
+ /** The filters the flags name, without the project scope a query keeps elsewhere. */
146
+ function queryFilters(flags) {
147
+ return buildWpFilters({ ...flags, project: undefined, includeSubprojects: undefined }, new Date())
148
+ .filter((clause) => clause.name !== "project" && clause.name !== "subprojectId")
149
+ .map(queryFilterInstance);
150
+ }
151
+ const PROJECT_ONLY_FLAGS = [
152
+ ["version", "--version"],
153
+ ["observedIn", "--observed-in"],
154
+ ["category", "--category"],
155
+ ["sprint", "--sprint"],
156
+ ["bucket", "--bucket"],
157
+ ];
158
+ function requireProjectForNames(options, projectId) {
159
+ if (projectId !== undefined) {
160
+ return;
161
+ }
162
+ for (const [key, flag] of PROJECT_ONLY_FLAGS) {
163
+ const value = options[key];
164
+ if (Array.isArray(value) && value.length > 0) {
165
+ throw new OpCliError("USAGE_ERROR", `${flag} needs a project in context to resolve names.`, "pass --project <name-or-id> or set a default project on the profile.");
166
+ }
167
+ }
168
+ }
169
+ async function resolvedFilters(runtime, profile, options, projectId) {
170
+ requireProjectForNames(options, projectId);
171
+ const resolved = await resolveListFlags({ ...runtime, writeBytes: () => undefined }, projectId === undefined ? { ...profile, project: undefined } : profile, options);
172
+ return queryFilters(resolved);
173
+ }
174
+ function checkFields(fields) {
175
+ if (fields === undefined) {
176
+ return;
177
+ }
178
+ const unknown = fields.split(",").map((name) => name.trim()).find((name) => name !== "" && !QUERY_FIELDS.includes(name));
179
+ if (unknown !== undefined) {
180
+ throw new OpCliError("USAGE_ERROR", `field "${unknown}" is not a column. Valid fields: ${QUERY_FIELDS.join(", ")}.`, "run op-cli query get to list every available field.");
181
+ }
182
+ }
183
+ function checkName(raw, flag) {
184
+ const name = raw.trim();
185
+ if (name === "") {
186
+ throw new OpCliError("USAGE_ERROR", `${flag === "name" ? "the query name" : "--name"} cannot be blank.`, "give the query a name.");
187
+ }
188
+ return name;
189
+ }
190
+ function registerCreate(query, runtime) {
191
+ addViewOptions(addFilterFlags(query
192
+ .command("create")
193
+ .description("Create a saved work package query")
194
+ .argument("<name>", "name of the new query")
195
+ .option("--global", "make a query that belongs to no project"))).action(async (rawName, options) => {
196
+ runtime.setJsonMode(options.json === true);
197
+ const name = checkName(rawName, "name");
198
+ refuseCombined([options.global === true ? "--global" : undefined, options.project === undefined ? undefined : "--project"], "pass only one of --project or --global.");
199
+ const view = viewOf(options, "create");
200
+ // Flag conflicts among the filters are refused here, before any traffic.
201
+ queryFilters(rawListFlags(options));
202
+ const profile = await runtime.resolve({
203
+ profile: options.profile,
204
+ project: parseProjectOverride(options.project),
205
+ });
206
+ const projectId = options.global === true ? undefined : profile.project;
207
+ const filters = await resolvedFilters(runtime, profile, options, projectId);
208
+ const payload = {
209
+ name,
210
+ ...view.attributes,
211
+ ...(options.includeSubprojects === undefined
212
+ ? {}
213
+ : { includeSubprojects: options.includeSubprojects }),
214
+ ...(filters.length > 0 ? { filters } : {}),
215
+ _links: {
216
+ project: projectId === undefined
217
+ ? { href: null }
218
+ : { href: `/api/v3/projects/${String(projectId)}` },
219
+ ...view.links,
220
+ },
221
+ };
222
+ const response = await unknownIfUnfinished(() => apiPostRaw(profile.instanceUrl, profile.apiKey, QUERIES_COLLECTION, payload), CREATE_WORDING);
223
+ if (response.status >= 400) {
224
+ throw writeFailure(response.status, response.body, CREATE_WORDING);
225
+ }
226
+ const record = flattenQueryRecord(response.body);
227
+ renderQueryRecord(runtime, options, record, `query ${String(record.id)} was created`);
228
+ });
229
+ }
230
+ /**
231
+ * The project whose names the filter flags resolve against: none for
232
+ * --global, the one given by --project, otherwise the project of the query
233
+ * being changed when a flag needs one, else the profile's default.
234
+ */
235
+ async function filterProjectOf(connection, ref, options) {
236
+ if (options.global === true) {
237
+ return undefined;
238
+ }
239
+ if (options.project !== undefined) {
240
+ return connection.profile.project;
241
+ }
242
+ const needsProject = PROJECT_ONLY_FLAGS.some(([key]) => {
243
+ const value = options[key];
244
+ return Array.isArray(value) && value.length > 0;
245
+ });
246
+ if (!needsProject) {
247
+ return connection.profile.project;
248
+ }
249
+ const existing = (await fetchQuery(connection, ref));
250
+ const href = existing._links?.project?.href;
251
+ return halRefId(typeof href === "string" ? href : null) ?? undefined;
252
+ }
253
+ function registerUpdate(query, runtime) {
254
+ addQueryScopeOptions(addViewOptions(addFilterFlags(query
255
+ .command("update")
256
+ .description("Change a saved query by id or name; only the flags you pass change")
257
+ .argument("<id-or-name>", "query id or exact name")
258
+ .option("--name <text>", "new name")
259
+ .option("--clear-filters", "remove every filter"), false))).action(async (reference, options) => {
260
+ runtime.setJsonMode(options.json === true);
261
+ refuseDefault(reference);
262
+ const name = options.name === undefined ? undefined : checkName(options.name, "--name");
263
+ checkFields(options.fields);
264
+ const view = viewOf(options, "update");
265
+ const named = queryFilters(rawListFlags(options));
266
+ refuseCombined([options.clearFilters === true ? "--clear-filters" : undefined, named.length > 0 ? "a filter flag" : undefined], "--clear-filters removes every filter; it cannot be combined with filter flags.");
267
+ const touches = name !== undefined
268
+ || options.clearFilters === true
269
+ || named.length > 0
270
+ || options.includeSubprojects !== undefined
271
+ || Object.keys(view.attributes).length > 0
272
+ || Object.keys(view.links).length > 0;
273
+ if (!touches) {
274
+ throw new OpCliError("USAGE_ERROR", "query update needs at least one thing to change.", "pass --name, --clear-filters, a filter flag, or a view flag such as --sort or --public.");
275
+ }
276
+ const connection = await connectQuery(runtime, options);
277
+ const ref = await resolveSavedQuery(connection, reference);
278
+ const wording = updateWording(ref.id);
279
+ const { profile } = connection;
280
+ const filterProject = named.length > 0
281
+ ? await filterProjectOf(connection, ref, options)
282
+ : undefined;
283
+ const filters = named.length > 0
284
+ ? await resolvedFilters(runtime, { ...profile, project: filterProject }, options, filterProject)
285
+ : [];
286
+ const links = view.links;
287
+ const payload = {
288
+ ...(name === undefined ? {} : { name }),
289
+ ...view.attributes,
290
+ ...(options.includeSubprojects === undefined
291
+ ? {}
292
+ : { includeSubprojects: options.includeSubprojects }),
293
+ ...(options.clearFilters === true ? { filters: [] } : {}),
294
+ ...(named.length > 0 ? { filters } : {}),
295
+ ...(Object.keys(links).length > 0 ? { _links: links } : {}),
296
+ };
297
+ const response = await unknownIfUnfinished(() => apiPatchRaw(profile.instanceUrl, profile.apiKey, `${QUERIES_COLLECTION}/${String(ref.id)}`, payload), wording);
298
+ if (response.status >= 400) {
299
+ throw writeFailure(response.status, response.body, wording);
300
+ }
301
+ const record = flattenQueryRecord(response.body);
302
+ renderQueryRecord(runtime, options, record, `query ${String(record.id ?? ref.id)} was updated`);
303
+ });
304
+ }
305
+ export function registerQueryWrite(query, runtime) {
306
+ registerCreate(query, runtime);
307
+ registerUpdate(query, runtime);
308
+ }
309
+ //# sourceMappingURL=query-write.js.map
@@ -0,0 +1,330 @@
1
+ import { formatCell, renderTable } from "../output/table.js";
2
+ import { registerQueryRun } from "./query-run.js";
3
+ import { registerQueryManage } from "./query-manage.js";
4
+ import { OpCliError, refuseCombined } from "../core/errors.js";
5
+ import { filtersQuery } from "../core/filters.js";
6
+ import { emitRows, PAGED_JSON_HELP, rowViewOf, } from "../core/define.js";
7
+ import { flattenHalLink, flattenHalRecord, halRefId } from "../core/hal.js";
8
+ import { apiGet } from "../core/http.js";
9
+ import { DEFAULT_PAGE_SIZE, allPageSize, halElements, parsePageSize, withPageSize, } from "../core/paginate.js";
10
+ import { isIdForm, matchByName, rankByCloseness } from "../context/resolve.js";
11
+ import { parseProjectOverride, } from "../context/profile.js";
12
+ import { registerQueryWrite } from "./query-write.js";
13
+ import { PROJECTS_COLLECTION, withMovedRetry, WORKSPACES_COLLECTION, } from "../context/projectref.js";
14
+ export const QUERIES_COLLECTION = "/api/v3/queries";
15
+ export const QUERY_COLUMNS = [
16
+ { title: "ID", field: "id" },
17
+ { title: "NAME", field: "name" },
18
+ { title: "PROJECT", field: "project" },
19
+ { title: "STARRED", field: "starred" },
20
+ { title: "PUBLIC", field: "public" },
21
+ ];
22
+ /** Declares the scope flags on one command; the single spelling of them. */
23
+ export function addQueryScopeOptions(command) {
24
+ return command
25
+ .option("--profile <name>", "use this profile for this command only")
26
+ .option("--project <name-or-id>", "only queries of this project")
27
+ .option("--global", "only queries that belong to no project")
28
+ .option("--all-projects", "queries of every project, ignoring the default project");
29
+ }
30
+ /** Flag misuse is refused here, before any traffic. */
31
+ export function checkQueryScopeFlags(options) {
32
+ refuseCombined([
33
+ options.global === true ? "--global" : undefined,
34
+ options.allProjects === true ? "--all-projects" : undefined,
35
+ options.project === undefined ? undefined : "--project",
36
+ ], "pass only one of --project, --global, or --all-projects.");
37
+ }
38
+ /** The scope the flags and the profile's default project select. */
39
+ export function queryScopeOf(options, profile) {
40
+ if (options.global === true) {
41
+ return { kind: "global" };
42
+ }
43
+ if (options.allProjects === true || profile.project === undefined) {
44
+ return { kind: "all" };
45
+ }
46
+ return { kind: "project", id: profile.project };
47
+ }
48
+ /** The shared opening: JSON mode, flag checks, the profile, the scope. */
49
+ export async function connectQuery(runtime, options) {
50
+ runtime.setJsonMode(options.json === true);
51
+ checkQueryScopeFlags(options);
52
+ const profile = await runtime.resolve({
53
+ profile: options.profile,
54
+ project: parseProjectOverride(options.project),
55
+ });
56
+ return {
57
+ getPage: (path) => apiGet(profile.instanceUrl, profile.apiKey, path),
58
+ scope: queryScopeOf(options, profile),
59
+ profile,
60
+ };
61
+ }
62
+ /** The collection path of the queries in scope, without pageSize. */
63
+ export function queriesPath(scope) {
64
+ const filters = [];
65
+ if (scope.kind === "project") {
66
+ filters.push({ name: "project", operator: "=", values: [String(scope.id)] });
67
+ }
68
+ else if (scope.kind === "global") {
69
+ filters.push({ name: "project", operator: "!*", values: [] });
70
+ }
71
+ return filters.length === 0
72
+ ? QUERIES_COLLECTION
73
+ : `${QUERIES_COLLECTION}?filters=${filtersQuery(filters)}`;
74
+ }
75
+ /** Where the default query of the scope lives; undefined for the global one. */
76
+ export function defaultQueryPath(scope) {
77
+ return scope.kind === "project"
78
+ ? `${WORKSPACES_COLLECTION}/${String(scope.id)}/queries/default`
79
+ : `${QUERIES_COLLECTION}/default`;
80
+ }
81
+ function defaultQueryFallbackPath(scope) {
82
+ return scope.kind === "project"
83
+ ? `${PROJECTS_COLLECTION}/${String(scope.id)}/queries/default`
84
+ : undefined;
85
+ }
86
+ function refuseDefaultQuery() {
87
+ throw new OpCliError("USAGE_ERROR", "the default query is not a saved query and cannot be modified.", "pass the id or exact name of a saved query; run op-cli query list to see them.");
88
+ }
89
+ /** The default query is a view of the scope, not a stored query. */
90
+ export function refuseDefault(reference) {
91
+ if (reference.trim() === "default") {
92
+ refuseDefaultQuery();
93
+ }
94
+ }
95
+ /** The last path segment of an href, decoded; undefined when there is none. */
96
+ export function lastSegment(href) {
97
+ if (typeof href !== "string") {
98
+ return undefined;
99
+ }
100
+ const tail = href.split("/").filter((part) => part !== "").pop();
101
+ return tail === undefined ? undefined : decodeURIComponent(tail);
102
+ }
103
+ async function walkQueries(connection) {
104
+ const found = [];
105
+ for await (const element of halElements(connection.getPage, withPageSize(queriesPath(connection.scope), DEFAULT_PAGE_SIZE))) {
106
+ if (typeof element.id !== "number" || typeof element.name !== "string") {
107
+ continue;
108
+ }
109
+ const project = flattenHalLink(element._links?.project);
110
+ found.push({
111
+ id: element.id,
112
+ name: element.name,
113
+ owner: project.id === null ? "global" : `project ${project.name ?? String(project.id)}`,
114
+ });
115
+ }
116
+ return found;
117
+ }
118
+ /**
119
+ * A query reference to what it names. A number is an id and a bare
120
+ * "default" is the scope's default query; anything else is an exact name
121
+ * matched live over the queries in scope, because queries are not part of
122
+ * the stored metadata. Ambiguity and a miss fail loudly.
123
+ */
124
+ export async function resolveQueryRef(connection, raw) {
125
+ if (isIdForm(raw)) {
126
+ return { kind: "id", id: Number(raw) };
127
+ }
128
+ if (raw === "default") {
129
+ return { kind: "default" };
130
+ }
131
+ const candidates = await walkQueries(connection);
132
+ const match = matchByName(raw, candidates.map((candidate) => ({
133
+ name: candidate.name,
134
+ owner: candidate.owner,
135
+ value: candidate.id,
136
+ })));
137
+ if (match.kind === "unique") {
138
+ return { kind: "id", id: match.entry.value, name: match.entry.name };
139
+ }
140
+ if (match.kind === "ambiguous") {
141
+ const listed = match.candidates
142
+ .map((candidate) => `${String(candidate.value)} (${candidate.owner})`)
143
+ .join(", ");
144
+ throw new OpCliError("USAGE_ERROR", `query "${raw}" is ambiguous. Candidates: ${listed}.`, "repeat the command with the numeric id of one candidate, or narrow with --project or --global.");
145
+ }
146
+ throw new OpCliError("USAGE_ERROR", candidates.length === 0
147
+ ? `query "${raw}" not found; no query is visible in this scope.`
148
+ : `query "${raw}" not found. Valid values, closest first: `
149
+ + `${rankByCloseness(raw, candidates.map((candidate) => candidate.name)).join(", ")}.`, "run op-cli query list to see the queries you can address.");
150
+ }
151
+ /** Like resolveQueryRef, but a reference to the default query is refused. */
152
+ export async function resolveSavedQuery(connection, raw) {
153
+ const ref = await resolveQueryRef(connection, raw);
154
+ if (ref.kind !== "id") {
155
+ refuseDefaultQuery();
156
+ }
157
+ return ref;
158
+ }
159
+ /** The raw Query resource a reference names. */
160
+ export async function fetchQuery(connection, ref) {
161
+ if (ref.kind === "id") {
162
+ return connection.getPage(`${QUERIES_COLLECTION}/${String(ref.id)}`);
163
+ }
164
+ const fallback = defaultQueryFallbackPath(connection.scope);
165
+ const first = defaultQueryPath(connection.scope);
166
+ return fallback === undefined
167
+ ? connection.getPage(first)
168
+ : withMovedRetry(() => connection.getPage(first), () => connection.getPage(fallback));
169
+ }
170
+ function filterSummary(filter) {
171
+ const body = filter;
172
+ const links = body._links ?? {};
173
+ const linked = Array.isArray(links.values)
174
+ ? links.values.map((value) => {
175
+ const href = value.href;
176
+ return halRefId(typeof href === "string" ? href : null)?.toString() ?? lastSegment(href) ?? "";
177
+ })
178
+ : [];
179
+ const plain = Array.isArray(body.values) ? body.values.map(String) : [];
180
+ return {
181
+ field: lastSegment(links.filter?.href) ?? null,
182
+ operator: lastSegment(links.operator?.href) ?? null,
183
+ values: [...plain, ...linked],
184
+ };
185
+ }
186
+ function linkList(links) {
187
+ return Array.isArray(links) ? links : [];
188
+ }
189
+ function sortSummary(href) {
190
+ const key = lastSegment(href);
191
+ const split = key?.lastIndexOf("-") ?? -1;
192
+ return key === undefined || split < 0
193
+ ? key
194
+ : `${key.slice(0, split)}:${key.slice(split + 1)}`;
195
+ }
196
+ /**
197
+ * One Query resource as a flat record: every attribute the server sent
198
+ * (ADR-0003), with `{ id, name }` for project, user, and group-by, the
199
+ * columns and sort order as plain strings, and the filters as
200
+ * `{ field, operator, values }`. The embedded results are dropped:
201
+ * running a query is its own command.
202
+ */
203
+ export function flattenQueryRecord(element) {
204
+ const query = element;
205
+ // The filters are summarised below; their plain `values` arrays are not
206
+ // resources, which the generic flattening cannot take.
207
+ const withoutFilters = { ...query };
208
+ delete withoutFilters.filters;
209
+ const base = flattenHalRecord(withoutFilters);
210
+ delete base.results;
211
+ const links = query._links ?? {};
212
+ return {
213
+ ...base,
214
+ id: query.id ?? null,
215
+ name: query.name ?? null,
216
+ project: flattenHalLink(links.project),
217
+ user: flattenHalLink(links.user),
218
+ starred: query.starred ?? null,
219
+ public: query.public ?? null,
220
+ sums: query.sums ?? null,
221
+ includeSubprojects: query.includeSubprojects ?? null,
222
+ showHierarchies: query.showHierarchies ?? null,
223
+ groupBy: flattenHalLink(links.groupBy),
224
+ columns: linkList(links.columns)
225
+ .map((link) => lastSegment(link.href))
226
+ .filter((name) => name !== undefined),
227
+ sortBy: linkList(links.sortBy)
228
+ .map((link) => sortSummary(link.href))
229
+ .filter((sort) => sort !== undefined),
230
+ filters: Array.isArray(query.filters) ? query.filters.map(filterSummary) : [],
231
+ createdAt: query.createdAt ?? null,
232
+ updatedAt: query.updatedAt ?? null,
233
+ };
234
+ }
235
+ /** Renders one flat query record as a FIELD/VALUE table or picked JSON. */
236
+ export function renderQueryRecord(runtime, options, record, done) {
237
+ const requested = typeof options.fields === "string"
238
+ ? [
239
+ ...new Set(options.fields.split(",").map((name) => name.trim()).filter((name) => name !== "")),
240
+ ]
241
+ : Object.keys(record);
242
+ const unknown = requested.find((name) => !(name in record));
243
+ if (unknown !== undefined) {
244
+ throw new OpCliError("USAGE_ERROR", `${done === undefined ? "" : `${done}; `}field "${unknown}" is not a column. Valid fields, closest first: `
245
+ + `${rankByCloseness(unknown, Object.keys(record)).join(", ")}.`, "run the command without --fields to list every available field.");
246
+ }
247
+ if (options.json === true) {
248
+ runtime.write(`${JSON.stringify(Object.fromEntries(requested.map((field) => [field, record[field]])))}\n`);
249
+ return;
250
+ }
251
+ runtime.write(renderTable(["FIELD", "VALUE"], requested.map((field) => [field, formatCell(record[field])])));
252
+ }
253
+ function registerList(query, runtime) {
254
+ addQueryScopeOptions(query
255
+ .command("list")
256
+ .description("List visible queries (saved work package queries)")
257
+ .option("--starred", "only queries you starred")
258
+ .option("--json", PAGED_JSON_HELP)
259
+ .option("--fields <list>", "comma-separated columns to show")
260
+ .option("--limit <n>", "maximum number of results to show")
261
+ .option("--all", "fetch every page instead of one limited page")).action(async (options) => {
262
+ runtime.setJsonMode(options.json === true);
263
+ // Flag misuse is refused before any traffic.
264
+ const { pick } = rowViewOf(QUERY_COLUMNS, options);
265
+ const limit = parsePageSize(options.limit);
266
+ const { getPage, scope } = await connectQuery(runtime, options);
267
+ const basePath = queriesPath(scope);
268
+ const keep = (row) => options.starred !== true || row.starred === true;
269
+ // The starred flag is applied here, not by the server: the filter set
270
+ // of the collection is not documented for it. A client-side filter
271
+ // needs every page, or a short first page could hide a starred query.
272
+ const walkAll = options.all === true || options.starred === true;
273
+ if (walkAll) {
274
+ const startPath = withPageSize(basePath, await allPageSize(getPage));
275
+ const rows = [];
276
+ for await (const element of halElements(getPage, startPath)) {
277
+ const row = flattenQueryRecord(element);
278
+ if (!keep(row)) {
279
+ continue;
280
+ }
281
+ if (options.all === true && options.json === true) {
282
+ runtime.write(`${JSON.stringify(pick(row))}\n`);
283
+ }
284
+ else {
285
+ rows.push(row);
286
+ }
287
+ }
288
+ if (options.all === true && options.json === true) {
289
+ return;
290
+ }
291
+ const shown = options.all === true ? rows : rows.slice(0, limit);
292
+ emitRows(runtime, QUERY_COLUMNS, shown, options);
293
+ if (shown.length < rows.length) {
294
+ runtime.writeErr(`Showing ${String(shown.length)} of ${String(rows.length)} queries. `
295
+ + "Pass --all to fetch every result.\n");
296
+ }
297
+ return;
298
+ }
299
+ const page = (await getPage(withPageSize(basePath, limit)));
300
+ const elements = page._embedded?.elements ?? [];
301
+ const shown = elements.slice(0, limit).map(flattenQueryRecord);
302
+ emitRows(runtime, QUERY_COLUMNS, shown, options);
303
+ const total = Math.max(typeof page.total === "number" ? page.total : elements.length, elements.length);
304
+ if (total > shown.length) {
305
+ runtime.writeErr(`Showing ${String(shown.length)} of ${String(total)} queries. `
306
+ + "Pass --all to fetch every result.\n");
307
+ }
308
+ });
309
+ }
310
+ function registerGet(query, runtime) {
311
+ addQueryScopeOptions(query
312
+ .command("get")
313
+ .description('Show one query by id, name, or "default"')
314
+ .argument("<id-or-name>", 'query id, exact name, or "default"')
315
+ .option("--json", "emit a flat JSON record")
316
+ .option("--fields <list>", "comma-separated fields to show")).action(async (reference, options) => {
317
+ const connection = await connectQuery(runtime, options);
318
+ const ref = await resolveQueryRef(connection, reference);
319
+ renderQueryRecord(runtime, options, flattenQueryRecord(await fetchQuery(connection, ref)));
320
+ });
321
+ }
322
+ export function registerQueryCommands(query, runtime) {
323
+ query.description("Inspect and manage saved work package queries");
324
+ registerList(query, runtime);
325
+ registerGet(query, runtime);
326
+ registerQueryRun(query, runtime);
327
+ registerQueryManage(query, runtime);
328
+ registerQueryWrite(query, runtime);
329
+ }
330
+ //# sourceMappingURL=query.js.map
@@ -106,19 +106,19 @@ async function openProfile(runtime, options) {
106
106
  project: parseProjectOverride(options.project),
107
107
  });
108
108
  }
109
- function collectValue(value, previous) {
109
+ export function collectValue(value, previous) {
110
110
  return [...previous, value];
111
111
  }
112
112
  /** Like collectValue, but a flag left out stays undefined, not empty. */
113
- function collectOptional(value, previous) {
113
+ export function collectOptional(value, previous) {
114
114
  return [...(previous ?? []), value];
115
115
  }
116
116
  /**
117
117
  * Attach the shared filter surface of `wp list` and `wp count`. Both
118
118
  * commands accept exactly the same flags; repeating a value flag ORs.
119
119
  */
120
- function addFilterFlags(command) {
121
- return command
120
+ export function addFilterFlags(command, withScope = true) {
121
+ const filters = command
122
122
  .option("--status <name>", "status name or id; repeat to OR values", collectValue, [])
123
123
  .option("--type <name>", "type name or id; repeat to OR values", collectValue, [])
124
124
  .option("--assignee <name>", "user name, id, or me; repeat to OR values", collectValue, [])
@@ -144,9 +144,12 @@ function addFilterFlags(command) {
144
144
  .option("--include-subprojects", "include subprojects in a --project listing (the default; an instance setting may change what a project clause covers)")
145
145
  .option("--no-include-subprojects", "only the project's own work packages, not its subprojects' (needs a project)")
146
146
  .option("--open", "shorthand for every open status")
147
- .option("--closed", "shorthand for every closed status")
148
- .option("--profile <name>", "use this profile for this command only")
149
- .option("--project <name-or-id>", "override the profile default project");
147
+ .option("--closed", "shorthand for every closed status");
148
+ return withScope
149
+ ? filters
150
+ .option("--profile <name>", "use this profile for this command only")
151
+ .option("--project <name-or-id>", "override the profile default project")
152
+ : filters;
150
153
  }
151
154
  /** Normalise --id values ("12" or "#12") to digit strings. */
152
155
  function parseIdValues(raw) {
@@ -158,7 +161,7 @@ function parseIdValues(raw) {
158
161
  return id;
159
162
  });
160
163
  }
161
- function rawListFlags(options) {
164
+ export function rawListFlags(options) {
162
165
  return {
163
166
  statuses: options.status,
164
167
  types: options.type,
@@ -401,6 +404,42 @@ async function submitCreate(runtime, profile, payload, refs, memo) {
401
404
  }
402
405
  return response.body;
403
406
  }
407
+ /**
408
+ * OpenProject subscribes the creator to every work package it creates, and
409
+ * no create flag turns that off. The only lever is removing oneself
410
+ * afterwards. The create already succeeded, so a failure here is a warning
411
+ * and never an error: a non-zero exit would invite a retry that duplicates
412
+ * the work package. Returns false when the watcher is gone and null when
413
+ * that is not known.
414
+ */
415
+ async function removeCreatorWatch(runtime, profile, id, memo) {
416
+ if (typeof id !== "number") {
417
+ runtime.writeErr("warning: work package was created without a numeric id; "
418
+ + "cannot remove you from its watchers.\n");
419
+ return null;
420
+ }
421
+ try {
422
+ const userId = await memo.me();
423
+ await deleteWatcher(profile, id, userId);
424
+ return false;
425
+ }
426
+ catch (error) {
427
+ const failure = error instanceof OpCliError
428
+ ? error
429
+ : new OpCliError("INTERNAL_ERROR");
430
+ runtime.writeErr(`work package ${String(id)} was created, but removing you from its watchers `
431
+ + `failed: ${failure.code}: ${failure.message}`
432
+ + `${failure.hint ? ` (${failure.hint})` : ""}\n`);
433
+ return null;
434
+ }
435
+ }
436
+ /** DELETE one watcher; any non-2xx answer becomes a write failure. */
437
+ async function deleteWatcher(profile, wpId, userId) {
438
+ const response = await unknownIfUnfinished(() => apiDeleteRaw(profile.instanceUrl, profile.apiKey, `/api/v3/work_packages/${String(wpId)}/watchers/${String(userId)}`), WATCH_WRITE(String(wpId)));
439
+ if (response.status < 200 || response.status >= 300) {
440
+ throw writeFailure(response.status, response.body, WATCH_WRITE(String(wpId)));
441
+ }
442
+ }
404
443
  /**
405
444
  * Kebab spellings a stdin item may use for a camelCase key, mirroring the
406
445
  * flag. Both spell the same attribute; giving both is refused.
@@ -412,6 +451,7 @@ const BULK_KEY_ALIASES = {
412
451
  /** Keys one stdin item may carry; everything else is a loud usage error. */
413
452
  const BULK_ITEM_KEYS = [
414
453
  "subject",
454
+ "watch",
415
455
  ...Object.keys(VALUE_OPTIONS),
416
456
  ...Object.keys(BULK_KEY_ALIASES),
417
457
  ];
@@ -446,6 +486,10 @@ function parseBulkItem(raw, index) {
446
486
  if (typeof subject !== "string" || subject.trim() === "") {
447
487
  throw usage('every input needs a non-empty "subject" string.');
448
488
  }
489
+ const watch = record.watch;
490
+ if (watch !== undefined && typeof watch !== "boolean") {
491
+ throw usage('"watch" must be true or false.', 'false removes you from the watchers after the create, e.g. {"subject": "...", "watch": false}.');
492
+ }
449
493
  const values = {};
450
494
  const scalarKeys = [
451
495
  "type",
@@ -526,7 +570,7 @@ function parseBulkItem(raw, index) {
526
570
  }
527
571
  values.field = field;
528
572
  }
529
- return { subject, values };
573
+ return { subject, values, ...(watch === undefined ? {} : { watch }) };
530
574
  }
531
575
  /**
532
576
  * The --stdin batch: one NDJSON result line per input, in input order,
@@ -590,12 +634,18 @@ async function runBulkCreate(runtime, subjectArg, options) {
590
634
  const id = typeof body === "object" && body !== null
591
635
  ? body.id
592
636
  : undefined;
637
+ // An item's own "watch" wins; otherwise --no-watch (watch === false).
638
+ const unwatchWanted = (item.watch ?? options.watch) === false;
639
+ const watching = unwatchWanted
640
+ ? await removeCreatorWatch(runtime, profile, id, memo)
641
+ : undefined;
593
642
  runtime.write(`${JSON.stringify({
594
643
  index,
595
644
  ok: true,
596
645
  status: "created",
597
646
  ...(typeof id === "number" ? { id } : {}),
598
647
  subject: item.subject,
648
+ ...(watching === undefined ? {} : { watching }),
599
649
  })}\n`);
600
650
  }
601
651
  catch (error) {
@@ -1132,7 +1182,7 @@ async function resolveParents(profile, raws) {
1132
1182
  }
1133
1183
  return ids;
1134
1184
  }
1135
- async function resolveListFlags(runtime, profile, options) {
1185
+ export async function resolveListFlags(runtime, profile, options) {
1136
1186
  const flags = {};
1137
1187
  // The project in context scopes the listing itself, not just the
1138
1188
  // vocabularies resolved below; without it every listing is
@@ -1892,6 +1942,8 @@ export function registerWpCommands(wp, runtime) {
1892
1942
  .option("--stdin", "read a JSON array of work packages and report one NDJSON line per item")
1893
1943
  .option("--fail-fast", "with --stdin: stop the batch at the first failing item")
1894
1944
  .option("--dry-run", "with --stdin: resolve and validate everything, create nothing")
1945
+ .option("--no-watch", "after the create, remove yourself from the watchers OpenProject added you to; "
1946
+ + "with --stdin applies to every item unless an item sets \"watch\": true")
1895
1947
  .option("--type <name-or-id>", "work package type, by name or id")
1896
1948
  .option("--status <name-or-id>", "initial status, by name or id")
1897
1949
  .option("--priority <name-or-id>", "priority, by name or id")
@@ -1943,7 +1995,16 @@ export function registerWpCommands(wp, runtime) {
1943
1995
  const { payload, refs } = await prepareCreatePayload(runtime, profile, subject, options);
1944
1996
  const body = await submitCreate(runtime, profile, payload, refs);
1945
1997
  const created = flattenHalRecord(body);
1946
- renderRecord(runtime, options, created, `work package ${String(created.id)} was created`);
1998
+ let done = `work package ${String(created.id)} was created`;
1999
+ // Commander: --no-watch makes options.watch false; absent it is true.
2000
+ if (options.watch === false) {
2001
+ const watching = await removeCreatorWatch(runtime, profile, created.id, newResolutionMemo(runtime, profile));
2002
+ created.watching = watching;
2003
+ if (watching === false) {
2004
+ done += ", not watching";
2005
+ }
2006
+ }
2007
+ renderRecord(runtime, options, created, done);
1947
2008
  });
1948
2009
  wp.command("update")
1949
2010
  .description("Update one work package with every value given by name")
@@ -2376,10 +2437,7 @@ export function registerWpCommands(wp, runtime) {
2376
2437
  reportWatch(reference, options, userId, name, false, false);
2377
2438
  return;
2378
2439
  }
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
- }
2440
+ await deleteWatcher(profile, reference, userId);
2383
2441
  reportWatch(reference, options, userId, name, false, present === null ? null : true);
2384
2442
  });
2385
2443
  wp.command("relate")
@@ -18,7 +18,7 @@ const API_ROOT = "/api/v3/";
18
18
  * which the client prepends again from the instance URL, so everything
19
19
  * before the API root is dropped.
20
20
  */
21
- function instancePathOf(href) {
21
+ export function instancePathOf(href) {
22
22
  const path = halNextPath(href);
23
23
  const root = path?.indexOf(API_ROOT) ?? -1;
24
24
  return path === undefined || root <= 0 ? path : path.slice(root);
package/dist/core/hal.js CHANGED
@@ -45,6 +45,15 @@ function isFlatLink(value) {
45
45
  return (Object.keys(record).every((key) => key === "id" || key === "name")
46
46
  && ("id" in record || "name" in record));
47
47
  }
48
+ function flattenValue(value) {
49
+ if (Array.isArray(value)) {
50
+ return value.map(flattenValue);
51
+ }
52
+ if (typeof value === "object" && value !== null) {
53
+ return flattenHalRecord(value);
54
+ }
55
+ return value;
56
+ }
48
57
  /**
49
58
  * Flatten one HAL resource in place: `_type` is dropped, `_embedded` is
50
59
  * stripped (embedded resources are never merged into the record), every
@@ -63,11 +72,7 @@ export function flattenHalRecord(record) {
63
72
  if (key === "_type" || key === "_embedded" || key === "_links") {
64
73
  continue;
65
74
  }
66
- flat[key] = Array.isArray(value)
67
- ? value.map(flattenHalRecord)
68
- : typeof value === "object" && value !== null
69
- ? flattenHalRecord(value)
70
- : value;
75
+ flat[key] = flattenValue(value);
71
76
  }
72
77
  const links = resource._links;
73
78
  if (typeof links === "object" && links !== null) {
@@ -15,7 +15,8 @@ export const SCALAR_OPTIONS = SCALARS.map((scalar) => scalar.option);
15
15
  export function scalarFlag(option) {
16
16
  return SCALARS.find((scalar) => scalar.option === option)?.flag ?? option;
17
17
  }
18
- function readDate(raw, flag) {
18
+ /** One real YYYY-MM-DD calendar date, trimmed; USAGE_ERROR naming the flag otherwise. */
19
+ export function readDate(raw, flag) {
19
20
  const token = raw.trim();
20
21
  const real = /^\d{4}-\d{2}-\d{2}$/.test(token) && (() => {
21
22
  const [year, month, day] = token.split("-").map(Number);
package/dist/run.js CHANGED
@@ -8,6 +8,7 @@ import { registerMetaCommands } from "./commands/meta.js";
8
8
  import { registerDoctorCommand } from "./commands/doctor.js";
9
9
  import { registerWpCommands } from "./commands/wp.js";
10
10
  import { registerProjectCommands } from "./commands/project.js";
11
+ import { registerQueryCommands } from "./commands/query.js";
11
12
  import { installWorkspaceAlias } from "./core/workspace-alias.js";
12
13
  import { registerTimeCommands } from "./commands/time.js";
13
14
  import { registerNotificationCommands } from "./commands/notification.js";
@@ -221,6 +222,20 @@ export async function run(argv, env, io) {
221
222
  group.description("Alias of project: inspect and manage projects");
222
223
  }
223
224
  }
225
+ const query = program.command("query");
226
+ registerQueryCommands(query, {
227
+ env,
228
+ resolve: (overrides) => resolveProfile(env, overrides),
229
+ write: (text) => {
230
+ stdout += text;
231
+ },
232
+ writeErr: (text) => {
233
+ stderr += text;
234
+ },
235
+ setJsonMode: (on) => {
236
+ jsonOutput = on;
237
+ },
238
+ });
224
239
  const time = program
225
240
  .command("time")
226
241
  .description("Track and inspect time entries");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuanhv/op-cli",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "A resolving command-line client for OpenProject",
5
5
  "license": "MIT",
6
6
  "author": "hoangvantuan",