@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 1,042 lines 37.8 KB
Raw
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 */
6 import * as Cache from "effect/Cache";
7 import * as Duration from "effect/Duration";
8 import * as Effect from "effect/Effect";
9 import * as Exit from "effect/Exit";
10 import * as FileSystem from "effect/FileSystem";
11 import * as Result from "effect/Result";
12 import * as Schema from "effect/Schema";
13 import {
14 IssueTrackerKind,
15 type IssueCapabilities,
16 type IssueEvent,
17 type IssueInvolvement,
18 type IssueLinkedPullRequest,
19 type IssueViewerPermissions,
20 } from "@t3tools/contracts";
21 import {
22 IssueTrackerError,
23 type IssueTrackerApi,
24 } from "@t3tools/source-control-core/server/IssueTracker";
25
26 import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
27 import {
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";
39 import { decodePullRequestJson } from "./azureDevOpsPullRequestJson.ts";
40
41 const KIND = IssueTrackerKind.make("azure-devops");
42
43 const 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 */
63 const VIEWER_PERMISSIONS: IssueViewerPermissions = {
64 setState: true,
65 comment: true,
66 edit: true,
67 labels: true,
68 assignees: true,
69 };
70
71 const REST_API_VERSION = "7.1";
72 const PAGE_SIZE = 100;
73 const CLOSED_STATES_TTL = Duration.minutes(10);
74 /** Updates are read a page per `az` process, oldest first, so a long history is bounded. */
75 const UPDATE_PAGE_LIMIT = 5;
76 /** Linked pull requests are read one `az` process each, so a work item's links are bounded. */
77 const LINKED_PULL_REQUEST_LIMIT = 10;
78 /** Which work item type a new issue is filed as, in order of preference across the stock processes. */
79 const CREATE_TYPES = ["Issue", "Bug", "Task", "User Story", "Product Backlog Item"];
80
81 const 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
95 const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
96 const decodeWiql = Schema.decodeUnknownResult(
97 Schema.Struct({
98 workItems: Schema.optional(Schema.NullOr(Schema.Array(Schema.Struct({ id: Schema.Int })))),
99 }),
100 );
101 const 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 );
114 const decodeTags = Schema.decodeUnknownResult(
115 Schema.Struct({ value: Schema.Array(Schema.Struct({ name: Schema.String })) }),
116 );
117 const decodeTeams = Schema.decodeUnknownResult(Schema.Array(Schema.Struct({ id: Schema.String })));
118 const 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 );
130 const decodeUnknown = Schema.decodeUnknownResult(Schema.fromJsonString(Schema.Unknown));
131
132 /** The parts of an `organization/project` scope, as the organization URL and the project name. */
133 function 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
150 function 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. */
155 function quoted(value: string): string {
156 return `'${value.replaceAll("'", "''")}'`;
157 }
158
159 function 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
173 function 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. */
186 function 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
191 function 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
206 export 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 // Shares one in-flight workflow read per project; only a success replaces the cached states.
364 const workflowReads = 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 Effect.tap((closed) => Cache.set(listClosedStates, key, closed)),
370 );
371 },
372 { capacity: Infinity, timeToLive: () => Duration.zero },
373 );
374 // Each `az` call costs seconds of startup, and a project's states rarely change.
375 const listClosedStates: Cache.Cache<string, ClosedStates, IssueTrackerError> =
376 yield* Cache.makeWith((key: string) => Cache.get(workflowReads, key), {
377 capacity: 256,
378 timeToLive: (exit) => (Exit.isSuccess(exit) ? CLOSED_STATES_TTL : Duration.zero),
379 });
380
381 const workItem = (input: {
382 readonly cwd: string;
383 readonly operation: string;
384 readonly organization: string;
385 readonly project: string;
386 readonly number: number;
387 readonly closed: ClosedStates;
388 }): Effect.Effect<AzureDevOpsWorkItem, IssueTrackerError> =>
389 read({
390 cwd: input.cwd,
391 operation: input.operation,
392 args: [
393 "boards",
394 "work-item",
395 "show",
396 "--detect",
397 "false",
398 "--organization",
399 input.organization,
400 "--id",
401 String(input.number),
402 "--expand",
403 "relations",
404 ],
405 decode: (raw) => decodeWorkItemJson(raw, input.closed),
406 }).pipe(
407 Effect.filterOrFail(
408 (item) => item !== null,
409 () => notFound(input.operation),
410 ),
411 // `az` addresses a work item by organization and id alone, so one from another project
412 // answers too; the scope names a project, and an item outside it is not this scope's.
413 Effect.filterOrFail(
414 (item) => item.project?.toLowerCase() === input.project.toLowerCase(),
415 () => notFound(input.operation),
416 ),
417 );
418
419 /** The work item as `az` addresses it, or a not-found for a key that names no id. */
420 const target = (
421 operation: string,
422 input: { readonly host: string; readonly scope: string; readonly key: string },
423 ) =>
424 scoped(operation, input).pipe(
425 Effect.flatMap((scope) => {
426 const number = parseNumber(input.key);
427 return number === null
428 ? Effect.fail(notFound(operation))
429 : Effect.succeed({ ...scope, number });
430 }),
431 );
432
433 /** Newest first, so the first page is the current discussion and a cursor leads to older ones. */
434 const comments = (input: {
435 readonly cwd: string;
436 readonly operation: string;
437 readonly organization: string;
438 readonly project: string;
439 readonly number: number;
440 readonly cursor?: string | undefined;
441 }) =>
442 read({
443 cwd: input.cwd,
444 operation: input.operation,
445 args: invokeArgs({
446 ...input,
447 resource: "comments",
448 route: [`workItemId=${input.number}`],
449 apiVersion: "7.1-preview",
450 query: [
451 `$top=${PAGE_SIZE}`,
452 "order=desc",
453 "$expand=reactions",
454 "api-version=7.1-preview.4",
455 ...(input.cursor === undefined ? [] : [`continuationToken=${input.cursor}`]),
456 ],
457 }),
458 decode: decodeCommentsJson,
459 }).pipe(Effect.map((page) => ({ ...page, comments: page.comments.toReversed() })));
460
461 const updates = Effect.fn("AzureDevOpsIssueTracker.updates")(function* (input: {
462 readonly cwd: string;
463 readonly organization: string;
464 readonly project: string;
465 readonly number: number;
466 readonly closed: ClosedStates;
467 }) {
468 const events: IssueEvent[] = [];
469 for (let page = 0; page < UPDATE_PAGE_LIMIT; page += 1) {
470 const answer = yield* read({
471 cwd: input.cwd,
472 operation: "getIssue",
473 args: invokeArgs({
474 ...input,
475 resource: "updates",
476 route: [`id=${input.number}`],
477 query: [`$top=${PAGE_SIZE}`, ...(page === 0 ? [] : [`$skip=${page * PAGE_SIZE}`])],
478 }),
479 decode: (raw) => decodeUpdatesJson(raw, input.closed),
480 });
481 events.push(...answer.events);
482 if (answer.count < PAGE_SIZE) break;
483 }
484 return events;
485 });
486
487 const linkedPullRequests = (input: {
488 readonly cwd: string;
489 readonly organization: string;
490 readonly item: AzureDevOpsWorkItem;
491 }): Effect.Effect<ReadonlyArray<IssueLinkedPullRequest>, IssueTrackerError> => {
492 const numbers = [
493 ...new Set(input.item.relations.flatMap((relation) => pullRequestNumberOf(relation) ?? [])),
494 ].slice(0, LINKED_PULL_REQUEST_LIMIT);
495 return Effect.forEach(
496 numbers,
497 (number) =>
498 read({
499 cwd: input.cwd,
500 operation: "getIssue",
501 args: [
502 "repos",
503 "pr",
504 "show",
505 "--detect",
506 "false",
507 "--organization",
508 input.organization,
509 "--id",
510 String(number),
511 ],
512 decode: decodePullRequestJson,
513 }).pipe(
514 Effect.map((pullRequest) =>
515 pullRequest === null || pullRequest.location === null
516 ? []
517 : [
518 {
519 repository: `${pullRequest.location.project}/${pullRequest.location.repository}`,
520 number: pullRequest.number,
521 title: pullRequest.title,
522 url: pullRequest.url,
523 state: pullRequest.state,
524 isDraft: pullRequest.isDraft,
525 // Azure links a pull request to a work item but never says whether completing
526 // it resolves the item; that lives in a completion option nothing reports.
527 closesIssue: false,
528 },
529 ],
530 ),
531 // A link to a pull request this account cannot see is left out, not a failed detail.
532 Effect.catchIf(
533 (error) => error.reason === "not-found",
534 () => Effect.succeed([]),
535 ),
536 ),
537 { concurrency: 2 },
538 ).pipe(Effect.map((links) => links.flat()));
539 };
540
541 const update = (input: {
542 readonly cwd: string;
543 readonly operation: string;
544 readonly organization: string;
545 readonly number: number;
546 readonly args: ReadonlyArray<string>;
547 readonly stdin?: string | undefined;
548 }) =>
549 run({
550 cwd: input.cwd,
551 operation: input.operation,
552 args: [
553 "boards",
554 "work-item",
555 "update",
556 "--detect",
557 "false",
558 "--organization",
559 input.organization,
560 "--id",
561 String(input.number),
562 ...input.args,
563 ],
564 stdin: input.stdin,
565 }).pipe(Effect.asVoid);
566
567 /** Azure keeps tags as one `; `-joined field and takes exactly one assignee. */
568 const fieldArgs = (
569 operation: string,
570 input: {
571 readonly labels?: ReadonlyArray<string> | undefined;
572 readonly assignees?: ReadonlyArray<string> | undefined;
573 },
574 ): Effect.Effect<ReadonlyArray<string>, IssueTrackerError> => {
575 if ((input.assignees?.length ?? 0) > 1) {
576 return Effect.fail(refused(operation, "An Azure DevOps work item has one assignee at most."));
577 }
578 const fields = [
579 ...(input.labels === undefined ? [] : [["System.Tags", input.labels.join("; ")] as const]),
580 ...(input.assignees === undefined
581 ? []
582 : [["System.AssignedTo", input.assignees[0] ?? ""] as const]),
583 ];
584 // `az` reads `field=@path` as that local file, and a field value has no stdin to go through.
585 if (fields.some(([, value]) => value.startsWith("@"))) {
586 return Effect.fail(
587 refused(operation, "Azure DevOps takes no label or assignee that starts with `@`."),
588 );
589 }
590 return Effect.succeed(fields.map(([name, value]) => `${name}=${value}`));
591 };
592
593 return {
594 kind: KIND,
595 capabilities: CAPABILITIES,
596
597 // Listing filters with WIQL's `@Me`, so nothing compares against a name. Looking one up
598 // needs a profile host that a PAT saved for one organization cannot reach.
599 getViewer: () => Effect.succeed("@Me"),
600
601 listIssues: Effect.fn("AzureDevOpsIssueTracker.listIssues")(function* (input) {
602 const cursor = input.cursor === undefined ? undefined : parseCursor(input.cursor);
603 if (cursor === null) {
604 return yield* refused("listIssues", "The cursor was not one Azure DevOps handed out.");
605 }
606 const limit = Math.min(Math.max(input.limit, 1), PAGE_SIZE);
607 const text = input.query?.trim() ?? "";
608 const created = input.sort === "created";
609 const dateField = created ? "[System.CreatedDate]" : "[System.ChangedDate]";
610 return yield* scoped("listIssues", input).pipe(
611 Effect.flatMap((scope) => {
612 const key = JSON.stringify([input.cwd, scope.organization, scope.project]);
613 const refresh = cursor === undefined && input.refresh === true;
614 const closed = refresh ? Cache.get(workflowReads, key) : Cache.get(listClosedStates, key);
615 return closed.pipe(Effect.map((closed) => ({ scope, closed })));
616 }),
617 Effect.flatMap(({ scope, closed }) =>
618 invokeWithBody({
619 cwd: input.cwd,
620 operation: "listIssues",
621 args: invokeArgs({
622 ...scope,
623 resource: "wiql",
624 method: "POST",
625 // One more than the page, which is how a next page reveals itself.
626 query: ["timePrecision=true", `$top=${limit + 1}`],
627 }),
628 body: {
629 query:
630 `SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = ${quoted(scope.project)}` +
631 stateClause(input.state, closed) +
632 involvementClause(input.involvement) +
633 (text.length === 0 ? "" : ` AND [System.Title] CONTAINS ${quoted(text)}`) +
634 (input.labels ?? [])
635 .map((label) => ` AND [System.Tags] CONTAINS ${quoted(label)}`)
636 .join("") +
637 (input.assignee === undefined
638 ? ""
639 : ` AND [System.AssignedTo] = ${quoted(input.assignee)}`) +
640 (cursor === undefined
641 ? ""
642 : ` AND (${dateField} < ${quoted(cursor.date)} OR (${dateField} = ${quoted(cursor.date)} AND [System.Id] < ${cursor.id}))`) +
643 ` ORDER BY ${dateField} DESC, [System.Id] DESC`,
644 },
645 }).pipe(
646 Effect.flatMap((raw) => {
647 const decoded = decodeAs(decodeWiql)(raw);
648 return Result.isSuccess(decoded)
649 ? Effect.succeed(decoded.success.workItems ?? [])
650 : Effect.fail(unreadable("listIssues", decoded.failure));
651 }),
652 Effect.flatMap((ids) =>
653 ids.length === 0
654 ? Effect.succeed({ items: [], nextCursor: null })
655 : invokeWithBody({
656 cwd: input.cwd,
657 operation: "listIssues",
658 // az resolves `wit/workitems` to the create route (`workitems/${type}`)
659 // and fails before sending; `workitemsbatch` has a single route.
660 args: invokeArgs({ ...scope, resource: "workitemsbatch", method: "POST" }),
661 body: {
662 ids: ids.slice(0, limit).map((row) => row.id),
663 fields: LIST_FIELDS,
664 },
665 }).pipe(
666 Effect.flatMap((raw) => {
667 const decoded = decodeWorkItemsJson(raw, closed);
668 return Result.isSuccess(decoded)
669 ? Effect.succeed(decoded.success)
670 : Effect.fail(unreadable("listIssues", decoded.failure));
671 }),
672 Effect.map((hydrated) => {
673 // The cursor is the last row WIQL sorted, so its order is restored.
674 const position = new Map(ids.map((row, index) => [String(row.id), index]));
675 const items = hydrated.toSorted(
676 (left, right) =>
677 (position.get(left.key) ?? 0) - (position.get(right.key) ?? 0),
678 );
679 const last = items.at(-1);
680 return {
681 items,
682 nextCursor:
683 ids.length > limit && last !== undefined
684 ? `${created ? last.createdAt : last.updatedAt}|${last.key}`
685 : null,
686 };
687 }),
688 ),
689 ),
690 ),
691 ),
692 );
693 }),
694
695 getIssue: (input) =>
696 target("getIssue", input).pipe(
697 Effect.flatMap((scope) =>
698 workItemTypes({ ...scope, cwd: input.cwd, operation: "getIssue" }).pipe(
699 Effect.flatMap((types) => {
700 const closed = closedStateNames(types);
701 return workItem({ ...scope, cwd: input.cwd, operation: "getIssue", closed }).pipe(
702 Effect.map((item) => ({ item, closed, states: workItemStates(types, item) })),
703 );
704 }),
705 Effect.flatMap(({ item, closed, states }) =>
706 Effect.all(
707 [
708 comments({ ...scope, cwd: input.cwd, operation: "getIssue" }),
709 updates({ ...scope, cwd: input.cwd, closed }),
710 linkedPullRequests({ cwd: input.cwd, organization: scope.organization, item }),
711 ],
712 { concurrency: 3 },
713 ).pipe(
714 Effect.map(([conversation, events, links]) => ({
715 ...item,
716 // Its type's own entry, so the category is the one that type gives the name.
717 state: states.find((state) => state.name === item.state.name) ?? item.state,
718 states,
719 // Nothing cheap names the viewer here; the service already read it per host.
720 viewer: null,
721 viewerPermissions: VIEWER_PERMISSIONS,
722 comments: conversation.comments,
723 commentsCursor: conversation.nextCursor,
724 events,
725 linkedPullRequests: links,
726 })),
727 ),
728 ),
729 ),
730 ),
731 ),
732
733 getComments: (input) =>
734 target("getComments", input).pipe(
735 // `az` would read a `continuationToken=@path` as that local file.
736 Effect.filterOrFail(
737 () => !input.cursor.startsWith("@"),
738 () => refused("getComments", "The cursor was not one Azure DevOps handed out."),
739 ),
740 Effect.flatMap((scope) =>
741 comments({ ...scope, cwd: input.cwd, operation: "getComments", cursor: input.cursor }),
742 ),
743 ),
744
745 create: (input) => {
746 const title = AzureDevOpsCli.textOption("--title", input.title);
747 const body =
748 input.body.length === 0
749 ? undefined
750 : AzureDevOpsCli.textOption("--description", input.body);
751 // az has one stdin, so a second value read from it goes in a call of its own.
752 const bodyFollows = title.stdin !== undefined && body?.stdin !== undefined;
753 return scoped("create", input).pipe(
754 Effect.flatMap((scope) =>
755 workItemTypes({ ...scope, cwd: input.cwd, operation: "create" }).pipe(
756 Effect.flatMap((types) => {
757 const names = types.flatMap((type) => (type.isDisabled ? [] : [type.name]));
758 const type = CREATE_TYPES.find((name) => names.includes(name)) ?? names[0];
759 return type === undefined
760 ? Effect.fail(refused("create", "The project offers no work item type to file."))
761 : fieldArgs("create", {
762 ...(input.labels.length === 0 ? {} : { labels: input.labels }),
763 ...(input.assignees.length === 0 ? {} : { assignees: input.assignees }),
764 }).pipe(
765 Effect.map((fields) => ({ type, fields, closed: closedStateNames(types) })),
766 );
767 }),
768 Effect.flatMap(({ type, fields, closed }) =>
769 read({
770 cwd: input.cwd,
771 operation: "create",
772 args: [
773 "boards",
774 "work-item",
775 "create",
776 "--detect",
777 "false",
778 "--organization",
779 scope.organization,
780 "--project",
781 scope.project,
782 "--type",
783 type,
784 title.arg,
785 ...(body === undefined || bodyFollows ? [] : [body.arg]),
786 ...(fields.length === 0 ? [] : ["--fields", ...fields]),
787 ],
788 stdin: title.stdin ?? body?.stdin,
789 decode: (raw) => decodeWorkItemJson(raw, closed),
790 }),
791 ),
792 Effect.filterOrFail(
793 (item) => item !== null,
794 () => unreadable("create", "incomplete-response"),
795 ),
796 Effect.tap((item) =>
797 body === undefined || !bodyFollows
798 ? Effect.void
799 : update({
800 cwd: input.cwd,
801 operation: "create",
802 organization: scope.organization,
803 number: Number(item.key),
804 args: [body.arg],
805 stdin: body.stdin,
806 }),
807 ),
808 Effect.map((item) => ({ key: item.key, displayKey: item.displayKey, url: item.url })),
809 ),
810 ),
811 );
812 },
813
814 comment: (input) =>
815 target("comment", input).pipe(
816 Effect.flatMap((scope) =>
817 invokeWithBody({
818 cwd: input.cwd,
819 operation: "comment",
820 args: invokeArgs({
821 ...scope,
822 resource: "comments",
823 route: [`workItemId=${scope.number}`],
824 method: "POST",
825 apiVersion: "7.1-preview",
826 query: ["format=markdown", "api-version=7.1-preview.4"],
827 }),
828 body: { text: input.body },
829 }),
830 ),
831 Effect.asVoid,
832 ),
833
834 update: (input) =>
835 target("update", input).pipe(
836 Effect.flatMap((scope) =>
837 fieldArgs("update", input).pipe(Effect.map((fields) => ({ scope, fields }))),
838 ),
839 // `az` names a work item by id alone, so the read proves the item is the scope's own; it
840 // also names the field the item keeps its text in.
841 Effect.flatMap(({ scope, fields }) =>
842 workItem({ ...scope, cwd: input.cwd, operation: "update", closed: new Set() }).pipe(
843 Effect.map((item) => ({ scope, fields, bodyField: item.bodyField })),
844 ),
845 ),
846 Effect.flatMap(({ scope, fields, bodyField }) => {
847 const texts = [
848 ...(input.title === undefined
849 ? []
850 : [{ ...AzureDevOpsCli.textOption("--title", input.title), field: false }]),
851 ...(input.body === undefined
852 ? []
853 : bodyField === "System.Description"
854 ? [{ ...AzureDevOpsCli.textOption("--description", input.body), field: false }]
855 : [{ ...AzureDevOpsCli.textOption(bodyField, input.body), field: true }]),
856 ];
857 // az has one stdin, so each value read from it needs its own call.
858 const batches =
859 texts.filter((text) => text.stdin !== undefined).length > 1
860 ? texts.map((text) => [text])
861 : [texts];
862 return Effect.forEach(
863 batches,
864 (batch, index) => {
865 // az keeps only the last `--fields`, so every field of a call goes in one.
866 const pairs = [
867 ...(index === 0 ? fields : []),
868 ...batch.flatMap((text) => (text.field ? [text.arg] : [])),
869 ];
870 return update({
871 ...scope,
872 cwd: input.cwd,
873 operation: "update",
874 args: [
875 ...batch.flatMap((text) => (text.field ? [] : [text.arg])),
876 ...(pairs.length === 0 ? [] : ["--fields", ...pairs]),
877 ],
878 stdin: batch.find((text) => text.stdin !== undefined)?.stdin,
879 });
880 },
881 { discard: true },
882 );
883 }),
884 ),
885
886 setState: (input) =>
887 target("setState", input).pipe(
888 // `az` names a work item by id alone, so the read also proves the item is the scope's own.
889 Effect.flatMap((scope) =>
890 workItem({ ...scope, cwd: input.cwd, operation: "setState", closed: new Set() }).pipe(
891 Effect.flatMap((item) =>
892 workItemTypes({ ...scope, cwd: input.cwd, operation: "setState" }).pipe(
893 Effect.map((types) => workItemStates(types, item)),
894 ),
895 ),
896 Effect.filterOrFail(
897 (states) => states.some((state) => state.name === input.state),
898 () => refused("setState", `This work item has no "${input.state}" state.`),
899 ),
900 Effect.flatMap(() =>
901 update({
902 ...scope,
903 cwd: input.cwd,
904 operation: "setState",
905 args: ["--state", input.state],
906 }),
907 ),
908 ),
909 ),
910 ),
911
912 setReaction: (input) =>
913 target("setReaction", input).pipe(
914 Effect.flatMap((scope) => {
915 const type = azureDevOpsReactionType(input.content);
916 if (input.subjectId === undefined) {
917 return Effect.fail(
918 refused("setReaction", "Azure DevOps reactions go on comments only."),
919 );
920 }
921 if (!/^[1-9]\d{0,9}$/.test(input.subjectId)) {
922 return Effect.fail(
923 refused("setReaction", "The comment id names no Azure DevOps comment."),
924 );
925 }
926 if (type === null) {
927 return Effect.fail(refused("setReaction", "Azure DevOps has no such reaction."));
928 }
929 return run({
930 cwd: input.cwd,
931 operation: "setReaction",
932 args: invokeArgs({
933 ...scope,
934 resource: "commentsReactions",
935 route: [
936 `workItemId=${scope.number}`,
937 `commentId=${input.subjectId}`,
938 `reactionType=${type}`,
939 ],
940 method: input.reacted ? "PUT" : "DELETE",
941 apiVersion: "7.1-preview",
942 query: ["api-version=7.1-preview.1"],
943 }),
944 }).pipe(Effect.asVoid);
945 }),
946 ),
947
948 listCandidates: (input) =>
949 scoped("listCandidates", input).pipe(
950 Effect.flatMap((scope) =>
951 Effect.all(
952 [
953 read({
954 cwd: input.cwd,
955 operation: "listCandidates",
956 args: invokeArgs({ ...scope, resource: "tags" }),
957 decode: decodeAs(decodeTags),
958 }).pipe(
959 Effect.map((tags) =>
960 tags.value.map((tag) => ({ name: tag.name, color: null, description: null })),
961 ),
962 ),
963 // Nothing in `az boards` lists who a work item may go to; the project's teams are
964 // the nearest thing, read a handful at a time.
965 read({
966 cwd: input.cwd,
967 operation: "listCandidates",
968 args: [
969 "devops",
970 "team",
971 "list",
972 "--detect",
973 "false",
974 "--organization",
975 scope.organization,
976 "--project",
977 scope.project,
978 "--top",
979 "10",
980 ],
981 decode: decodeAs(decodeTeams),
982 }).pipe(
983 Effect.flatMap((teams) =>
984 Effect.forEach(
985 teams,
986 (team) =>
987 read({
988 cwd: input.cwd,
989 operation: "listCandidates",
990 args: [
991 "devops",
992 "team",
993 "list-member",
994 "--detect",
995 "false",
996 "--organization",
997 scope.organization,
998 "--project",
999 scope.project,
1000 "--team",
1001 team.id,
1002 "--top",
1003 String(PAGE_SIZE),
1004 ],
1005 decode: decodeAs(decodeMembers),
1006 }),
1007 { concurrency: 3 },
1008 ),
1009 ),
1010 Effect.map((members) => {
1011 const byLogin = new Map<
1012 string,
1013 { id: string; login: string; name: string | null; avatarUrl: string | null }
1014 >();
1015 for (const { identity } of members.flat()) {
1016 const login = identity.uniqueName.trim();
1017 if (
1018 identity.isContainer ||
1019 login.length === 0 ||
1020 byLogin.has(login.toLowerCase())
1021 ) {
1022 continue;
1023 }
1024 byLogin.set(login.toLowerCase(), {
1025 id: login,
1026 login,
1027 name: identity.displayName?.trim() || null,
1028 avatarUrl: identity.imageUrl?.trim() || null,
1029 });
1030 }
1031 return [...byLogin.values()];
1032 }),
1033 ),
1034 ],
1035 { concurrency: 2 },
1036 ),
1037 ),
1038 // Teams are a sample of who can be assigned, so somebody missing is not ineligible.
1039 Effect.map(([labels, assignees]) => ({ labels, assignees, truncated: true })),
1040 ),
1041 };
1042 });