@tuanhv/op-cli 0.3.1 → 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.
@@ -1,4 +1,4 @@
1
- import { OpCliError } from "./errors.js";
1
+ import { OpCliError, refuseCombined } from "./errors.js";
2
2
  const DATE_FORMS = "today, yesterday, a number of days such as 7d, or an explicit YYYY-MM-DD date";
3
3
  export function isoDate(date) {
4
4
  const month = String(date.getMonth() + 1).padStart(2, "0");
@@ -81,16 +81,40 @@ export function buildWpFilters(flags, now) {
81
81
  throw new OpCliError("USAGE_ERROR", "--open and --closed cannot be combined.", "pass only one of the two shorthands.");
82
82
  }
83
83
  const statuses = unique(flags.statuses ?? []);
84
+ if (flags.overdue === true && flags.closed === true) {
85
+ throw new OpCliError("USAGE_ERROR", "--overdue cannot be combined with --closed.", "an overdue work package is an open one past its due date.");
86
+ }
84
87
  if ((flags.open === true || flags.closed === true) && statuses.length > 0) {
85
88
  throw new OpCliError("USAGE_ERROR", "--status cannot be combined with --open or --closed.", "list explicit statuses or use one shorthand, not both.");
86
89
  }
90
+ // A work package sits in a sprint, in a backlog bucket, or in the
91
+ // backlog inbox, never in two, so any pair of these ANDs to nothing (#46).
92
+ refuseCombined([
93
+ (flags.sprints ?? []).length > 0 ? "--sprint" : undefined,
94
+ (flags.buckets ?? []).length > 0 ? "--bucket" : undefined,
95
+ flags.backlogInbox === true ? "--backlog-inbox" : undefined,
96
+ ], "a work package sits in a sprint, in a backlog bucket, or in the backlog inbox; "
97
+ + "run one listing per placement.");
98
+ if (flags.includeSubprojects === false && flags.project === undefined) {
99
+ throw new OpCliError("USAGE_ERROR", "--no-include-subprojects needs a project in context.", "pass --project <name-or-id> (or --workspace) or set a default project on the profile.");
100
+ }
87
101
  const filters = [];
88
102
  // The project leads: it is the scope every other clause narrows, and it
89
103
  // is the same clause the project-scoped collection applies internally,
90
104
  // subprojects included.
91
- if (flags.project !== undefined) {
105
+ if (flags.project !== undefined && flags.includeSubprojects !== false) {
92
106
  filters.push({ name: "project", operator: "=", values: [flags.project] });
93
107
  }
108
+ if (flags.includeSubprojects === false) {
109
+ // The global project clause reaches subprojects. subprojectId "none"
110
+ // drops them, but the instance only evaluates it inside the
111
+ // project-scoped collection (see workPackagesPath in commands/wp.ts), so the project
112
+ // clause is left out here and the route carries the scope.
113
+ filters.push({ name: "subprojectId", operator: "!*", values: [] });
114
+ }
115
+ if ((flags.ids ?? []).length > 0) {
116
+ filters.push({ name: "id", operator: "=", values: unique(flags.ids) });
117
+ }
94
118
  if (flags.open === true) {
95
119
  filters.push({ name: "status", operator: "o", values: [] });
96
120
  }
@@ -100,21 +124,47 @@ export function buildWpFilters(flags, now) {
100
124
  else if (statuses.length > 0) {
101
125
  filters.push({ name: "status", operator: "=", values: statuses });
102
126
  }
127
+ if (flags.overdue === true && flags.open !== true && statuses.length === 0) {
128
+ filters.push({ name: "status", operator: "o", values: [] });
129
+ }
103
130
  if ((flags.types ?? []).length > 0) {
104
131
  filters.push({ name: "type", operator: "=", values: unique(flags.types) });
105
132
  }
106
133
  if ((flags.assignees ?? []).length > 0) {
107
134
  filters.push({ name: "assigned_to", operator: "=", values: unique(flags.assignees) });
108
135
  }
136
+ if ((flags.accountables ?? []).length > 0) {
137
+ filters.push({ name: "responsible", operator: "=", values: unique(flags.accountables) });
138
+ }
109
139
  if ((flags.authors ?? []).length > 0) {
110
140
  filters.push({ name: "author", operator: "=", values: unique(flags.authors) });
111
141
  }
142
+ if ((flags.watchers ?? []).length > 0) {
143
+ filters.push({ name: "watcher", operator: "=", values: unique(flags.watchers) });
144
+ }
112
145
  if ((flags.versions ?? []).length > 0) {
113
146
  filters.push({ name: "version", operator: "=", values: unique(flags.versions) });
114
147
  }
148
+ if ((flags.observedIn ?? []).length > 0) {
149
+ filters.push({
150
+ name: "observedInVersion",
151
+ operator: "=",
152
+ values: unique(flags.observedIn),
153
+ });
154
+ }
115
155
  if ((flags.categories ?? []).length > 0) {
116
156
  filters.push({ name: "category", operator: "=", values: unique(flags.categories) });
117
157
  }
158
+ if ((flags.sprints ?? []).length > 0) {
159
+ filters.push({ name: "sprint", operator: "=", values: unique(flags.sprints) });
160
+ }
161
+ if ((flags.buckets ?? []).length > 0) {
162
+ filters.push({ name: "backlogBucket", operator: "=", values: unique(flags.buckets) });
163
+ }
164
+ if (flags.backlogInbox === true) {
165
+ // A boolean filter: the instance reads "t", and refuses "true".
166
+ filters.push({ name: "backlogInbox", operator: "=", values: ["t"] });
167
+ }
118
168
  if ((flags.priorities ?? []).length > 0) {
119
169
  filters.push({ name: "priority", operator: "=", values: unique(flags.priorities) });
120
170
  }
@@ -138,6 +188,26 @@ export function buildWpFilters(flags, now) {
138
188
  values: [since, ""],
139
189
  });
140
190
  }
191
+ if (flags.dueAfter !== undefined || flags.dueBefore !== undefined || flags.overdue === true) {
192
+ // One clause carries the whole window: the API ANDs separate clauses
193
+ // on the same attribute only loosely, and an empty bound is open.
194
+ const lower = flags.dueAfter === undefined
195
+ ? ""
196
+ : untilDate(flags.dueAfter, now, "--due-after");
197
+ let upper = flags.dueBefore === undefined
198
+ ? ""
199
+ : untilDate(flags.dueBefore, now, "--due-before");
200
+ if (flags.overdue === true) {
201
+ const yesterday = isoDate(daysAgo(now, 1));
202
+ if (upper === "" || upper > yesterday) {
203
+ upper = yesterday;
204
+ }
205
+ }
206
+ if (lower !== "" && upper !== "" && lower > upper) {
207
+ throw new OpCliError("USAGE_ERROR", `the due window is empty: ${lower} is after ${upper}.`, "--due-after must not be later than --due-before (or the day before today with --overdue).");
208
+ }
209
+ filters.push({ name: "dueDate", operator: "<>d", values: [lower, upper] });
210
+ }
141
211
  if (flags.updatedAfter !== undefined) {
142
212
  const since = sinceDate(flags.updatedAfter, now);
143
213
  filters.push({
@@ -160,4 +230,43 @@ export function filtersQuery(filters) {
160
230
  }));
161
231
  return encodeURIComponent(JSON.stringify(wire));
162
232
  }
233
+ /**
234
+ * The sort fields `wp list --sort` accepts. The flattened record names
235
+ * users see are also the API's sortBy keys, so no mapping is needed.
236
+ */
237
+ const SORT_FIELDS = [
238
+ "updatedAt",
239
+ "createdAt",
240
+ "dueDate",
241
+ "startDate",
242
+ "priority",
243
+ "status",
244
+ "id",
245
+ "subject",
246
+ ];
247
+ /** Parse repeated `field[:asc|desc]` values into the API's sortBy pairs. */
248
+ export function parseSort(raw) {
249
+ const allowed = SORT_FIELDS.join(", ");
250
+ const pairs = [];
251
+ for (const entry of raw) {
252
+ const [name = "", direction = "asc", ...rest] = entry.trim().split(":");
253
+ const field = SORT_FIELDS.find((candidate) => candidate.toLowerCase() === name.toLowerCase());
254
+ if (field === undefined) {
255
+ throw new OpCliError("USAGE_ERROR", `cannot sort by "${name}".`, `--sort accepts ${allowed}, each optionally followed by :asc or :desc.`);
256
+ }
257
+ const lowered = direction.toLowerCase();
258
+ if (rest.length > 0 || (lowered !== "asc" && lowered !== "desc")) {
259
+ throw new OpCliError("USAGE_ERROR", `"${entry}" is not a sort direction.`, "--sort <field>:asc or <field>:desc; the direction defaults to asc.");
260
+ }
261
+ if (pairs.some(([existing]) => existing === field)) {
262
+ throw new OpCliError("USAGE_ERROR", `--sort lists ${field} twice.`, "name each field once.");
263
+ }
264
+ pairs.push([field, lowered]);
265
+ }
266
+ return pairs;
267
+ }
268
+ /** The URL-encoded `sortBy` query parameter value. */
269
+ export function sortByQuery(pairs) {
270
+ return encodeURIComponent(JSON.stringify(pairs));
271
+ }
163
272
  //# sourceMappingURL=filters.js.map
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) {
package/dist/core/http.js CHANGED
@@ -1,4 +1,4 @@
1
- import { OpCliError } from "./errors.js";
1
+ import { explanationOf, OpCliError, writeRefusal } from "./errors.js";
2
2
  export async function authenticate(instanceUrl, apiKey) {
3
3
  const user = (await apiGet(instanceUrl, apiKey, "/api/v3/users/me"));
4
4
  return {
@@ -32,7 +32,10 @@ let timeoutMs = DEFAULT_TIMEOUT_MS;
32
32
  export function bindRequestTimeout(env) {
33
33
  timeoutMs = parseTimeoutMs(env.OP_CLI_TIMEOUT_MS);
34
34
  }
35
- async function attempt(instanceUrl, apiKey, path, method, body) {
35
+ async function attempt(instanceUrl, apiKey, path, method, body, accept = "application/hal+json") {
36
+ // A multipart upload carries its own boundary-bearing content type;
37
+ // fetch only writes it when the caller leaves the header alone.
38
+ const multipart = body instanceof FormData;
36
39
  // AbortSignal.timeout aborts with a TimeoutError reason. A budget
37
40
  // problem (too impatient) and a reachability problem (wrong URL)
38
41
  // share the NETWORK_ERROR code and exit 6 by contract; only the
@@ -41,17 +44,17 @@ async function attempt(instanceUrl, apiKey, path, method, body) {
41
44
  try {
42
45
  return await fetch(`${instanceUrl}${path}`, {
43
46
  headers: {
44
- accept: "application/hal+json",
47
+ accept,
45
48
  authorization: `Basic ${Buffer.from(`apikey:${apiKey}`).toString("base64")}`,
46
49
  // The API rejects non-JSON bodies with 415; without this header
47
50
  // fetch would label the body text/plain.
48
- ...(method === "POST" || method === "PATCH"
51
+ ...((method === "POST" || method === "PATCH") && !multipart
49
52
  ? { "content-type": "application/json" }
50
53
  : {}),
51
54
  },
52
55
  signal,
53
56
  ...(method === "POST" || method === "PATCH"
54
- ? { method, body: JSON.stringify(body) }
57
+ ? { method, body: multipart ? body : JSON.stringify(body) }
55
58
  : { method }),
56
59
  });
57
60
  }
@@ -62,18 +65,32 @@ async function attempt(instanceUrl, apiKey, path, method, body) {
62
65
  throw new OpCliError("NETWORK_ERROR");
63
66
  }
64
67
  }
65
- async function request(instanceUrl, apiKey, path, method, body) {
66
- let response = await attempt(instanceUrl, apiKey, path, method, body);
68
+ async function request(instanceUrl, apiKey, path, method, body, accept) {
69
+ let response = await attempt(instanceUrl, apiKey, path, method, body, accept);
67
70
  if (method === "GET" && (response.status === 429 || response.status >= 500)) {
68
71
  // Promise.withResolvers needs ES2024 lib; the executor form stays.
69
72
  await new Promise((resolve) => setTimeout(resolve, READ_RETRY_DELAY_MS));
70
- response = await attempt(instanceUrl, apiKey, path, method, body);
73
+ response = await attempt(instanceUrl, apiKey, path, method, body, accept);
71
74
  }
72
- if (response.status === 401 || response.status === 403) {
75
+ if (response.status === 401) {
73
76
  throw new OpCliError("AUTH_FAILED");
74
77
  }
78
+ if (response.status === 403) {
79
+ throw permissionDenied(path, await bodyOf(response));
80
+ }
75
81
  return response;
76
82
  }
83
+ /**
84
+ * A 403 names what was refused: the credentials work, the account lacks
85
+ * a permission on this path. The query string is left out; it repeats
86
+ * filters the caller already knows and buries the path.
87
+ */
88
+ function permissionDenied(path, body) {
89
+ const bare = path.split("?")[0] ?? path;
90
+ const explanation = explanationOf(body);
91
+ return new OpCliError("PERMISSION_DENIED", `OpenProject denied access to ${bare}`
92
+ + (explanation === undefined ? "." : `: ${explanation}`), undefined, { status: 403, path: bare });
93
+ }
77
94
  async function send(instanceUrl, apiKey, path, method, body) {
78
95
  const response = await request(instanceUrl, apiKey, path, method, body);
79
96
  if (response.status === 204) {
@@ -82,6 +99,11 @@ async function send(instanceUrl, apiKey, path, method, body) {
82
99
  if (response.status === 404) {
83
100
  throw new OpCliError("NOT_FOUND");
84
101
  }
102
+ if (response.status < 500 && !response.ok) {
103
+ // A client error carries OpenProject's own explanation, and waiting
104
+ // will not change the answer: quote it instead of "try again later".
105
+ throw writeRefusal("request", response.status, await bodyOf(response));
106
+ }
85
107
  if (!response.ok) {
86
108
  throw new OpCliError("API_ERROR");
87
109
  }
@@ -110,10 +132,41 @@ export async function apiPatchRaw(instanceUrl, apiKey, path, body) {
110
132
  export async function apiDelete(instanceUrl, apiKey, path) {
111
133
  return send(instanceUrl, apiKey, path, "DELETE");
112
134
  }
135
+ export async function apiDeleteRaw(instanceUrl, apiKey, path) {
136
+ const response = await request(instanceUrl, apiKey, path, "DELETE");
137
+ return { status: response.status, body: await bodyOf(response) };
138
+ }
113
139
  export async function apiGet(instanceUrl, apiKey, path) {
114
140
  return send(instanceUrl, apiKey, path, "GET");
115
141
  }
116
142
  export async function apiPost(instanceUrl, apiKey, path, body) {
117
143
  return send(instanceUrl, apiKey, path, "POST", body);
118
144
  }
145
+ export async function apiPatch(instanceUrl, apiKey, path, body) {
146
+ return send(instanceUrl, apiKey, path, "PATCH", body);
147
+ }
148
+ /**
149
+ * The raw bytes of a file download. Redirects (external storage) are
150
+ * followed by fetch; it drops the credentials on a cross-origin hop.
151
+ */
152
+ export async function apiGetBytes(instanceUrl, apiKey, path) {
153
+ const response = await request(instanceUrl, apiKey, path, "GET", undefined, "*/*");
154
+ if (response.status === 404) {
155
+ throw new OpCliError("NOT_FOUND");
156
+ }
157
+ if (!response.ok) {
158
+ throw new OpCliError("API_ERROR");
159
+ }
160
+ try {
161
+ return new Uint8Array(await response.arrayBuffer());
162
+ }
163
+ catch {
164
+ throw new OpCliError("NETWORK_ERROR");
165
+ }
166
+ }
167
+ /** A multipart/form-data POST; like every write it is never retried. */
168
+ export async function apiPostMultipartRaw(instanceUrl, apiKey, path, form) {
169
+ const response = await request(instanceUrl, apiKey, path, "POST", form);
170
+ return { status: response.status, body: await bodyOf(response) };
171
+ }
119
172
  //# sourceMappingURL=http.js.map
@@ -0,0 +1,78 @@
1
+ import { OpCliError } from "./errors.js";
2
+ import { parseDuration } from "./duration.js";
3
+ /** Flag name, payload key, and reader of every scalar attribute. */
4
+ const SCALARS = [
5
+ { option: "start", flag: "--start", attribute: "startDate", read: readDate },
6
+ { option: "due", flag: "--due", attribute: "dueDate", read: readDate },
7
+ { option: "estimate", flag: "--estimate", attribute: "estimatedTime", read: readDuration },
8
+ { option: "remaining", flag: "--remaining", attribute: "remainingTime", read: readDuration },
9
+ { option: "done", flag: "--done", attribute: "percentageDone", read: readPercent },
10
+ { option: "storyPoints", flag: "--story-points", attribute: "storyPoints", read: readPoints },
11
+ ];
12
+ /** The option names, for callers that must loop over them. */
13
+ export const SCALAR_OPTIONS = SCALARS.map((scalar) => scalar.option);
14
+ /** The flag spelling of one scalar option, for error messages. */
15
+ export function scalarFlag(option) {
16
+ return SCALARS.find((scalar) => scalar.option === option)?.flag ?? option;
17
+ }
18
+ /** One real YYYY-MM-DD calendar date, trimmed; USAGE_ERROR naming the flag otherwise. */
19
+ export function readDate(raw, flag) {
20
+ const token = raw.trim();
21
+ const real = /^\d{4}-\d{2}-\d{2}$/.test(token) && (() => {
22
+ const [year, month, day] = token.split("-").map(Number);
23
+ const probe = new Date(Date.UTC(year, month - 1, day));
24
+ return probe.getUTCFullYear() === year
25
+ && probe.getUTCMonth() === month - 1
26
+ && probe.getUTCDate() === day;
27
+ })();
28
+ if (!real) {
29
+ throw new OpCliError("USAGE_ERROR", `${flag} "${raw}" is not a real YYYY-MM-DD date.`, `give a calendar date such as 2026-03-31, or "" to clear on update.`);
30
+ }
31
+ return token;
32
+ }
33
+ function readDuration(raw, flag) {
34
+ return parseDuration(raw, { flag, allowZero: true }).iso;
35
+ }
36
+ function readInteger(raw, flag, max) {
37
+ const token = raw.trim();
38
+ const value = /^\d+$/.test(token) ? Number(token) : Number.NaN;
39
+ if (!Number.isSafeInteger(value) || (max !== undefined && value > max)) {
40
+ throw new OpCliError("USAGE_ERROR", `${flag} "${raw}" is not ${max === undefined ? "a non-negative integer" : `an integer from 0 to ${String(max)}`}.`, `give ${max === undefined ? "a whole number of 0 or more" : `a whole number from 0 to ${String(max)}`}, or "" to clear on update.`);
41
+ }
42
+ return value;
43
+ }
44
+ function readPercent(raw, flag) {
45
+ return readInteger(raw, flag, 100);
46
+ }
47
+ function readPoints(raw, flag) {
48
+ return readInteger(raw, flag, undefined);
49
+ }
50
+ /**
51
+ * Refuse any given scalar that is not well formed, without building a
52
+ * payload. An empty value is a clear request, valid here; whether it is
53
+ * allowed is decided earlier (refuseEmptyValues).
54
+ */
55
+ export function validateScalars(flags) {
56
+ for (const scalar of SCALARS) {
57
+ const raw = flags[scalar.option];
58
+ if (raw !== undefined && raw !== "") {
59
+ scalar.read(raw, scalar.flag);
60
+ }
61
+ }
62
+ }
63
+ /**
64
+ * Validate every given scalar and write it into the payload's top-level
65
+ * attributes: dates as YYYY-MM-DD, durations as ISO 8601, integers as
66
+ * numbers. An empty value writes null, which is how the API clears a
67
+ * scalar; whether that is allowed is decided earlier (refuseEmptyValues).
68
+ */
69
+ export function applyScalars(payload, flags) {
70
+ for (const scalar of SCALARS) {
71
+ const raw = flags[scalar.option];
72
+ if (raw === undefined) {
73
+ continue;
74
+ }
75
+ payload[scalar.attribute] = raw === "" ? null : scalar.read(raw, scalar.flag);
76
+ }
77
+ }
78
+ //# sourceMappingURL=scalars.js.map
@@ -0,0 +1,47 @@
1
+ import { OpCliError } from "./errors.js";
2
+ /**
3
+ * OpenProject 17 renamed projects to workspaces in API v3 (#57). "Project"
4
+ * stays the canonical term; "workspace" is accepted wherever "project"
5
+ * is, with the same resolution (ADR-0005).
6
+ */
7
+ const PROJECT_FLAG = "--project";
8
+ const WORKSPACE_FLAG = "--workspace";
9
+ /**
10
+ * Give every command that declares --project a --workspace twin and fold
11
+ * the twin into --project before the action runs, so no command reads
12
+ * `options.workspace`. Passing both is fine when they name the same
13
+ * project: equal strings, or different spellings (an id and a name) that
14
+ * `sameProject` resolves to one project. Only a resolved difference, or a
15
+ * spelling that cannot be resolved, is refused.
16
+ *
17
+ * Walks the finished tree rather than each declaration so a new command
18
+ * with --project gets the alias without remembering it.
19
+ */
20
+ export function installWorkspaceAlias(program, onJsonMode, sameProject) {
21
+ const declare = (command) => {
22
+ for (const child of command.commands) {
23
+ declare(child);
24
+ }
25
+ if (command.options.some((option) => option.long === PROJECT_FLAG)) {
26
+ command.option(`${WORKSPACE_FLAG} <name-or-id>`, `alias of ${PROJECT_FLAG}`);
27
+ }
28
+ };
29
+ declare(program);
30
+ program.hook("preAction", async (_root, actionCommand) => {
31
+ const options = actionCommand.opts();
32
+ if (options.workspace === undefined) {
33
+ return;
34
+ }
35
+ if (options.project !== undefined
36
+ && options.project !== options.workspace
37
+ && !(await sameProject(options.profile, options.project, options.workspace).catch(() => false))) {
38
+ // The action has not run yet, so it could not tell the error
39
+ // renderer whether the caller asked for JSON.
40
+ onJsonMode(options.json === true);
41
+ throw new OpCliError("USAGE_ERROR", `${PROJECT_FLAG} and ${WORKSPACE_FLAG} are the same option and disagree: `
42
+ + `"${options.project}" vs "${options.workspace}".`, `pass only one of ${PROJECT_FLAG} or ${WORKSPACE_FLAG}.`);
43
+ }
44
+ actionCommand.setOptionValue("project", options.workspace);
45
+ });
46
+ }
47
+ //# sourceMappingURL=workspace-alias.js.map
package/dist/run.js CHANGED
@@ -8,6 +8,8 @@ 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";
12
+ import { installWorkspaceAlias } from "./core/workspace-alias.js";
11
13
  import { registerTimeCommands } from "./commands/time.js";
12
14
  import { registerNotificationCommands } from "./commands/notification.js";
13
15
  import { buildVersionOutput } from "./commands/version.js";
@@ -16,6 +18,7 @@ import { Command, CommanderError } from "commander";
16
18
  export async function run(argv, env, io) {
17
19
  let stdout = "";
18
20
  let stderr = "";
21
+ const stdoutChunks = [];
19
22
  // Spec story 51: one environment variable makes JSON the output for
20
23
  // the whole session, errors included, instead of a flag per command.
21
24
  let jsonOutput = env.OP_CLI_OUTPUT === "json";
@@ -191,15 +194,37 @@ export async function run(argv, env, io) {
191
194
  writeErr: (text) => {
192
195
  stderr += text;
193
196
  },
197
+ writeBytes: (bytes) => {
198
+ stdoutChunks.push(bytes);
199
+ },
194
200
  setJsonMode: (on) => {
195
201
  jsonOutput = on;
196
202
  },
197
203
  ...(io.readStdin === undefined ? {} : { readStdin: io.readStdin }),
198
204
  });
199
- const project = program
200
- .command("project")
201
- .description("Inspect and manage projects");
202
- registerProjectCommands(project, {
205
+ // "workspace" is the same group under OpenProject 17's name for a
206
+ // project (#57): one registration per name, so the two cannot drift.
207
+ for (const name of ["project", "workspace"]) {
208
+ const group = program.command(name);
209
+ registerProjectCommands(group, {
210
+ resolve: (overrides) => resolveProfile(env, overrides),
211
+ write: (text) => {
212
+ stdout += text;
213
+ },
214
+ writeErr: (text) => {
215
+ stderr += text;
216
+ },
217
+ setJsonMode: (on) => {
218
+ jsonOutput = on;
219
+ },
220
+ });
221
+ if (name === "workspace") {
222
+ group.description("Alias of project: inspect and manage projects");
223
+ }
224
+ }
225
+ const query = program.command("query");
226
+ registerQueryCommands(query, {
227
+ env,
203
228
  resolve: (overrides) => resolveProfile(env, overrides),
204
229
  write: (text) => {
205
230
  stdout += text;
@@ -275,6 +300,16 @@ export async function run(argv, env, io) {
275
300
  program.version(await buildVersionOutput(env), "--version", "print version information");
276
301
  }
277
302
  program.addHelpText("after", "\nRun op-cli --version for version information.");
303
+ installWorkspaceAlias(program, (on) => {
304
+ jsonOutput = on;
305
+ },
306
+ // Both spellings go through the same resolution as --project itself;
307
+ // numeric ids pass through without traffic.
308
+ async (profile, first, second) => {
309
+ const firstId = (await resolveProfile(env, { profile, project: parseProjectOverride(first) })).project;
310
+ const secondId = (await resolveProfile(env, { profile, project: parseProjectOverride(second) })).project;
311
+ return firstId !== undefined && firstId === secondId;
312
+ });
278
313
  // Commands built declaratively start as standalone Command objects, so
279
314
  // they miss the root's exitOverride and output capture; without this
280
315
  // walk their --help would print to the real stdout and process.exit,
@@ -317,7 +352,12 @@ export async function run(argv, env, io) {
317
352
  if (noticeLine !== undefined && stderr === "") {
318
353
  stderr += noticeLine;
319
354
  }
320
- return { stdout, stderr, exitCode: forcedExitCode ?? 0 };
355
+ return {
356
+ stdout,
357
+ ...(stdoutChunks.length === 0 ? {} : { stdoutBytes: Buffer.concat(stdoutChunks) }),
358
+ stderr,
359
+ exitCode: forcedExitCode ?? 0,
360
+ };
321
361
  }
322
362
  catch (error) {
323
363
  if (error instanceof CommanderError
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuanhv/op-cli",
3
- "version": "0.3.1",
3
+ "version": "0.5.0",
4
4
  "description": "A resolving command-line client for OpenProject",
5
5
  "license": "MIT",
6
6
  "author": "hoangvantuan",