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