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
| 1 | /** |
| 2 | * Decoders for Azure DevOps work items as `az boards` and the `wit` REST area answer them. Azure |
| 3 | * keeps everything under `fields`, keyed by reference name, and a project may add fields of its |
| 4 | * own, so only the ones every work item type carries are read. |
| 5 | * |
| 6 | * @module source-control-azure-devops/server/azureDevOpsIssueJson |
| 7 | */ |
| 8 | import * as Exit from "effect/Exit"; |
| 9 | import * as Result from "effect/Result"; |
| 10 | import * as Schema from "effect/Schema"; |
| 11 | import type { |
| 12 | IssueActor, |
| 13 | IssueComment, |
| 14 | IssueEvent, |
| 15 | IssueLabel, |
| 16 | IssueReaction, |
| 17 | IssueReactionContent, |
| 18 | IssueState, |
| 19 | } from "@t3tools/contracts"; |
| 20 | import { decodeJsonResult } from "@t3tools/shared/schemaJson"; |
| 21 | import type { TrackerIssueSummary } from "@t3tools/source-control-core/server/IssueTracker"; |
| 22 | |
| 23 | /** Lowercased names of the states a project treats as finished, read by `closedStateNames`. */ |
| 24 | export type ClosedStates = ReadonlySet<string>; |
| 25 | |
| 26 | /** The finished states of Azure's stock processes, for a project whose types report none. */ |
| 27 | const STOCK_CLOSED_STATES: ClosedStates = new Set([ |
| 28 | "closed", |
| 29 | "done", |
| 30 | "removed", |
| 31 | "resolved", |
| 32 | "completed", |
| 33 | ]); |
| 34 | |
| 35 | const FINISHED_CATEGORIES: ReadonlySet<string> = new Set(["Resolved", "Completed", "Removed"]); |
| 36 | |
| 37 | /** The stock Basic, Agile and Scrum states, for a work item whose type reports none. */ |
| 38 | const STOCK_STATES: ReadonlyArray<IssueState> = [ |
| 39 | { category: "open", name: "New" }, |
| 40 | { category: "open", name: "To Do" }, |
| 41 | { category: "open", name: "Active" }, |
| 42 | { category: "open", name: "Doing" }, |
| 43 | { category: "closed", name: "Resolved" }, |
| 44 | { category: "closed", name: "Done" }, |
| 45 | { category: "closed", name: "Closed" }, |
| 46 | { category: "closed", name: "Removed" }, |
| 47 | ]; |
| 48 | |
| 49 | type WorkItemTypes = ReadonlyArray<{ |
| 50 | readonly name: string; |
| 51 | readonly states?: ReadonlyArray<{ readonly name: string; readonly category: string }> | undefined; |
| 52 | }>; |
| 53 | |
| 54 | /** |
| 55 | * A project's finished states, from its work item types' state categories. Custom processes |
| 56 | * name their own columns, so the category, not the name, says whether one is finished. |
| 57 | */ |
| 58 | export function closedStateNames(types: WorkItemTypes): ClosedStates { |
| 59 | const names = types.flatMap((type) => |
| 60 | (type.states ?? []).flatMap((state) => |
| 61 | FINISHED_CATEGORIES.has(state.category) ? [state.name.toLowerCase()] : [], |
| 62 | ), |
| 63 | ); |
| 64 | return names.length === 0 ? STOCK_CLOSED_STATES : new Set(names); |
| 65 | } |
| 66 | |
| 67 | const Identity = Schema.Struct({ |
| 68 | displayName: Schema.optional(Schema.NullOr(Schema.String)), |
| 69 | uniqueName: Schema.optional(Schema.NullOr(Schema.String)), |
| 70 | imageUrl: Schema.optional(Schema.NullOr(Schema.String)), |
| 71 | }); |
| 72 | |
| 73 | /** WIQL answers an identity as an object; a project rule can leave a plain "Name <email>" string. */ |
| 74 | const IdentityValue = Schema.NullOr(Schema.Union([Identity, Schema.String])); |
| 75 | |
| 76 | const Fields = Schema.Struct({ |
| 77 | "System.CommentCount": Schema.optional(Schema.NullOr(Schema.Int)), |
| 78 | "System.Title": Schema.optional(Schema.NullOr(Schema.String)), |
| 79 | "System.State": Schema.optional(Schema.NullOr(Schema.String)), |
| 80 | "System.CreatedDate": Schema.optional(Schema.NullOr(Schema.String)), |
| 81 | "System.ChangedDate": Schema.optional(Schema.NullOr(Schema.String)), |
| 82 | "Microsoft.VSTS.Common.ClosedDate": Schema.optional(Schema.NullOr(Schema.String)), |
| 83 | "System.Description": Schema.optional(Schema.NullOr(Schema.String)), |
| 84 | "Microsoft.VSTS.TCM.ReproSteps": Schema.optional(Schema.NullOr(Schema.String)), |
| 85 | "System.Tags": Schema.optional(Schema.NullOr(Schema.String)), |
| 86 | "System.TeamProject": Schema.optional(Schema.NullOr(Schema.String)), |
| 87 | "System.WorkItemType": Schema.optional(Schema.NullOr(Schema.String)), |
| 88 | "System.CreatedBy": Schema.optional(IdentityValue), |
| 89 | "System.AssignedTo": Schema.optional(IdentityValue), |
| 90 | }); |
| 91 | |
| 92 | const Relation = Schema.Struct({ rel: Schema.String, url: Schema.String }); |
| 93 | |
| 94 | const WorkItem = Schema.Struct({ |
| 95 | id: Schema.Int, |
| 96 | url: Schema.optional(Schema.NullOr(Schema.String)), |
| 97 | fields: Schema.optional(Schema.NullOr(Fields)), |
| 98 | relations: Schema.optional(Schema.NullOr(Schema.Array(Relation))), |
| 99 | }); |
| 100 | |
| 101 | const decodeWorkItemEntry = Schema.decodeUnknownExit(WorkItem); |
| 102 | const decodeWorkItemList = decodeJsonResult( |
| 103 | Schema.Struct({ value: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))) }), |
| 104 | ); |
| 105 | const decodeWorkItem = decodeJsonResult(WorkItem); |
| 106 | |
| 107 | type DecodeFailure = |
| 108 | ReturnType<typeof decodeWorkItem> extends Result.Result<unknown, infer E> ? E : never; |
| 109 | |
| 110 | function trimmed(value: string | null | undefined): string | null { |
| 111 | const text = value?.trim() ?? ""; |
| 112 | return text.length > 0 ? text : null; |
| 113 | } |
| 114 | |
| 115 | /** |
| 116 | * The organization link `az` returns addresses the REST resource, which is not a page anybody can |
| 117 | * open. The one a reader wants is the board's own item, which Azure spells this way. |
| 118 | */ |
| 119 | function browserUrl( |
| 120 | apiUrl: string | null | undefined, |
| 121 | id: number, |
| 122 | project: string | null, |
| 123 | ): string | null { |
| 124 | if (apiUrl === null || apiUrl === undefined || project === null) return null; |
| 125 | const match = /^(https?:\/\/([^/]+))(?:\/([^/]+))?(?:\/[^/]+)?\/_apis\/wit\/workItems\//i.exec( |
| 126 | apiUrl, |
| 127 | ); |
| 128 | if (match === null) return null; |
| 129 | const [, origin, host, organization] = match; |
| 130 | // A legacy organization is its hostname, so whatever the path starts with is a project. |
| 131 | const base = host!.toLowerCase().endsWith(".visualstudio.com") |
| 132 | ? origin |
| 133 | : organization === undefined |
| 134 | ? null |
| 135 | : `${origin}/${organization}`; |
| 136 | return base === null ? null : `${base}/${encodeURIComponent(project)}/_workitems/edit/${id}`; |
| 137 | } |
| 138 | |
| 139 | function toActor(value: typeof IdentityValue.Type | undefined): IssueActor | null { |
| 140 | if (value === null || value === undefined) return null; |
| 141 | if (typeof value === "string") { |
| 142 | const login = trimmed(value); |
| 143 | return login === null ? null : { login, name: null, avatarUrl: null }; |
| 144 | } |
| 145 | const login = trimmed(value.uniqueName) ?? trimmed(value.displayName); |
| 146 | return login === null |
| 147 | ? null |
| 148 | : { login, name: trimmed(value.displayName), avatarUrl: trimmed(value.imageUrl) }; |
| 149 | } |
| 150 | |
| 151 | function toIssueState(name: string | null | undefined, closed: ClosedStates): IssueState { |
| 152 | const state = trimmed(name) ?? "New"; |
| 153 | return { category: closed.has(state.toLowerCase()) ? "closed" : "open", name: state }; |
| 154 | } |
| 155 | |
| 156 | /** Azure keeps tags as one `; `-separated string, with no colour anywhere. */ |
| 157 | function toLabels(tags: string | null | undefined): ReadonlyArray<IssueLabel> { |
| 158 | return [...new Set((tags ?? "").split(";").flatMap((tag) => trimmed(tag) ?? []))].map((name) => ({ |
| 159 | name, |
| 160 | color: null, |
| 161 | })); |
| 162 | } |
| 163 | |
| 164 | /** The field a work item keeps its text in, which is the one an edit of its body writes. */ |
| 165 | export type BodyField = "System.Description" | "Microsoft.VSTS.TCM.ReproSteps"; |
| 166 | |
| 167 | export interface AzureDevOpsWorkItem extends TrackerIssueSummary { |
| 168 | readonly body: string; |
| 169 | readonly bodyField: BodyField; |
| 170 | readonly project: string | null; |
| 171 | readonly workItemType: string | null; |
| 172 | readonly relations: ReadonlyArray<typeof Relation.Type>; |
| 173 | } |
| 174 | |
| 175 | /** A Bug has Repro Steps where other types have a Description, and in Agile and CMMI no Description. */ |
| 176 | function bodyFieldOf(fields: typeof Fields.Type): BodyField { |
| 177 | const bug = trimmed(fields["System.WorkItemType"])?.toLowerCase() === "bug"; |
| 178 | return trimmed(fields["System.Description"]) === null && |
| 179 | (bug || trimmed(fields["Microsoft.VSTS.TCM.ReproSteps"]) !== null) |
| 180 | ? "Microsoft.VSTS.TCM.ReproSteps" |
| 181 | : "System.Description"; |
| 182 | } |
| 183 | |
| 184 | /** Null for a row this cannot place: no title, no dates, or no project to build a link from. */ |
| 185 | function toWorkItem(raw: typeof WorkItem.Type, closed: ClosedStates): AzureDevOpsWorkItem | null { |
| 186 | const fields = raw.fields ?? {}; |
| 187 | const title = trimmed(fields["System.Title"]); |
| 188 | const createdAt = trimmed(fields["System.CreatedDate"]); |
| 189 | const updatedAt = trimmed(fields["System.ChangedDate"]) ?? createdAt; |
| 190 | const project = trimmed(fields["System.TeamProject"]); |
| 191 | const url = browserUrl(raw.url, raw.id, project); |
| 192 | if (raw.id <= 0 || title === null || createdAt === null || updatedAt === null || url === null) { |
| 193 | return null; |
| 194 | } |
| 195 | const assignee = toActor(fields["System.AssignedTo"]); |
| 196 | const bodyField = bodyFieldOf(fields); |
| 197 | return { |
| 198 | key: String(raw.id), |
| 199 | displayKey: `#${raw.id}`, |
| 200 | title, |
| 201 | url, |
| 202 | author: toActor(fields["System.CreatedBy"]), |
| 203 | state: toIssueState(fields["System.State"], closed), |
| 204 | createdAt, |
| 205 | updatedAt, |
| 206 | closedAt: trimmed(fields["Microsoft.VSTS.Common.ClosedDate"]), |
| 207 | assignees: assignee === null ? [] : [assignee], |
| 208 | labels: toLabels(fields["System.Tags"]), |
| 209 | commentCount: Math.max(0, fields["System.CommentCount"] ?? 0), |
| 210 | body: fields[bodyField] ?? "", |
| 211 | bodyField, |
| 212 | project, |
| 213 | workItemType: trimmed(fields["System.WorkItemType"]), |
| 214 | relations: raw.relations ?? [], |
| 215 | }; |
| 216 | } |
| 217 | |
| 218 | /** |
| 219 | * The states a work item can be in: its own type's, in the order Azure lists them, which differ |
| 220 | * per type and per process. The item's current state is always among them, even when the type |
| 221 | * could not be read and the stock list stands in. |
| 222 | */ |
| 223 | export function workItemStates( |
| 224 | types: WorkItemTypes, |
| 225 | item: Pick<AzureDevOpsWorkItem, "workItemType" | "state">, |
| 226 | ): ReadonlyArray<IssueState> { |
| 227 | const type = types.find((entry) => entry.name.toLowerCase() === item.workItemType?.toLowerCase()); |
| 228 | const own = (type?.states ?? []).flatMap((state): ReadonlyArray<IssueState> => { |
| 229 | const name = trimmed(state.name); |
| 230 | return name === null |
| 231 | ? [] |
| 232 | : [{ category: FINISHED_CATEGORIES.has(state.category) ? "closed" : "open", name }]; |
| 233 | }); |
| 234 | const states = own.length === 0 ? STOCK_STATES : own; |
| 235 | return states.some((state) => state.name === item.state.name) ? states : [...states, item.state]; |
| 236 | } |
| 237 | |
| 238 | /** The `{ count, value }` page `wit/workitemsbatch` answers; a row this cannot place is skipped. */ |
| 239 | export function decodeWorkItemsJson( |
| 240 | raw: string, |
| 241 | closed: ClosedStates, |
| 242 | ): Result.Result<ReadonlyArray<AzureDevOpsWorkItem>, DecodeFailure> { |
| 243 | return Result.map(decodeWorkItemList(raw), (page) => |
| 244 | (page.value ?? []).flatMap((entry) => { |
| 245 | const item = decodeWorkItemEntry(entry); |
| 246 | if (Exit.isFailure(item)) return []; |
| 247 | return toWorkItem(item.value, closed) ?? []; |
| 248 | }), |
| 249 | ); |
| 250 | } |
| 251 | |
| 252 | /** Null where az answered with a work item this cannot place, which the caller reports as such. */ |
| 253 | export function decodeWorkItemJson( |
| 254 | raw: string, |
| 255 | closed: ClosedStates, |
| 256 | ): Result.Result<AzureDevOpsWorkItem | null, DecodeFailure> { |
| 257 | return Result.map(decodeWorkItem(raw), (item) => toWorkItem(item, closed)); |
| 258 | } |
| 259 | |
| 260 | /** Azure names comment reactions after its own icons; the six it has map onto the contract's. */ |
| 261 | const CONTENT_BY_REACTION: Readonly<Record<string, IssueReactionContent>> = { |
| 262 | like: "thumbs-up", |
| 263 | dislike: "thumbs-down", |
| 264 | heart: "heart", |
| 265 | hooray: "hooray", |
| 266 | smile: "laugh", |
| 267 | confused: "confused", |
| 268 | }; |
| 269 | |
| 270 | export function azureDevOpsReactionType(content: IssueReactionContent): string | null { |
| 271 | return Object.entries(CONTENT_BY_REACTION).find(([, mapped]) => mapped === content)?.[0] ?? null; |
| 272 | } |
| 273 | |
| 274 | const Comment = Schema.Struct({ |
| 275 | id: Schema.Int, |
| 276 | text: Schema.optional(Schema.NullOr(Schema.String)), |
| 277 | createdDate: Schema.String, |
| 278 | createdBy: Schema.optional(Schema.NullOr(Identity)), |
| 279 | isDeleted: Schema.optional(Schema.Boolean), |
| 280 | reactions: Schema.optional( |
| 281 | Schema.NullOr( |
| 282 | Schema.Array( |
| 283 | Schema.Struct({ |
| 284 | type: Schema.String, |
| 285 | count: Schema.Int, |
| 286 | isCurrentUserEngaged: Schema.optional(Schema.Boolean), |
| 287 | }), |
| 288 | ), |
| 289 | ), |
| 290 | ), |
| 291 | }); |
| 292 | |
| 293 | const CommentsPage = Schema.Struct({ |
| 294 | comments: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))), |
| 295 | continuationToken: Schema.optional(Schema.NullOr(Schema.String)), |
| 296 | }); |
| 297 | |
| 298 | const decodeCommentsPage = decodeJsonResult(CommentsPage); |
| 299 | const decodeCommentEntry = Schema.decodeUnknownExit(Comment); |
| 300 | |
| 301 | function toReactions(raw: (typeof Comment.Type)["reactions"]): ReadonlyArray<IssueReaction> { |
| 302 | return (raw ?? []).flatMap((reaction) => { |
| 303 | const content = CONTENT_BY_REACTION[reaction.type.toLowerCase()]; |
| 304 | return content === undefined || reaction.count <= 0 |
| 305 | ? [] |
| 306 | : [ |
| 307 | { |
| 308 | content, |
| 309 | count: reaction.count, |
| 310 | // Azure counts reactions and says whether the reader is among them, but names nobody. |
| 311 | actors: [], |
| 312 | viewerHasReacted: reaction.isCurrentUserEngaged ?? false, |
| 313 | }, |
| 314 | ]; |
| 315 | }); |
| 316 | } |
| 317 | |
| 318 | export function decodeCommentsJson( |
| 319 | raw: string, |
| 320 | ): Result.Result< |
| 321 | { readonly comments: ReadonlyArray<IssueComment>; readonly nextCursor: string | null }, |
| 322 | DecodeFailure |
| 323 | > { |
| 324 | return Result.map(decodeCommentsPage(raw), (page) => ({ |
| 325 | comments: (page.comments ?? []).flatMap((entry) => { |
| 326 | const comment = decodeCommentEntry(entry); |
| 327 | if (Exit.isFailure(comment) || comment.value.isDeleted === true) return []; |
| 328 | return [ |
| 329 | { |
| 330 | id: String(comment.value.id), |
| 331 | author: toActor(comment.value.createdBy), |
| 332 | body: comment.value.text ?? "", |
| 333 | createdAt: comment.value.createdDate, |
| 334 | url: null, |
| 335 | reactions: toReactions(comment.value.reactions), |
| 336 | }, |
| 337 | ]; |
| 338 | }), |
| 339 | nextCursor: trimmed(page.continuationToken), |
| 340 | })); |
| 341 | } |
| 342 | |
| 343 | const FieldChange = Schema.Struct({ |
| 344 | oldValue: Schema.optional(Schema.Unknown), |
| 345 | newValue: Schema.optional(Schema.Unknown), |
| 346 | }); |
| 347 | |
| 348 | const Update = Schema.Struct({ |
| 349 | id: Schema.Int, |
| 350 | revisedDate: Schema.String, |
| 351 | revisedBy: Schema.optional(Schema.NullOr(Identity)), |
| 352 | fields: Schema.optional(Schema.NullOr(Schema.Record(Schema.String, FieldChange))), |
| 353 | }); |
| 354 | |
| 355 | const decodeUpdatesPage = decodeJsonResult( |
| 356 | Schema.Struct({ value: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))) }), |
| 357 | ); |
| 358 | const decodeUpdateEntry = Schema.decodeUnknownExit(Update); |
| 359 | const decodeIdentityValue = Schema.decodeUnknownExit(IdentityValue); |
| 360 | |
| 361 | function identityLogin(value: unknown): string | null { |
| 362 | const decoded = decodeIdentityValue(value); |
| 363 | return Exit.isSuccess(decoded) ? (toActor(decoded.value)?.login ?? null) : null; |
| 364 | } |
| 365 | |
| 366 | /** |
| 367 | * The timeline, read out of each revision's field changes, with how many updates the page held. |
| 368 | * `revisedDate` is when a revision was superseded, `9999-01-01` on the newest, so an event is |
| 369 | * dated by the revision's changed date where Azure states one. |
| 370 | */ |
| 371 | export function decodeUpdatesJson( |
| 372 | raw: string, |
| 373 | closed: ClosedStates, |
| 374 | ): Result.Result< |
| 375 | { readonly events: ReadonlyArray<IssueEvent>; readonly count: number }, |
| 376 | DecodeFailure |
| 377 | > { |
| 378 | return Result.map(decodeUpdatesPage(raw), (page) => ({ |
| 379 | count: (page.value ?? []).length, |
| 380 | events: (page.value ?? []).flatMap((entry) => { |
| 381 | const update = decodeUpdateEntry(entry); |
| 382 | if (Exit.isFailure(update) || update.value.id === 1) return []; |
| 383 | const { id, revisedBy, revisedDate } = update.value; |
| 384 | const fields = update.value.fields ?? {}; |
| 385 | const changedDate = fields["System.ChangedDate"]?.newValue; |
| 386 | const createdAt = typeof changedDate === "string" ? changedDate : revisedDate; |
| 387 | const events: IssueEvent[] = []; |
| 388 | const add = (kind: IssueEvent["kind"], detail: string | null) => |
| 389 | events.push({ |
| 390 | id: `update-${id}-${events.length}`, |
| 391 | kind, |
| 392 | actor: toActor(revisedBy), |
| 393 | createdAt, |
| 394 | detail, |
| 395 | }); |
| 396 | const state = fields["System.State"]; |
| 397 | if (typeof state?.oldValue === "string" && typeof state.newValue === "string") { |
| 398 | const was = toIssueState(state.oldValue, closed); |
| 399 | const now = toIssueState(state.newValue, closed); |
| 400 | add( |
| 401 | was.category === now.category |
| 402 | ? "state-changed" |
| 403 | : now.category === "closed" |
| 404 | ? "closed" |
| 405 | : "reopened", |
| 406 | now.name, |
| 407 | ); |
| 408 | } |
| 409 | const title = fields["System.Title"]; |
| 410 | if (typeof title?.oldValue === "string" && typeof title.newValue === "string") { |
| 411 | add("renamed", trimmed(title.newValue)); |
| 412 | } |
| 413 | const tags = fields["System.Tags"]; |
| 414 | if (tags !== undefined) { |
| 415 | const before = toLabels(typeof tags.oldValue === "string" ? tags.oldValue : null); |
| 416 | const after = toLabels(typeof tags.newValue === "string" ? tags.newValue : null); |
| 417 | for (const tag of before) |
| 418 | if (!after.some((label) => label.name === tag.name)) add("unlabeled", tag.name); |
| 419 | for (const tag of after) |
| 420 | if (!before.some((label) => label.name === tag.name)) add("labeled", tag.name); |
| 421 | } |
| 422 | const assigned = fields["System.AssignedTo"]; |
| 423 | if (assigned !== undefined) { |
| 424 | const before = identityLogin(assigned.oldValue); |
| 425 | const after = identityLogin(assigned.newValue); |
| 426 | if (before !== after) { |
| 427 | if (before !== null) add("unassigned", before); |
| 428 | if (after !== null) add("assigned", after); |
| 429 | } |
| 430 | } |
| 431 | return events; |
| 432 | }), |
| 433 | })); |
| 434 | } |
| 435 | |
| 436 | /** A relation that links a pull request, as Azure spells it: `vstfs:///Git/PullRequestId/{project}/{repo}/{id}`. */ |
| 437 | export function pullRequestNumberOf(relation: typeof Relation.Type): number | null { |
| 438 | if (relation.rel !== "ArtifactLink") return null; |
| 439 | const match = /^vstfs:\/\/\/Git\/PullRequestId\/(.+)$/.exec(relation.url); |
| 440 | if (match === null) return null; |
| 441 | const number = decodeURIComponent(match[1]!).split("/").at(-1) ?? ""; |
| 442 | return /^[1-9]\d{0,9}$/.test(number) ? Number(number) : null; |
| 443 | } |