Open History to see the last commit
1import * as Schema from "effect/Schema";
2import * as HttpServerRespondable from "effect/http/HttpServerRespondable";
3import * as HttpServerResponse from "effect/http/HttpServerResponse";
4
5import {
6 IsoDateTime,
7 NonNegativeInt,
8 PositiveInt,
9 ProjectId,
10 ThreadId,
11 TrimmedNonEmptyString,
12} from "./baseSchemas.ts";
13import {
14 PullRequestActor,
15 PullRequestLabel,
16 PullRequestReaction,
17 PullRequestReactionContent,
18 PullRequestState,
19} from "./pullRequest.ts";
20
21/**
22 * Which tracker an issue lives in. Git hosts reuse their `SourceControlProviderKind` spelling
23 * (`github`, `gitlab`); standalone trackers get their own (`linear`, `jira`). Branded apart from
24 * the source control kind because the two sets are not the same: Bitbucket is a git host with no
25 * tracker, and Linear is a tracker with no git host.
26 */
27export const IssueTrackerKind = TrimmedNonEmptyString.check(
28 Schema.isMaxLength(64),
29 Schema.isPattern(/^[a-z][a-z0-9-]*$/),
30).pipe(Schema.brand("IssueTrackerKind"));
31export type IssueTrackerKind = typeof IssueTrackerKind.Type;
32
33/**
34 * One saved account of a standalone tracker. A tracker's first account has none: it predates
35 * accounts, and keeps its credential and bindings unchanged.
36 */
37export const IssueTrackerAccountId = TrimmedNonEmptyString.check(
38 Schema.isMaxLength(64),
39 Schema.isPattern(/^[a-z0-9][a-z0-9-]*$/),
40).pipe(Schema.brand("IssueTrackerAccountId"));
41export type IssueTrackerAccountId = typeof IssueTrackerAccountId.Type;
42
43export const IssueActor = PullRequestActor;
44export type IssueActor = typeof IssueActor.Type;
45
46export const IssueLabel = PullRequestLabel;
47export type IssueLabel = typeof IssueLabel.Type;
48
49/**
50 * Where an issue stands: the tracker's own name for the state ("In Review", "Closed as not
51 * planned"), which is what people read and what a move is asked for by, and the category every
52 * tracker has, which only filters and colours key off. Nothing moves an issue to "open" or
53 * "closed": it moves to one of the states its `IssueDetail.states` lists.
54 */
55export const IssueStateCategory = Schema.Literals(["open", "closed"]);
56export type IssueStateCategory = typeof IssueStateCategory.Type;
57
58export const IssueState = Schema.Struct({
59 category: IssueStateCategory,
60 name: TrimmedNonEmptyString,
61 /** How a closed state ended, where the tracker says: `completed`, or its word for not done. */
62 closeReason: Schema.optional(TrimmedNonEmptyString),
63});
64export type IssueState = typeof IssueState.Type;
65
66/** What a listing asks for: either category, or both. */
67export const IssueListState = Schema.Literals(["all", "open", "closed"]);
68export type IssueListState = typeof IssueListState.Type;
69
70export const IssueInvolvement = Schema.Literals(["all", "assigned", "authored", "mentioned"]);
71export type IssueInvolvement = typeof IssueInvolvement.Type;
72
73/** Newest first by the named date. */
74export const IssueListSort = Schema.Literals(["updated", "created"]);
75export type IssueListSort = typeof IssueListSort.Type;
76
77export const IssueReactionContent = PullRequestReactionContent;
78export type IssueReactionContent = typeof IssueReactionContent.Type;
79
80export const IssueReaction = PullRequestReaction;
81export type IssueReaction = typeof IssueReaction.Type;
82
83/**
84 * Addresses one issue: `scope` is the tracker's own container (`owner/repo`, a team key) and
85 * `key` the issue's native id in it. `host` is absent for the kind's public host. `projectId`
86 * names the project whose credentials serve the read, which need not own the issue.
87 */
88export const IssueRef = Schema.Struct({
89 projectId: ProjectId,
90 tracker: IssueTrackerKind,
91 host: Schema.optional(TrimmedNonEmptyString),
92 scope: TrimmedNonEmptyString,
93 key: TrimmedNonEmptyString,
94});
95export type IssueRef = typeof IssueRef.Type;
96
97/** A scope with no issue in it, for reads about the container itself: templates, candidates. */
98export const IssueScopeRef = Schema.Struct({
99 projectId: ProjectId,
100 tracker: IssueTrackerKind,
101 host: Schema.optional(TrimmedNonEmptyString),
102 scope: TrimmedNonEmptyString,
103});
104export type IssueScopeRef = typeof IssueScopeRef.Type;
105
106/** One row of a listing. Carries everything a list needs and nothing a detail needs. */
107export const IssueSummary = Schema.Struct({
108 tracker: IssueTrackerKind,
109 host: TrimmedNonEmptyString,
110 scope: TrimmedNonEmptyString,
111 key: TrimmedNonEmptyString,
112 /** How the tracker writes the key for people: `#123` on a git host, `ENG-123` on Linear. */
113 displayKey: TrimmedNonEmptyString,
114 title: TrimmedNonEmptyString,
115 url: TrimmedNonEmptyString,
116 author: Schema.NullOr(IssueActor),
117 state: IssueState,
118 createdAt: IsoDateTime,
119 updatedAt: IsoDateTime,
120 closedAt: Schema.NullOr(IsoDateTime),
121 assignees: Schema.Array(IssueActor),
122 labels: Schema.Array(IssueLabel),
123 commentCount: NonNegativeInt,
124});
125export type IssueSummary = typeof IssueSummary.Type;
126
127export const IssueListEntry = Schema.Struct({
128 ...IssueSummary.fields,
129 projectId: ProjectId,
130 projectTitle: TrimmedNonEmptyString,
131});
132export type IssueListEntry = typeof IssueListEntry.Type;
133
134export const IssueComment = Schema.Struct({
135 id: TrimmedNonEmptyString,
136 author: Schema.NullOr(IssueActor),
137 body: Schema.String,
138 createdAt: IsoDateTime,
139 url: Schema.NullOr(Schema.String),
140 /** Absent from a tracker with no reactions, which differs from none on this comment. */
141 reactions: Schema.optional(Schema.Array(IssueReaction)),
142});
143export type IssueComment = typeof IssueComment.Type;
144
145/**
146 * Something that happened to an issue that nobody wrote words for: it was closed, labelled,
147 * assigned, renamed. Kinds are the common vocabulary; a tracker drops what it cannot map rather
148 * than guessing.
149 */
150export const IssueEventKind = Schema.Literals([
151 "closed",
152 "reopened",
153 "labeled",
154 "unlabeled",
155 "assigned",
156 "unassigned",
157 "renamed",
158 "referenced",
159 "state-changed",
160]);
161export type IssueEventKind = typeof IssueEventKind.Type;
162
163export const IssueEventReference = Schema.Struct({
164 repository: TrimmedNonEmptyString,
165 number: PositiveInt,
166 kind: Schema.Literals(["issue", "pull-request"]),
167 url: TrimmedNonEmptyString,
168});
169export type IssueEventReference = typeof IssueEventReference.Type;
170
171export const IssueEvent = Schema.Struct({
172 id: TrimmedNonEmptyString,
173 kind: IssueEventKind,
174 actor: Schema.NullOr(IssueActor),
175 createdAt: IsoDateTime,
176 /** What the event was about, where it has a subject: a label name, a login, a new title. */
177 detail: Schema.NullOr(TrimmedNonEmptyString),
178 /** The issue or change request a `referenced` event came from, so a surface can open it. */
179 reference: Schema.optional(IssueEventReference),
180});
181export type IssueEvent = typeof IssueEvent.Type;
182
183/** A change request the tracker says closes or mentions this issue. */
184export const IssueLinkedPullRequest = Schema.Struct({
185 repository: TrimmedNonEmptyString,
186 number: PositiveInt,
187 title: TrimmedNonEmptyString,
188 url: TrimmedNonEmptyString,
189 state: PullRequestState,
190 isDraft: Schema.Boolean,
191 /** Merging it closes this issue, rather than only citing it. */
192 closesIssue: Schema.Boolean,
193});
194export type IssueLinkedPullRequest = typeof IssueLinkedPullRequest.Type;
195
196/**
197 * What a tracker can do at all, so a surface never offers an action that would fail. The
198 * service refuses a call outside these before it reaches the driver.
199 */
200export const IssueCapabilities = Schema.Struct({
201 create: Schema.Boolean,
202 /** Title and body can be rewritten after filing. */
203 edit: Schema.Boolean,
204 comment: Schema.Boolean,
205 labels: Schema.Boolean,
206 assignees: Schema.Boolean,
207 /** Reactions can be read and written on the issue and its comments. */
208 reactions: Schema.Boolean,
209 /** The scope offers starting points for a new issue. */
210 templates: Schema.Boolean,
211 /** The tracker reports linked change requests of its own accord. */
212 linkedPullRequests: Schema.Boolean,
213 /** State changes arrive as events beside the comments, not only as comments. */
214 events: Schema.Boolean,
215 /** The tracker narrows a listing by free text itself. */
216 search: Schema.Boolean,
217});
218export type IssueCapabilities = typeof IssueCapabilities.Type;
219
220/**
221 * What the signed-in account may do with this issue, which `capabilities` says nothing about.
222 * A permission the tracker reports nothing about is granted, so a refusal comes from the
223 * tracker, which says why, rather than from a missing control.
224 */
225export const IssueViewerPermissions = Schema.Struct({
226 setState: Schema.Boolean,
227 comment: Schema.Boolean,
228 edit: Schema.Boolean,
229 labels: Schema.Boolean,
230 assignees: Schema.Boolean,
231});
232export type IssueViewerPermissions = typeof IssueViewerPermissions.Type;
233
234export const IssueDetail = Schema.Struct({
235 ...IssueSummary.fields,
236 projectId: ProjectId,
237 projectTitle: TrimmedNonEmptyString,
238 /** False for an issue outside every project's scope, which is read-only through this server. */
239 writable: Schema.Boolean,
240 capabilities: IssueCapabilities,
241 viewerPermissions: IssueViewerPermissions,
242 /**
243 * Every state this issue can be in, in the tracker's workflow order, its current one included.
244 * Empty means its state cannot be changed from here.
245 */
246 states: Schema.Array(IssueState),
247 /** The signed-in account, so a comment edit is offered only on the viewer's own remarks. */
248 viewer: Schema.NullOr(TrimmedNonEmptyString),
249 body: Schema.String,
250 reactions: Schema.optional(Schema.Array(IssueReaction)),
251 comments: Schema.Array(IssueComment),
252 /** Where older comments carry on; null once the conversation is whole. */
253 commentsCursor: Schema.NullOr(TrimmedNonEmptyString),
254 events: Schema.Array(IssueEvent),
255 linkedPullRequests: Schema.Array(IssueLinkedPullRequest),
256});
257export type IssueDetail = typeof IssueDetail.Type;
258
259export const IssueDetailInput = Schema.Struct({
260 ...IssueRef.fields,
261 /** An explicit refresh reads the tracker instead of a recently shared read. */
262 refresh: Schema.optional(Schema.Boolean),
263});
264export type IssueDetailInput = typeof IssueDetailInput.Type;
265
266/** Older comments, one page past a cursor the detail or a previous page handed over. */
267export const IssueCommentsPageInput = Schema.Struct({
268 ...IssueRef.fields,
269 cursor: TrimmedNonEmptyString.check(Schema.isMaxLength(4_096)),
270});
271export type IssueCommentsPageInput = typeof IssueCommentsPageInput.Type;
272
273export const IssueCommentsPage = Schema.Struct({
274 comments: Schema.Array(IssueComment),
275 nextCursor: Schema.NullOr(TrimmedNonEmptyString),
276});
277export type IssueCommentsPage = typeof IssueCommentsPage.Type;
278
279/** Where each scope a listing already reached carries on, keyed `"<host> <scope>"`. */
280export const IssueListCursors = Schema.Record(
281 TrimmedNonEmptyString,
282 TrimmedNonEmptyString.check(Schema.isMaxLength(4_096)),
283);
284export type IssueListCursors = typeof IssueListCursors.Type;
285
286export const ISSUE_LIST_MAX_EXCLUDED_PROJECTS = 1_000;
287
288export const IssueListInput = Schema.Struct({
289 state: IssueListState,
290 involvement: Schema.optional(IssueInvolvement),
291 projectId: Schema.optional(ProjectId),
292 /** Projects left out of the listing, as the issues page hides them. */
293 excludeProjectIds: Schema.optional(
294 Schema.Array(ProjectId).check(Schema.isMaxLength(ISSUE_LIST_MAX_EXCLUDED_PROJECTS)),
295 ),
296 /** Narrows to one host, named as the host itself. Absent means every host the workspace has. */
297 host: Schema.optional(TrimmedNonEmptyString),
298 /** Rows per scope, which with a continuation is rows per slice. */
299 limit: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 200 }))),
300 /** Carry on from an earlier answer: only the scopes named here are read, one slice each. */
301 cursors: Schema.optional(IssueListCursors),
302 /** An explicit refresh of the first page may also refresh tracker metadata. */
303 refresh: Schema.optional(Schema.Boolean),
304 /** Free text the trackers themselves are asked to match. */
305 query: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(200))),
306 /** Label names an issue must carry, every one of them. */
307 labels: Schema.optional(
308 Schema.Array(TrimmedNonEmptyString.check(Schema.isMaxLength(200))).check(
309 Schema.isMaxLength(20),
310 ),
311 ),
312 /** An assignee's `login`, as an issue of that tracker names them. */
313 assignee: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(320))),
314 /** Absent means `updated`. */
315 sort: Schema.optional(IssueListSort),
316});
317export type IssueListInput = typeof IssueListInput.Type;
318
319/** One tracker account the workspace has projects on, and whether it can be read right now. */
320export const IssueTrackerSummary = Schema.Struct({
321 tracker: IssueTrackerKind,
322 host: TrimmedNonEmptyString,
323 projectCount: PositiveInt,
324 capabilities: Schema.NullOr(IssueCapabilities),
325 /** False when the tracker's tool or credentials are missing, with `detail` saying which. */
326 configured: Schema.Boolean,
327 detail: Schema.NullOr(TrimmedNonEmptyString),
328});
329export type IssueTrackerSummary = typeof IssueTrackerSummary.Type;
330
331export const IssueListProjectError = Schema.Struct({
332 projectId: ProjectId,
333 projectTitle: TrimmedNonEmptyString,
334 message: TrimmedNonEmptyString,
335});
336export type IssueListProjectError = typeof IssueListProjectError.Type;
337
338export const IssueListResult = Schema.Struct({
339 /** The signed-in account per host that involvement compared against. Empty for `all`. */
340 viewers: Schema.Record(TrimmedNonEmptyString, TrimmedNonEmptyString),
341 trackers: Schema.Array(IssueTrackerSummary),
342 /** Newest first by the requested `sort` (`updated` when absent), across every scope this answer covers. */
343 entries: Schema.Array(IssueListEntry),
344 errors: Schema.Array(IssueListProjectError),
345 /** Where each scope carries on, sent straight back as `cursors`. Absent once a scope is done. */
346 nextCursors: IssueListCursors,
347 /**
348 * Every scope the listing covers, matched or not, with one project that reads it. A Linear team
349 * bound in settings is named nowhere else. Absent from servers that predate it.
350 */
351 scopes: Schema.optional(Schema.Array(IssueScopeRef)),
352});
353export type IssueListResult = typeof IssueListResult.Type;
354
355const IssueTitle = TrimmedNonEmptyString.check(Schema.isMaxLength(1024));
356// Not trimmed: a body is markdown, where leading spaces open a code block. The bound keeps
357// oversized payloads off the wire; the service rejects a comment that is only whitespace.
358const IssueBody = Schema.String.check(Schema.isMaxLength(65_536));
359const CommentBody = Schema.String.check(Schema.isNonEmpty()).check(Schema.isMaxLength(65_536));
360
361export const IssueCreateInput = Schema.Struct({
362 ...IssueScopeRef.fields,
363 title: IssueTitle,
364 /** May be empty: an issue with a title and nothing else is a legitimate one. */
365 body: IssueBody,
366 labels: Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(50)),
367 assignees: Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(25)),
368});
369export type IssueCreateInput = typeof IssueCreateInput.Type;
370
371export const IssueCreateResult = Schema.Struct({
372 key: TrimmedNonEmptyString,
373 displayKey: TrimmedNonEmptyString,
374 url: TrimmedNonEmptyString,
375});
376export type IssueCreateResult = typeof IssueCreateResult.Type;
377
378export const IssueCommentInput = Schema.Struct({
379 ...IssueRef.fields,
380 body: CommentBody,
381});
382export type IssueCommentInput = typeof IssueCommentInput.Type;
383
384/**
385 * Rewrites the issue's own fields. Every field is optional and only the present ones are
386 * written; `labels` and `assignees` are the whole set, which is how every tracker writes them.
387 * The service refuses a request with nothing present.
388 */
389export const IssueUpdateInput = Schema.Struct({
390 ...IssueRef.fields,
391 title: Schema.optional(IssueTitle),
392 body: Schema.optional(IssueBody),
393 labels: Schema.optional(Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(50))),
394 assignees: Schema.optional(Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(25))),
395});
396export type IssueUpdateInput = typeof IssueUpdateInput.Type;
397
398/** Moves the issue to one of the states the tracker declared in `capabilities.states`. */
399export const IssueSetStateInput = Schema.Struct({
400 ...IssueRef.fields,
401 /** The name of one of the issue's `states`. */
402 state: TrimmedNonEmptyString,
403});
404export type IssueSetStateInput = typeof IssueSetStateInput.Type;
405
406export const IssueReactionInput = Schema.Struct({
407 ...IssueRef.fields,
408 /** Absent reacts to the issue itself; present names a comment id as the detail carried it. */
409 subjectId: Schema.optional(TrimmedNonEmptyString),
410 content: IssueReactionContent,
411 reacted: Schema.Boolean,
412});
413export type IssueReactionInput = typeof IssueReactionInput.Type;
414
415/**
416 * One starting point a scope offers for a new issue. Only the body-shaped kind travels here:
417 * GitHub's typed issue forms are flattened to a body by the driver, so a composer on any
418 * tracker is one text box with a draft in it.
419 */
420export const IssueTemplate = Schema.Struct({
421 key: TrimmedNonEmptyString,
422 name: TrimmedNonEmptyString,
423 about: Schema.String,
424 title: Schema.String,
425 body: Schema.String,
426 labels: Schema.Array(TrimmedNonEmptyString),
427 assignees: Schema.Array(TrimmedNonEmptyString),
428});
429export type IssueTemplate = typeof IssueTemplate.Type;
430
431/** A starting point only the tracker's own site can render: Linear's form and rich templates. */
432export const IssueExternalTemplate = Schema.Struct({
433 name: TrimmedNonEmptyString,
434 about: Schema.String,
435 /** Opens the exact template on the tracker, ready to fill in. */
436 url: TrimmedNonEmptyString,
437});
438export type IssueExternalTemplate = typeof IssueExternalTemplate.Type;
439
440export const IssueTemplateList = Schema.Struct({
441 templates: Schema.Array(IssueTemplate),
442 /** Absent from a tracker whose every template is body-shaped. */
443 externalTemplates: Schema.optional(Schema.Array(IssueExternalTemplate)),
444 /** False where the scope's config forbids an issue filed from nothing. */
445 blankIssuesEnabled: Schema.Boolean,
446});
447export type IssueTemplateList = typeof IssueTemplateList.Type;
448
449export const IssueLabelCandidate = Schema.Struct({
450 ...IssueLabel.fields,
451 description: Schema.NullOr(Schema.String),
452});
453export type IssueLabelCandidate = typeof IssueLabelCandidate.Type;
454
455export const IssueAssigneeCandidate = Schema.Struct({
456 ...IssueActor.fields,
457 /** How the tracker addresses this person on a write, which is not always the login. */
458 id: TrimmedNonEmptyString,
459});
460export type IssueAssigneeCandidate = typeof IssueAssigneeCandidate.Type;
461
462/** The labels and people a scope offers, read when a picker opens rather than with every issue. */
463export const IssueCandidates = Schema.Struct({
464 labels: Schema.Array(IssueLabelCandidate),
465 assignees: Schema.Array(IssueAssigneeCandidate),
466 /** The tracker has more than were read, so somebody missing is not necessarily ineligible. */
467 truncated: Schema.Boolean,
468});
469export type IssueCandidates = typeof IssueCandidates.Type;
470
471export const IssueUnavailableReason = Schema.Literals([
472 "tool-missing",
473 "unauthenticated",
474 "tracker-unsupported",
475]);
476export type IssueUnavailableReason = typeof IssueUnavailableReason.Type;
477
478/** The tracker cannot be read at all for this project, as opposed to one request failing. */
479export class IssueUnavailableError extends Schema.TaggedError<IssueUnavailableError>()(
480 "IssueUnavailableError",
481 {
482 reason: IssueUnavailableReason,
483 tracker: Schema.optional(IssueTrackerKind),
484 cause: Schema.optional(Schema.Defect()),
485 },
486 { httpApiStatus: 503 },
487) {
488 [HttpServerRespondable.symbol]() {
489 return HttpServerResponse.schemaJson(IssueUnavailableError)(this, { status: 503 });
490 }
491
492 override get message(): string {
493 switch (this.reason) {
494 case "tool-missing":
495 return "The tool this tracker is read through is not installed or set up.";
496 case "unauthenticated":
497 return "This tracker has no working credentials.";
498 case "tracker-unsupported":
499 return "Issues cannot be browsed for this project yet.";
500 }
501 }
502}
503
504export class IssueOperationError extends Schema.TaggedError<IssueOperationError>()(
505 "IssueOperationError",
506 {
507 operation: Schema.String,
508 detail: TrimmedNonEmptyString,
509 reason: Schema.optional(Schema.Literals(["not-found", "read-only", "rate-limited"])),
510 retryAt: Schema.optional(Schema.Number),
511 cause: Schema.optional(Schema.Defect()),
512 },
513 // Not 502: Cloudflare, in front of T3 Connect, swaps an origin 502 for its own page.
514 { httpApiStatus: 503 },
515) {
516 [HttpServerRespondable.symbol]() {
517 return HttpServerResponse.schemaJson(IssueOperationError)(this, { status: 503 });
518 }
519
520 override get message(): string {
521 return `Issue operation ${this.operation} failed: ${this.detail}`;
522 }
523}
524
525export type IssueError = IssueUnavailableError | IssueOperationError;
526
527/** Who created a thread ↔ issue link. */
528export const ThreadIssueLinkSource = Schema.Literals(["manual", "agent"]);
529export type ThreadIssueLinkSource = typeof ThreadIssueLinkSource.Type;
530
531/**
532 * Identity of an issue as a thread link sees it: tracker-level, so the same issue linked through
533 * two projects compares equal. `host` is always written here, unlike `IssueRef`, because a link
534 * outlives the project whose binding supplied the default.
535 */
536export const ThreadIssueKey = Schema.Struct({
537 tracker: IssueTrackerKind,
538 host: TrimmedNonEmptyString,
539 scope: TrimmedNonEmptyString,
540 key: TrimmedNonEmptyString,
541});
542export type ThreadIssueKey = typeof ThreadIssueKey.Type;
543
544/**
545 * An issue linked to a thread. `projectId` is the project the issue is read through, which the
546 * detail panel needs; `url` is what the agent or user handed over.
547 */
548export const ThreadIssueLink = Schema.Struct({
549 ...ThreadIssueKey.fields,
550 projectId: ProjectId,
551 url: TrimmedNonEmptyString,
552 source: ThreadIssueLinkSource,
553 linkedAt: IsoDateTime,
554 /** As the tracker named the issue when it was linked; opening it reads the live state. */
555 displayKey: TrimmedNonEmptyString,
556 title: TrimmedNonEmptyString,
557});
558export type ThreadIssueLink = typeof ThreadIssueLink.Type;
559
560export function threadIssueKeyOf(key: ThreadIssueKey): string {
561 return `${key.tracker}\u0000${key.host.trim().toLowerCase()}\u0000${key.scope.trim().toLowerCase()}\u0000${key.key.trim()}`;
562}
563
564export function threadIssueKeysEqual(left: ThreadIssueKey, right: ThreadIssueKey): boolean {
565 return threadIssueKeyOf(left) === threadIssueKeyOf(right);
566}
567
568/** The threads an issue is linked to, most recently active first. */
569export const IssueLinkedThreadsResult = Schema.Struct({
570 threads: Schema.Array(
571 Schema.Struct({
572 id: ThreadId,
573 projectId: ProjectId,
574 title: Schema.String,
575 archivedAt: Schema.NullOr(IsoDateTime),
576 settled: Schema.Boolean,
577 }),
578 ),
579});
580export type IssueLinkedThreadsResult = typeof IssueLinkedThreadsResult.Type;
581
582/**
583 * A tracker that is not a git host: it is reached with its own credential rather than a
584 * checkout's, and a project opts into it by binding one of the tracker's scopes. Everything a
585 * client needs to draw the connect flow for any such tracker without knowing which one it is.
586 */
587export const StandaloneIssueTrackerDescriptor = Schema.Struct({
588 tracker: IssueTrackerKind,
589 displayName: TrimmedNonEmptyString,
590 /** Where the tracker is served from; what `IssueRef.host` carries for its issues. */
591 host: TrimmedNonEmptyString,
592 /** What the tracker calls its container, in the singular: "team" on Linear, "project" on Jira. */
593 scopeNoun: TrimmedNonEmptyString,
594 credential: Schema.Struct({
595 /** What the tracker calls the credential: "Personal API key", "API token". */
596 label: TrimmedNonEmptyString,
597 /** Where to mint one, or null when the tracker has no stable page for it. */
598 helpUrl: Schema.NullOr(TrimmedNonEmptyString),
599 }),
600});
601export type StandaloneIssueTrackerDescriptor = typeof StandaloneIssueTrackerDescriptor.Type;
602
603export const MAX_ISSUE_TRACKER_ADDITIONAL_SCOPES = 250;
604
605/**
606 * Which standalone tracker scopes a project's issues come from, beside its git host's own.
607 * `scope` is where agents file new issues; `additionalScopes` are listed and written too.
608 */
609export const IssueTrackerProjectBinding = Schema.Struct({
610 tracker: IssueTrackerKind,
611 /** The account the scope is read with; absent for the tracker's first account. */
612 accountId: Schema.optional(IssueTrackerAccountId),
613 scope: TrimmedNonEmptyString,
614 additionalScopes: Schema.optionalKey(
615 Schema.Array(TrimmedNonEmptyString).check(
616 Schema.isMaxLength(MAX_ISSUE_TRACKER_ADDITIONAL_SCOPES),
617 ),
618 ),
619});
620export type IssueTrackerProjectBinding = typeof IssueTrackerProjectBinding.Type;
621
622export const issueTrackerBindingScopes = (binding: IssueTrackerProjectBinding) => [
623 binding.scope,
624 ...(binding.additionalScopes ?? []),
625];
626
627/** One container the connected account can read, offered when a project is bound. */
628export const IssueTrackerScope = Schema.Struct({
629 key: TrimmedNonEmptyString,
630 name: TrimmedNonEmptyString,
631});
632export type IssueTrackerScope = typeof IssueTrackerScope.Type;
633
634/**
635 * A standalone tracker as the settings page sees it: the descriptor, whether a credential is
636 * stored and still works, and the scopes it can reach. `scopes` is empty until connected.
637 */
638export const IssueTrackerConnection = Schema.Struct({
639 ...StandaloneIssueTrackerDescriptor.fields,
640 /** Which of the tracker's accounts this is; absent for its first. */
641 accountId: Schema.optional(IssueTrackerAccountId),
642 /** A credential is stored. It may still be rejected, which `account` being null reports. */
643 connected: Schema.Boolean,
644 /** Who the credential signs in as, or null when there is none or it was refused. */
645 account: Schema.NullOr(TrimmedNonEmptyString),
646 /** Why a stored credential did not work, when it did not. */
647 detail: Schema.NullOr(TrimmedNonEmptyString),
648 /** The workspace the credential reaches, as its issue URLs name it; links elsewhere are foreign. */
649 workspace: Schema.optional(TrimmedNonEmptyString),
650 scopes: Schema.Array(IssueTrackerScope),
651});
652export type IssueTrackerConnection = typeof IssueTrackerConnection.Type;
653
654export const IssueTrackerConnectionList = Schema.Struct({
655 /** Each standalone tracker's first account. */
656 trackers: Schema.Array(IssueTrackerConnection),
657 /** The accounts added beside a tracker's first, oldest first. Absent from older servers. */
658 accounts: Schema.optional(Schema.Array(IssueTrackerConnection)),
659 /**
660 * Which standalone tracker scopes each project bound with a tracker's first account reads. A
661 * project bound with an added account is in `accountBindings` instead, so older clients never
662 * read another account's team as the first account's.
663 */
664 bindings: Schema.Record(ProjectId, IssueTrackerProjectBinding),
665 /** Projects bound with an added account. Absent from older servers. */
666 accountBindings: Schema.optional(Schema.Record(ProjectId, IssueTrackerProjectBinding)),
667});
668export type IssueTrackerConnectionList = typeof IssueTrackerConnectionList.Type;
669
670/**
671 * A credential for one standalone tracker account; `null` disconnects it and unbinds its
672 * projects. `addAccount` saves the credential as a new account beside the existing ones.
673 */
674export const IssueTrackerConnectInput = Schema.Struct({
675 tracker: IssueTrackerKind,
676 accountId: Schema.optional(IssueTrackerAccountId),
677 addAccount: Schema.optional(Schema.Boolean),
678 token: Schema.NullOr(TrimmedNonEmptyString.check(Schema.isMaxLength(4_096))),
679});
680export type IssueTrackerConnectInput = typeof IssueTrackerConnectInput.Type;
681
682export const IssueTrackerBindProjectInput = Schema.Struct({
683 projectId: ProjectId,
684 /** Null unbinds. */
685 binding: Schema.NullOr(IssueTrackerProjectBinding),
686 /** On an unbind, the account the binding was made with; absent for a tracker's first. */
687 accountId: Schema.optionalKey(IssueTrackerAccountId),
688});
689export type IssueTrackerBindProjectInput = typeof IssueTrackerBindProjectInput.Type;
690
691/**
692 * A standalone tracker the connect flow could not reach or that refused the credential, or a
693 * binding that could not be saved.
694 */
695export class IssueTrackerConnectionError extends Schema.TaggedError<IssueTrackerConnectionError>()(
696 "IssueTrackerConnectionError",
697 {
698 tracker: IssueTrackerKind,
699 reason: Schema.Literals(["unknown-tracker", "rejected", "failed"]),
700 detail: TrimmedNonEmptyString,
701 cause: Schema.optional(Schema.Defect()),
702 },
703 // Not 502: Cloudflare, in front of T3 Connect, swaps an origin 502 for its own page.
704 { httpApiStatus: 503 },
705) {
706 [HttpServerRespondable.symbol]() {
707 return HttpServerResponse.schemaJson(IssueTrackerConnectionError)(this, { status: 503 });
708 }
709
710 override get message(): string {
711 return `${this.tracker} connection failed: ${this.detail}`;
712 }
713}