Open History to see the last commit
1/**
2 * Azure DevOps work items as an issue tracker, over `az`. Work items belong to a project, so the
3 * scope is `organization/project` and every call names the organization. Listing is a WIQL
4 * query paged by a `(changedDate, id)` keyset cursor, because WIQL has no offset.
5 */
6import * as Cache from "effect/Cache";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Exit from "effect/Exit";
10import * as FileSystem from "effect/FileSystem";
11import * as Result from "effect/Result";
12import * as Schema from "effect/Schema";
13import {
14 IssueTrackerKind,
15 type IssueCapabilities,
16 type IssueEvent,
17 type IssueInvolvement,
18 type IssueLinkedPullRequest,
19 type IssueViewerPermissions,
20} from "@t3tools/contracts";
21import {
22 IssueTrackerError,
23 type IssueTrackerApi,
24} from "@t3tools/source-control-core/server/IssueTracker";
25
26import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
27import {
28 azureDevOpsReactionType,
29 closedStateNames,
30 workItemStates,
31 decodeCommentsJson,
32 decodeUpdatesJson,
33 decodeWorkItemJson,
34 decodeWorkItemsJson,
35 pullRequestNumberOf,
36 type AzureDevOpsWorkItem,
37 type ClosedStates,
38} from "./azureDevOpsIssueJson.ts";
39import { decodePullRequestJson } from "./azureDevOpsPullRequestJson.ts";
40
41const KIND = IssueTrackerKind.make("azure-devops");
42
43const CAPABILITIES: IssueCapabilities = {
44 create: true,
45 edit: true,
46 comment: true,
47 labels: true,
48 assignees: true,
49 // On comments only; a work item itself takes none, and `setReaction` says so.
50 reactions: true,
51 // Azure has no issue templates. Its work item types are picked here, not by the reader.
52 templates: false,
53 linkedPullRequests: true,
54 events: true,
55 search: true,
56};
57
58/**
59 * Everything granted. Azure states no permission anywhere `az boards` reaches: the answer lives
60 * in the security namespaces, behind identity descriptors that would be several calls per work
61 * item to resolve. Controls stay live and a viewer who may not use one is told so by Azure.
62 */
63const VIEWER_PERMISSIONS: IssueViewerPermissions = {
64 setState: true,
65 comment: true,
66 edit: true,
67 labels: true,
68 assignees: true,
69};
70
71const REST_API_VERSION = "7.1";
72const PAGE_SIZE = 100;
73const CLOSED_STATES_TTL = Duration.minutes(10);
74/** Updates are read a page per `az` process, oldest first, so a long history is bounded. */
75const UPDATE_PAGE_LIMIT = 5;
76/** Linked pull requests are read one `az` process each, so a work item's links are bounded. */
77const LINKED_PULL_REQUEST_LIMIT = 10;
78/** Which work item type a new issue is filed as, in order of preference across the stock processes. */
79const CREATE_TYPES = ["Issue", "Bug", "Task", "User Story", "Product Backlog Item"];
80
81const LIST_FIELDS = [
82 "System.Id",
83 "System.Title",
84 "System.State",
85 "System.CreatedDate",
86 "System.ChangedDate",
87 "System.CreatedBy",
88 "System.AssignedTo",
89 "System.CommentCount",
90 "System.Tags",
91 "System.TeamProject",
92 "Microsoft.VSTS.Common.ClosedDate",
93];
94
95const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
96const decodeWiql = Schema.decodeUnknownResult(
97 Schema.Struct({
98 workItems: Schema.optional(Schema.NullOr(Schema.Array(Schema.Struct({ id: Schema.Int })))),
99 }),
100);
101const decodeTypes = Schema.decodeUnknownResult(
102 Schema.Struct({
103 value: Schema.Array(
104 Schema.Struct({
105 name: Schema.String,
106 isDisabled: Schema.optional(Schema.Boolean),
107 states: Schema.optional(
108 Schema.Array(Schema.Struct({ name: Schema.String, category: Schema.String })),
109 ),
110 }),
111 ),
112 }),
113);
114const decodeTags = Schema.decodeUnknownResult(
115 Schema.Struct({ value: Schema.Array(Schema.Struct({ name: Schema.String })) }),
116);
117const decodeTeams = Schema.decodeUnknownResult(Schema.Array(Schema.Struct({ id: Schema.String })));
118const decodeMembers = Schema.decodeUnknownResult(
119 Schema.Array(
120 Schema.Struct({
121 identity: Schema.Struct({
122 uniqueName: Schema.String,
123 displayName: Schema.optional(Schema.NullOr(Schema.String)),
124 imageUrl: Schema.optional(Schema.NullOr(Schema.String)),
125 isContainer: Schema.optional(Schema.Boolean),
126 }),
127 }),
128 ),
129);
130const decodeUnknown = Schema.decodeUnknownResult(Schema.fromJsonString(Schema.Unknown));
131
132/** The parts of an `organization/project` scope, as the organization URL and the project name. */
133function parseScope(
134 host: string,
135 scope: string,
136): { readonly organization: string; readonly project: string } | null {
137 const parts = scope.split("/").flatMap((part) => part.trim() || []);
138 // `az` replaces a value starting with `@` by the contents of that local file.
139 if (parts.some((part) => part.startsWith("@"))) return null;
140 // A legacy organization is its hostname, so its scope may be the project alone.
141 if (host.toLowerCase().endsWith(".visualstudio.com")) {
142 const project = parts.length === 1 || parts.length === 2 ? parts.at(-1) : undefined;
143 return project === undefined ? null : { organization: `https://${host}`, project };
144 }
145 if (parts.length !== 2) return null;
146 const [organization, project] = parts as [string, string];
147 return { organization: `https://${host}/${encodeURIComponent(organization)}`, project };
148}
149
150function parseNumber(key: string): number | null {
151 return /^[1-9]\d{0,9}$/.test(key) ? Number(key) : null;
152}
153
154/** WIQL string literals are single-quoted and escape a quote by doubling it. */
155function quoted(value: string): string {
156 return `'${value.replaceAll("'", "''")}'`;
157}
158
159function involvementClause(involvement: IssueInvolvement): string {
160 switch (involvement) {
161 case "assigned":
162 return " AND [System.AssignedTo] = @Me";
163 case "authored":
164 return " AND [System.CreatedBy] = @Me";
165 // WIQL over REST has no way to ask who was mentioned (`@RecentMentions` is a web portal
166 // macro), so a mention filter has nothing to narrow by.
167 case "mentioned":
168 case "all":
169 return "";
170 }
171}
172
173function stateClause(state: "all" | "open" | "closed", closedStates: ClosedStates): string {
174 const closed = `(${[...closedStates].map(quoted).join(", ")})`;
175 switch (state) {
176 case "open":
177 return ` AND [System.State] NOT IN ${closed}`;
178 case "closed":
179 return ` AND [System.State] IN ${closed}`;
180 case "all":
181 return "";
182 }
183}
184
185/** `<iso date the list is sorted by>|<id>` of the last row handed over, where the next page starts. */
186function parseCursor(cursor: string): { readonly date: string; readonly id: number } | null {
187 const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)\|([1-9]\d{0,9})$/.exec(cursor);
188 return match === null ? null : { date: match[1]!, id: Number(match[2]) };
189}
190
191function reasonFor(error: AzureDevOpsCli.AzureDevOpsCliError): IssueTrackerError["reason"] {
192 switch (error._tag) {
193 case "AzureDevOpsCliUnavailableError":
194 return "missing-tool";
195 case "AzureDevOpsCliAuthenticationError":
196 return "unauthenticated";
197 case "AzureDevOpsCliRateLimitError":
198 return "rate-limited";
199 case "AzureDevOpsPullRequestNotFoundError":
200 return "not-found";
201 default:
202 return "failed";
203 }
204}
205
206export const make: Effect.Effect<
207 IssueTrackerApi,
208 never,
209 AzureDevOpsCli.AzureDevOpsCli | FileSystem.FileSystem
210> = Effect.gen(function* () {
211 const azure = yield* AzureDevOpsCli.AzureDevOpsCli;
212 const fs = yield* FileSystem.FileSystem;
213
214 const fail = (operation: string) => (error: AzureDevOpsCli.AzureDevOpsCliError) =>
215 new IssueTrackerError({
216 tracker: KIND,
217 operation,
218 reason: reasonFor(error),
219 detail: error.detail,
220 cause: error,
221 });
222
223 const refused = (operation: string, detail: string, cause?: unknown) =>
224 new IssueTrackerError({
225 tracker: KIND,
226 operation,
227 reason: "failed",
228 detail,
229 ...(cause === undefined ? {} : { cause }),
230 });
231
232 const unreadable = (operation: string, cause: unknown) =>
233 refused(operation, `Azure DevOps returned an unreadable ${operation} response.`, cause);
234
235 const notFound = (operation: string) =>
236 new IssueTrackerError({
237 tracker: KIND,
238 operation,
239 reason: "not-found",
240 detail: "Azure DevOps could not find the requested work item.",
241 });
242
243 const scoped = (
244 operation: string,
245 input: { readonly host: string; readonly scope: string },
246 ): Effect.Effect<
247 { readonly organization: string; readonly project: string },
248 IssueTrackerError
249 > => {
250 const parsed = parseScope(input.host, input.scope);
251 return parsed === null
252 ? Effect.fail(refused(operation, "An Azure DevOps scope is named `organization/project`."))
253 : Effect.succeed(parsed);
254 };
255
256 const run = (input: {
257 readonly cwd: string;
258 readonly operation: string;
259 readonly args: ReadonlyArray<string>;
260 readonly stdin?: string | undefined;
261 }) =>
262 azure
263 .execute({
264 cwd: input.cwd,
265 args: [...input.args, "--only-show-errors", "--output", "json"],
266 ...(input.stdin === undefined ? {} : { stdin: input.stdin }),
267 })
268 .pipe(
269 Effect.map((result) => result.stdout.trim()),
270 Effect.mapError(fail(input.operation)),
271 );
272
273 const read = <A>(input: {
274 readonly cwd: string;
275 readonly operation: string;
276 readonly args: ReadonlyArray<string>;
277 readonly stdin?: string | undefined;
278 readonly decode: (raw: string) => Result.Result<A, unknown>;
279 }): Effect.Effect<A, IssueTrackerError> =>
280 run(input).pipe(
281 Effect.flatMap((raw) => {
282 const decoded = input.decode(raw);
283 return Result.isSuccess(decoded)
284 ? Effect.succeed(decoded.success)
285 : Effect.fail(unreadable(input.operation, decoded.failure));
286 }),
287 );
288
289 const decodeAs =
290 <A>(schema: (value: unknown) => Result.Result<A, unknown>) =>
291 (raw: string): Result.Result<A, unknown> =>
292 Result.flatMap(decodeUnknown(raw), schema);
293
294 /** A `wit` REST route, addressed by resource and route parameters rather than by URL. */
295 const invokeArgs = (input: {
296 readonly organization: string;
297 readonly project: string;
298 readonly resource: string;
299 readonly route?: ReadonlyArray<string>;
300 readonly query?: ReadonlyArray<string>;
301 readonly method?: string;
302 readonly apiVersion?: string;
303 }) => [
304 "devops",
305 "invoke",
306 "--detect",
307 "false",
308 "--organization",
309 input.organization,
310 "--area",
311 "wit",
312 "--resource",
313 input.resource,
314 "--api-version",
315 input.apiVersion ?? REST_API_VERSION,
316 "--route-parameters",
317 `project=${input.project}`,
318 ...(input.route ?? []),
319 ...(input.query === undefined || input.query.length === 0
320 ? []
321 : ["--query-parameters", ...input.query]),
322 ...(input.method === undefined ? [] : ["--http-method", input.method]),
323 ];
324
325 /** A request with a body, which `az devops invoke` only takes from a file. */
326 const invokeWithBody = Effect.fn("AzureDevOpsIssueTracker.invokeWithBody")(function* (input: {
327 readonly cwd: string;
328 readonly operation: string;
329 readonly args: ReadonlyArray<string>;
330 readonly body: unknown;
331 }) {
332 const unwritable = (cause: unknown) =>
333 refused(input.operation, "Could not write the Azure DevOps request body.", cause);
334 const file = yield* fs
335 .makeTempFileScoped({ prefix: "t3-azure-issue-" })
336 .pipe(Effect.mapError(unwritable));
337 yield* fs.writeFileString(file, encodeJson(input.body)).pipe(Effect.mapError(unwritable));
338 return yield* run({
339 cwd: input.cwd,
340 operation: input.operation,
341 args: [...input.args, "--in-file", file, "--media-type", "application/json"],
342 });
343 }, Effect.scoped);
344
345 const workItemTypes = (input: {
346 readonly cwd: string;
347 readonly operation: string;
348 readonly organization: string;
349 readonly project: string;
350 }) =>
351 read({
352 cwd: input.cwd,
353 operation: input.operation,
354 // Form layouts can exceed the CLI output cap; only workflow metadata is needed.
355 args: [
356 ...invokeArgs({ ...input, resource: "workitemtypes" }),
357 "--query",
358 "{value: value[].{name: name, isDisabled: isDisabled || `false`, states: (states || `[]`)[].{name: name, category: category}}}",
359 ],
360 decode: decodeAs(decodeTypes),
361 }).pipe(Effect.map((types) => types.value));
362
363 // Each `az` call costs seconds of startup, and a project's states rarely change.
364 const listClosedStates = yield* Cache.makeWith(
365 (key: string) => {
366 const [cwd, organization, project] = JSON.parse(key) as [string, string, string];
367 return workItemTypes({ cwd, organization, project, operation: "listIssues" }).pipe(
368 Effect.map(closedStateNames),
369 );
370 },
371 {
372 capacity: 256,
373 timeToLive: (exit) => (Exit.isSuccess(exit) ? CLOSED_STATES_TTL : Duration.zero),
374 },
375 );
376
377 const workItem = (input: {
378 readonly cwd: string;
379 readonly operation: string;
380 readonly organization: string;
381 readonly project: string;
382 readonly number: number;
383 readonly closed: ClosedStates;
384 }): Effect.Effect<AzureDevOpsWorkItem, IssueTrackerError> =>
385 read({
386 cwd: input.cwd,
387 operation: input.operation,
388 args: [
389 "boards",
390 "work-item",
391 "show",
392 "--detect",
393 "false",
394 "--organization",
395 input.organization,
396 "--id",
397 String(input.number),
398 "--expand",
399 "relations",
400 ],
401 decode: (raw) => decodeWorkItemJson(raw, input.closed),
402 }).pipe(
403 Effect.filterOrFail(
404 (item) => item !== null,
405 () => notFound(input.operation),
406 ),
407 // `az` addresses a work item by organization and id alone, so one from another project
408 // answers too; the scope names a project, and an item outside it is not this scope's.
409 Effect.filterOrFail(
410 (item) => item.project?.toLowerCase() === input.project.toLowerCase(),
411 () => notFound(input.operation),
412 ),
413 );
414
415 /** The work item as `az` addresses it, or a not-found for a key that names no id. */
416 const target = (
417 operation: string,
418 input: { readonly host: string; readonly scope: string; readonly key: string },
419 ) =>
420 scoped(operation, input).pipe(
421 Effect.flatMap((scope) => {
422 const number = parseNumber(input.key);
423 return number === null
424 ? Effect.fail(notFound(operation))
425 : Effect.succeed({ ...scope, number });
426 }),
427 );
428
429 /** Newest first, so the first page is the current discussion and a cursor leads to older ones. */
430 const comments = (input: {
431 readonly cwd: string;
432 readonly operation: string;
433 readonly organization: string;
434 readonly project: string;
435 readonly number: number;
436 readonly cursor?: string | undefined;
437 }) =>
438 read({
439 cwd: input.cwd,
440 operation: input.operation,
441 args: invokeArgs({
442 ...input,
443 resource: "comments",
444 route: [`workItemId=${input.number}`],
445 apiVersion: "7.1-preview",
446 query: [
447 `$top=${PAGE_SIZE}`,
448 "order=desc",
449 "$expand=reactions",
450 "api-version=7.1-preview.4",
451 ...(input.cursor === undefined ? [] : [`continuationToken=${input.cursor}`]),
452 ],
453 }),
454 decode: decodeCommentsJson,
455 }).pipe(Effect.map((page) => ({ ...page, comments: page.comments.toReversed() })));
456
457 const updates = Effect.fn("AzureDevOpsIssueTracker.updates")(function* (input: {
458 readonly cwd: string;
459 readonly organization: string;
460 readonly project: string;
461 readonly number: number;
462 readonly closed: ClosedStates;
463 }) {
464 const events: IssueEvent[] = [];
465 for (let page = 0; page < UPDATE_PAGE_LIMIT; page += 1) {
466 const answer = yield* read({
467 cwd: input.cwd,
468 operation: "getIssue",
469 args: invokeArgs({
470 ...input,
471 resource: "updates",
472 route: [`id=${input.number}`],
473 query: [`$top=${PAGE_SIZE}`, ...(page === 0 ? [] : [`$skip=${page * PAGE_SIZE}`])],
474 }),
475 decode: (raw) => decodeUpdatesJson(raw, input.closed),
476 });
477 events.push(...answer.events);
478 if (answer.count < PAGE_SIZE) break;
479 }
480 return events;
481 });
482
483 const linkedPullRequests = (input: {
484 readonly cwd: string;
485 readonly organization: string;
486 readonly item: AzureDevOpsWorkItem;
487 }): Effect.Effect<ReadonlyArray<IssueLinkedPullRequest>, IssueTrackerError> => {
488 const numbers = [
489 ...new Set(input.item.relations.flatMap((relation) => pullRequestNumberOf(relation) ?? [])),
490 ].slice(0, LINKED_PULL_REQUEST_LIMIT);
491 return Effect.forEach(
492 numbers,
493 (number) =>
494 read({
495 cwd: input.cwd,
496 operation: "getIssue",
497 args: [
498 "repos",
499 "pr",
500 "show",
501 "--detect",
502 "false",
503 "--organization",
504 input.organization,
505 "--id",
506 String(number),
507 ],
508 decode: decodePullRequestJson,
509 }).pipe(
510 Effect.map((pullRequest) =>
511 pullRequest === null || pullRequest.location === null
512 ? []
513 : [
514 {
515 repository: `${pullRequest.location.project}/${pullRequest.location.repository}`,
516 number: pullRequest.number,
517 title: pullRequest.title,
518 url: pullRequest.url,
519 state: pullRequest.state,
520 isDraft: pullRequest.isDraft,
521 // Azure links a pull request to a work item but never says whether completing
522 // it resolves the item; that lives in a completion option nothing reports.
523 closesIssue: false,
524 },
525 ],
526 ),
527 // A link to a pull request this account cannot see is left out, not a failed detail.
528 Effect.catchIf(
529 (error) => error.reason === "not-found",
530 () => Effect.succeed([]),
531 ),
532 ),
533 { concurrency: 2 },
534 ).pipe(Effect.map((links) => links.flat()));
535 };
536
537 const update = (input: {
538 readonly cwd: string;
539 readonly operation: string;
540 readonly organization: string;
541 readonly number: number;
542 readonly args: ReadonlyArray<string>;
543 readonly stdin?: string | undefined;
544 }) =>
545 run({
546 cwd: input.cwd,
547 operation: input.operation,
548 args: [
549 "boards",
550 "work-item",
551 "update",
552 "--detect",
553 "false",
554 "--organization",
555 input.organization,
556 "--id",
557 String(input.number),
558 ...input.args,
559 ],
560 stdin: input.stdin,
561 }).pipe(Effect.asVoid);
562
563 /** A write names its work item by id alone, so the item is first read to be the scope's own. */
564 const owned = (
565 operation: string,
566 cwd: string,
567 scope: { readonly organization: string; readonly project: string; readonly number: number },
568 ) => workItem({ ...scope, cwd, operation, closed: new Set() }).pipe(Effect.as(scope));
569
570 /** Azure keeps tags as one `; `-joined field and takes exactly one assignee. */
571 const fieldArgs = (
572 operation: string,
573 input: {
574 readonly labels?: ReadonlyArray<string> | undefined;
575 readonly assignees?: ReadonlyArray<string> | undefined;
576 },
577 ): Effect.Effect<ReadonlyArray<string>, IssueTrackerError> => {
578 if ((input.assignees?.length ?? 0) > 1) {
579 return Effect.fail(refused(operation, "An Azure DevOps work item has one assignee at most."));
580 }
581 const fields = [
582 ...(input.labels === undefined ? [] : [["System.Tags", input.labels.join("; ")] as const]),
583 ...(input.assignees === undefined
584 ? []
585 : [["System.AssignedTo", input.assignees[0] ?? ""] as const]),
586 ];
587 // `az` reads `field=@path` as that local file, and a field value has no stdin to go through.
588 if (fields.some(([, value]) => value.startsWith("@"))) {
589 return Effect.fail(
590 refused(operation, "Azure DevOps takes no label or assignee that starts with `@`."),
591 );
592 }
593 return Effect.succeed(
594 fields.length === 0 ? [] : ["--fields", ...fields.map(([name, value]) => `${name}=${value}`)],
595 );
596 };
597
598 return {
599 kind: KIND,
600 capabilities: CAPABILITIES,
601
602 // Listing filters with WIQL's `@Me`, so nothing compares against a name. Looking one up
603 // needs a profile host that a PAT saved for one organization cannot reach.
604 getViewer: () => Effect.succeed("@Me"),
605
606 listIssues: Effect.fn("AzureDevOpsIssueTracker.listIssues")(function* (input) {
607 const cursor = input.cursor === undefined ? undefined : parseCursor(input.cursor);
608 if (cursor === null) {
609 return yield* refused("listIssues", "The cursor was not one Azure DevOps handed out.");
610 }
611 const limit = Math.min(Math.max(input.limit, 1), PAGE_SIZE);
612 const text = input.query?.trim() ?? "";
613 const created = input.sort === "created";
614 const dateField = created ? "[System.CreatedDate]" : "[System.ChangedDate]";
615 return yield* scoped("listIssues", input).pipe(
616 Effect.flatMap((scope) =>
617 Cache.get(
618 listClosedStates,
619 JSON.stringify([input.cwd, scope.organization, scope.project]),
620 ).pipe(Effect.map((closed) => ({ scope, closed }))),
621 ),
622 Effect.flatMap(({ scope, closed }) =>
623 invokeWithBody({
624 cwd: input.cwd,
625 operation: "listIssues",
626 args: invokeArgs({
627 ...scope,
628 resource: "wiql",
629 method: "POST",
630 // One more than the page, which is how a next page reveals itself.
631 query: ["timePrecision=true", `$top=${limit + 1}`],
632 }),
633 body: {
634 query:
635 `SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = ${quoted(scope.project)}` +
636 stateClause(input.state, closed) +
637 involvementClause(input.involvement) +
638 (text.length === 0 ? "" : ` AND [System.Title] CONTAINS ${quoted(text)}`) +
639 (input.labels ?? [])
640 .map((label) => ` AND [System.Tags] CONTAINS ${quoted(label)}`)
641 .join("") +
642 (input.assignee === undefined
643 ? ""
644 : ` AND [System.AssignedTo] = ${quoted(input.assignee)}`) +
645 (cursor === undefined
646 ? ""
647 : ` AND (${dateField} < ${quoted(cursor.date)} OR (${dateField} = ${quoted(cursor.date)} AND [System.Id] < ${cursor.id}))`) +
648 ` ORDER BY ${dateField} DESC, [System.Id] DESC`,
649 },
650 }).pipe(
651 Effect.flatMap((raw) => {
652 const decoded = decodeAs(decodeWiql)(raw);
653 return Result.isSuccess(decoded)
654 ? Effect.succeed(decoded.success.workItems ?? [])
655 : Effect.fail(unreadable("listIssues", decoded.failure));
656 }),
657 Effect.flatMap((ids) =>
658 ids.length === 0
659 ? Effect.succeed({ items: [], nextCursor: null })
660 : invokeWithBody({
661 cwd: input.cwd,
662 operation: "listIssues",
663 // az resolves `wit/workitems` to the create route (`workitems/${type}`)
664 // and fails before sending; `workitemsbatch` has a single route.
665 args: invokeArgs({ ...scope, resource: "workitemsbatch", method: "POST" }),
666 body: {
667 ids: ids.slice(0, limit).map((row) => row.id),
668 fields: LIST_FIELDS,
669 },
670 }).pipe(
671 Effect.flatMap((raw) => {
672 const decoded = decodeWorkItemsJson(raw, closed);
673 return Result.isSuccess(decoded)
674 ? Effect.succeed(decoded.success)
675 : Effect.fail(unreadable("listIssues", decoded.failure));
676 }),
677 Effect.map((hydrated) => {
678 // The cursor is the last row WIQL sorted, so its order is restored.
679 const position = new Map(ids.map((row, index) => [String(row.id), index]));
680 const items = hydrated.toSorted(
681 (left, right) =>
682 (position.get(left.key) ?? 0) - (position.get(right.key) ?? 0),
683 );
684 const last = items.at(-1);
685 return {
686 items,
687 nextCursor:
688 ids.length > limit && last !== undefined
689 ? `${created ? last.createdAt : last.updatedAt}|${last.key}`
690 : null,
691 };
692 }),
693 ),
694 ),
695 ),
696 ),
697 );
698 }),
699
700 getIssue: (input) =>
701 target("getIssue", input).pipe(
702 Effect.flatMap((scope) =>
703 workItemTypes({ ...scope, cwd: input.cwd, operation: "getIssue" }).pipe(
704 Effect.flatMap((types) => {
705 const closed = closedStateNames(types);
706 return workItem({ ...scope, cwd: input.cwd, operation: "getIssue", closed }).pipe(
707 Effect.map((item) => ({ item, closed, states: workItemStates(types, item) })),
708 );
709 }),
710 Effect.flatMap(({ item, closed, states }) =>
711 Effect.all(
712 [
713 comments({ ...scope, cwd: input.cwd, operation: "getIssue" }),
714 updates({ ...scope, cwd: input.cwd, closed }),
715 linkedPullRequests({ cwd: input.cwd, organization: scope.organization, item }),
716 ],
717 { concurrency: 3 },
718 ).pipe(
719 Effect.map(([conversation, events, links]) => ({
720 ...item,
721 // Its type's own entry, so the category is the one that type gives the name.
722 state: states.find((state) => state.name === item.state.name) ?? item.state,
723 states,
724 // Nothing cheap names the viewer here; the service already read it per host.
725 viewer: null,
726 viewerPermissions: VIEWER_PERMISSIONS,
727 comments: conversation.comments,
728 commentsCursor: conversation.nextCursor,
729 events,
730 linkedPullRequests: links,
731 })),
732 ),
733 ),
734 ),
735 ),
736 ),
737
738 getComments: (input) =>
739 target("getComments", input).pipe(
740 // `az` would read a `continuationToken=@path` as that local file.
741 Effect.filterOrFail(
742 () => !input.cursor.startsWith("@"),
743 () => refused("getComments", "The cursor was not one Azure DevOps handed out."),
744 ),
745 Effect.flatMap((scope) =>
746 comments({ ...scope, cwd: input.cwd, operation: "getComments", cursor: input.cursor }),
747 ),
748 ),
749
750 create: (input) => {
751 const title = AzureDevOpsCli.textOption("--title", input.title);
752 const body =
753 input.body.length === 0
754 ? undefined
755 : AzureDevOpsCli.textOption("--description", input.body);
756 // az has one stdin, so a second value read from it goes in a call of its own.
757 const bodyFollows = title.stdin !== undefined && body?.stdin !== undefined;
758 return scoped("create", input).pipe(
759 Effect.flatMap((scope) =>
760 workItemTypes({ ...scope, cwd: input.cwd, operation: "create" }).pipe(
761 Effect.flatMap((types) => {
762 const names = types.flatMap((type) => (type.isDisabled ? [] : [type.name]));
763 const type = CREATE_TYPES.find((name) => names.includes(name)) ?? names[0];
764 return type === undefined
765 ? Effect.fail(refused("create", "The project offers no work item type to file."))
766 : fieldArgs("create", {
767 ...(input.labels.length === 0 ? {} : { labels: input.labels }),
768 ...(input.assignees.length === 0 ? {} : { assignees: input.assignees }),
769 }).pipe(
770 Effect.map((fields) => ({ type, fields, closed: closedStateNames(types) })),
771 );
772 }),
773 Effect.flatMap(({ type, fields, closed }) =>
774 read({
775 cwd: input.cwd,
776 operation: "create",
777 args: [
778 "boards",
779 "work-item",
780 "create",
781 "--detect",
782 "false",
783 "--organization",
784 scope.organization,
785 "--project",
786 scope.project,
787 "--type",
788 type,
789 title.arg,
790 ...(body === undefined || bodyFollows ? [] : [body.arg]),
791 ...fields,
792 ],
793 stdin: title.stdin ?? body?.stdin,
794 decode: (raw) => decodeWorkItemJson(raw, closed),
795 }),
796 ),
797 Effect.filterOrFail(
798 (item) => item !== null,
799 () => unreadable("create", "incomplete-response"),
800 ),
801 Effect.tap((item) =>
802 body === undefined || !bodyFollows
803 ? Effect.void
804 : update({
805 cwd: input.cwd,
806 operation: "create",
807 organization: scope.organization,
808 number: Number(item.key),
809 args: [body.arg],
810 stdin: body.stdin,
811 }),
812 ),
813 Effect.map((item) => ({ key: item.key, displayKey: item.displayKey, url: item.url })),
814 ),
815 ),
816 );
817 },
818
819 comment: (input) =>
820 target("comment", input).pipe(
821 Effect.flatMap((scope) =>
822 invokeWithBody({
823 cwd: input.cwd,
824 operation: "comment",
825 args: invokeArgs({
826 ...scope,
827 resource: "comments",
828 route: [`workItemId=${scope.number}`],
829 method: "POST",
830 apiVersion: "7.1-preview",
831 query: ["format=markdown", "api-version=7.1-preview.4"],
832 }),
833 body: { text: input.body },
834 }),
835 ),
836 Effect.asVoid,
837 ),
838
839 update: (input) => {
840 const texts = [
841 ...(input.title === undefined ? [] : [AzureDevOpsCli.textOption("--title", input.title)]),
842 ...(input.body === undefined
843 ? []
844 : [AzureDevOpsCli.textOption("--description", input.body)]),
845 ];
846 // az has one stdin, so each value read from it needs its own call.
847 const batches =
848 texts.filter((text) => text.stdin !== undefined).length > 1
849 ? texts.map((text) => [text])
850 : [texts];
851 return target("update", input).pipe(
852 Effect.flatMap((scope) =>
853 fieldArgs("update", input).pipe(Effect.map((fields) => ({ scope, fields }))),
854 ),
855 Effect.tap(({ scope }) => owned("update", input.cwd, scope)),
856 Effect.flatMap(({ scope, fields }) =>
857 Effect.forEach(
858 batches,
859 (batch, index) =>
860 update({
861 ...scope,
862 cwd: input.cwd,
863 operation: "update",
864 args: [...batch.map((text) => text.arg), ...(index === 0 ? fields : [])],
865 stdin: batch.find((text) => text.stdin !== undefined)?.stdin,
866 }),
867 { discard: true },
868 ),
869 ),
870 );
871 },
872
873 setState: (input) =>
874 target("setState", input).pipe(
875 // The read also proves the item is the scope's own, as `owned` does for other writes.
876 Effect.flatMap((scope) =>
877 workItem({ ...scope, cwd: input.cwd, operation: "setState", closed: new Set() }).pipe(
878 Effect.flatMap((item) =>
879 workItemTypes({ ...scope, cwd: input.cwd, operation: "setState" }).pipe(
880 Effect.map((types) => workItemStates(types, item)),
881 ),
882 ),
883 Effect.filterOrFail(
884 (states) => states.some((state) => state.name === input.state),
885 () => refused("setState", `This work item has no "${input.state}" state.`),
886 ),
887 Effect.flatMap(() =>
888 update({
889 ...scope,
890 cwd: input.cwd,
891 operation: "setState",
892 args: ["--state", input.state],
893 }),
894 ),
895 ),
896 ),
897 ),
898
899 setReaction: (input) =>
900 target("setReaction", input).pipe(
901 Effect.flatMap((scope) => {
902 const type = azureDevOpsReactionType(input.content);
903 if (input.subjectId === undefined) {
904 return Effect.fail(
905 refused("setReaction", "Azure DevOps reactions go on comments only."),
906 );
907 }
908 if (!/^[1-9]\d{0,9}$/.test(input.subjectId)) {
909 return Effect.fail(
910 refused("setReaction", "The comment id names no Azure DevOps comment."),
911 );
912 }
913 if (type === null) {
914 return Effect.fail(refused("setReaction", "Azure DevOps has no such reaction."));
915 }
916 return run({
917 cwd: input.cwd,
918 operation: "setReaction",
919 args: invokeArgs({
920 ...scope,
921 resource: "commentsReactions",
922 route: [
923 `workItemId=${scope.number}`,
924 `commentId=${input.subjectId}`,
925 `reactionType=${type}`,
926 ],
927 method: input.reacted ? "PUT" : "DELETE",
928 apiVersion: "7.1-preview",
929 query: ["api-version=7.1-preview.1"],
930 }),
931 }).pipe(Effect.asVoid);
932 }),
933 ),
934
935 listCandidates: (input) =>
936 scoped("listCandidates", input).pipe(
937 Effect.flatMap((scope) =>
938 Effect.all(
939 [
940 read({
941 cwd: input.cwd,
942 operation: "listCandidates",
943 args: invokeArgs({ ...scope, resource: "tags" }),
944 decode: decodeAs(decodeTags),
945 }).pipe(
946 Effect.map((tags) =>
947 tags.value.map((tag) => ({ name: tag.name, color: null, description: null })),
948 ),
949 ),
950 // Nothing in `az boards` lists who a work item may go to; the project's teams are
951 // the nearest thing, read a handful at a time.
952 read({
953 cwd: input.cwd,
954 operation: "listCandidates",
955 args: [
956 "devops",
957 "team",
958 "list",
959 "--detect",
960 "false",
961 "--organization",
962 scope.organization,
963 "--project",
964 scope.project,
965 "--top",
966 "10",
967 ],
968 decode: decodeAs(decodeTeams),
969 }).pipe(
970 Effect.flatMap((teams) =>
971 Effect.forEach(
972 teams,
973 (team) =>
974 read({
975 cwd: input.cwd,
976 operation: "listCandidates",
977 args: [
978 "devops",
979 "team",
980 "list-member",
981 "--detect",
982 "false",
983 "--organization",
984 scope.organization,
985 "--project",
986 scope.project,
987 "--team",
988 team.id,
989 "--top",
990 String(PAGE_SIZE),
991 ],
992 decode: decodeAs(decodeMembers),
993 }),
994 { concurrency: 3 },
995 ),
996 ),
997 Effect.map((members) => {
998 const byLogin = new Map<
999 string,
1000 { id: string; login: string; name: string | null; avatarUrl: string | null }
1001 >();
1002 for (const { identity } of members.flat()) {
1003 const login = identity.uniqueName.trim();
1004 if (
1005 identity.isContainer ||
1006 login.length === 0 ||
1007 byLogin.has(login.toLowerCase())
1008 ) {
1009 continue;
1010 }
1011 byLogin.set(login.toLowerCase(), {
1012 id: login,
1013 login,
1014 name: identity.displayName?.trim() || null,
1015 avatarUrl: identity.imageUrl?.trim() || null,
1016 });
1017 }
1018 return [...byLogin.values()];
1019 }),
1020 ),
1021 ],
1022 { concurrency: 2 },
1023 ),
1024 ),
1025 // Teams are a sample of who can be assigned, so somebody missing is not ineligible.
1026 Effect.map(([labels, assignees]) => ({ labels, assignees, truncated: true })),
1027 ),
1028 };
1029});