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