Open History to see the last commit
1import {
2 IssueTrackerKind,
3 type IssueCapabilities,
4 type IssueComment,
5 type IssueEvent,
6 type IssueState,
7} from "@t3tools/contracts";
8import {
9 IssueTrackerError,
10 type IssueScopeTarget,
11 type IssueTrackerApi,
12 type TrackerIssueSummary,
13} from "@t3tools/source-control-core/server/IssueTracker";
14import * as Effect from "effect/Effect";
15import * as Schema from "effect/Schema";
16
17import { definition } from "../shared/definition.ts";
18import * as TanStackSourceApi from "./TanStackSourceApi.ts";
19import * as Hosts from "./tanStackSourceHosts.ts";
20import * as Json from "./tanStackSourceJson.ts";
21import * as Listing from "./tanStackSourceListing.ts";
22
23const KIND = IssueTrackerKind.make(definition.kind);
24
25const CAPABILITIES: IssueCapabilities = {
26 create: true,
27 edit: true,
28 comment: true,
29 labels: true,
30 assignees: true,
31 // Source documents no REST route for reactions.
32 reactions: false,
33 templates: false,
34 linkedPullRequests: true,
35 events: true,
36 search: true,
37};
38
39const OPEN: IssueState = { category: "open", name: "Open" };
40const CLOSED: IssueState = { category: "closed", name: "Closed" };
41const STATES: ReadonlyArray<IssueState> = [OPEN, CLOSED];
42
43/** Source keeps no update time; the newest timeline entry stands in where one was read. */
44const EVENT_KINDS: Readonly<Record<string, IssueEvent["kind"]>> = {
45 closed: "closed",
46 reopened: "reopened",
47 labeled: "labeled",
48 unlabeled: "unlabeled",
49 assigned: "assigned",
50 unassigned: "unassigned",
51 renamed: "renamed",
52 linked_from: "referenced",
53 referenced: "referenced",
54};
55
56const Assignee = Schema.Union([Schema.String, Schema.Struct({ username: Schema.String })]);
57const IssueRow = Schema.Struct({
58 number: Schema.Int,
59 title: Schema.String,
60 state: Schema.String,
61 author: Schema.NullOr(Schema.String),
62 labels: Schema.optional(Schema.Array(Schema.String)),
63 assignees: Schema.optional(Schema.Array(Assignee)),
64 comments: Schema.optional(Schema.Int),
65 createdAt: Schema.Finite,
66 moderation: Schema.optional(Schema.String),
67});
68type IssueRow = typeof IssueRow.Type;
69const IssueRows = Schema.Struct({
70 items: Schema.Array(IssueRow),
71 next: Schema.NullOr(Schema.String),
72});
73
74const TimelineEntry = Schema.Struct({
75 id: Schema.optional(Schema.Int),
76 comment: Schema.optional(Schema.NullOr(Schema.String)),
77 event: Schema.optional(Schema.String),
78 author: Schema.optional(Schema.NullOr(Schema.String)),
79 actor: Schema.optional(Schema.NullOr(Schema.String)),
80 at: Schema.Finite,
81 moderation: Schema.optional(Schema.String),
82});
83const IssueDetail = Schema.Struct({
84 ...IssueRow.fields,
85 kind: Schema.optional(Schema.String),
86 body: Schema.NullOr(Schema.String),
87 locked: Schema.optional(Schema.Boolean),
88 timeline: Schema.Array(TimelineEntry),
89 next: Schema.NullOr(Schema.String),
90 fixedBy: Schema.optional(
91 Schema.Array(Schema.Struct({ number: Schema.Int, title: Schema.String, state: Schema.String })),
92 ),
93});
94type IssueDetail = typeof IssueDetail.Type;
95const Created = Schema.Struct({ number: Schema.Int });
96const PAGE_LIMIT = 5;
97
98const issueUrl = (host: string, scope: string, number: number | string) =>
99 `https://${host}/@${scope}/issues/${number}`;
100const assigneeLogin = (assignee: typeof Assignee.Type) =>
101 typeof assignee === "string" ? assignee : assignee.username;
102const pullState = (state: string) =>
103 state === "merged"
104 ? ("merged" as const)
105 : state === "closed"
106 ? ("closed" as const)
107 : ("open" as const);
108
109export const make = Effect.gen(function* () {
110 const api = yield* TanStackSourceApi.TanStackSourceApi;
111
112 const failure = (operation: string, detail: string, cause?: unknown) =>
113 new IssueTrackerError({
114 tracker: KIND,
115 operation,
116 reason: "failed",
117 detail,
118 ...(cause === undefined ? {} : { cause }),
119 });
120
121 const base = (operation: string, input: IssueScopeTarget) => {
122 const repository = Hosts.tanStackSourceRepositoryPath(input.scope);
123 return Hosts.tanStackSourceHost(input.host) !== null && repository !== null
124 ? Effect.succeed(`/repos/${repository}`)
125 : Effect.fail(failure(operation, "TanStack Source issues live in owner/name repositories."));
126 };
127
128 const send = (
129 operation: string,
130 input: Pick<IssueScopeTarget, "host">,
131 request: Omit<TanStackSourceApi.TanStackSourceApiRequest, "operation" | "host">,
132 ) =>
133 api.request({ ...request, host: input.host, operation }).pipe(
134 Effect.mapError(
135 (error) =>
136 new IssueTrackerError({
137 tracker: KIND,
138 operation,
139 // A refused write is the request's, not a reason to switch the tracker off.
140 reason: error.reason === "forbidden" ? "failed" : error.reason,
141 detail: error.detail,
142 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
143 cause: error,
144 }),
145 ),
146 );
147
148 const read = <S extends Schema.Codec<unknown, unknown, never, never>>(
149 operation: string,
150 input: Pick<IssueScopeTarget, "host">,
151 request: Omit<TanStackSourceApi.TanStackSourceApiRequest, "operation" | "host">,
152 schema: S,
153 ) =>
154 send(operation, input, request).pipe(
155 Effect.flatMap((raw) =>
156 Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
157 Effect.mapError((cause) =>
158 failure(operation, "TanStack Source returned an unreadable response.", cause),
159 ),
160 ),
161 ),
162 );
163
164 const toSummary = (
165 issue: IssueRow,
166 input: IssueScopeTarget,
167 updatedAt = issue.createdAt,
168 ): TrackerIssueSummary => {
169 const created = Json.iso(issue.createdAt);
170 return {
171 key: String(issue.number),
172 displayKey: `#${issue.number}`,
173 title: issue.title.trim() || `#${issue.number}`,
174 url: issueUrl(input.host, input.scope, issue.number),
175 author: Json.toActor(issue.author, input.host),
176 state: issue.state === "closed" ? CLOSED : OPEN,
177 createdAt: created,
178 updatedAt: Json.iso(Math.max(updatedAt, issue.createdAt)),
179 // Source reports no close time.
180 closedAt: null,
181 assignees: (issue.assignees ?? []).flatMap((assignee) => {
182 const actor = Json.toActor(assigneeLogin(assignee), input.host);
183 return actor === null ? [] : [actor];
184 }),
185 labels: (issue.labels ?? []).map((name) => ({ name, color: null })),
186 commentCount: issue.comments ?? 0,
187 };
188 };
189
190 const toConversation = (detail: IssueDetail, input: IssueScopeTarget & { key: string }) => {
191 const comments: Array<IssueComment> = [];
192 const events: Array<IssueEvent> = [];
193 for (const [index, entry] of detail.timeline.entries()) {
194 if (entry.moderation !== undefined && entry.moderation !== "visible") continue;
195 if (entry.event !== undefined) {
196 const kind = EVENT_KINDS[entry.event];
197 if (kind !== undefined)
198 events.push({
199 id: `${input.key}:${entry.at}:${index}`,
200 kind,
201 actor: Json.toActor(entry.actor ?? null, input.host),
202 createdAt: Json.iso(entry.at),
203 detail: null,
204 });
205 continue;
206 }
207 if (entry.id === undefined) continue;
208 comments.push({
209 id: String(entry.id),
210 author: Json.toActor(entry.author ?? null, input.host),
211 body: entry.comment ?? "",
212 createdAt: Json.iso(entry.at),
213 url: `${issueUrl(input.host, input.scope, input.key)}#comment-${entry.id}`,
214 });
215 }
216 return { comments, events };
217 };
218
219 const readDetail = Effect.fn("TanStackSourceIssueTracker.readDetail")(function* (
220 operation: string,
221 input: IssueScopeTarget & { readonly key: string },
222 ) {
223 const path = yield* base(operation, input);
224 if (!/^\d+$/u.test(input.key))
225 return yield* failure(operation, "TanStack Source issue keys are numbers.");
226 return yield* read(operation, input, { path: `${path}/issues/${input.key}` }, IssueDetail);
227 });
228
229 const tracker: IssueTrackerApi = {
230 kind: KIND,
231 capabilities: CAPABILITIES,
232 getViewer: (input) =>
233 read("getViewer", input, { path: "/user" }, Json.SourceUser).pipe(
234 Effect.map((user) => user.username),
235 ),
236
237 listIssues: Effect.fn("TanStackSourceIssueTracker.listIssues")(function* (input) {
238 const path = yield* base("listIssues", input);
239 const query = new URLSearchParams();
240 if (input.query?.trim()) query.set("query", input.query.trim());
241 // Source narrows by one label; the rest are matched below.
242 const [label, ...moreLabels] = input.labels ?? [];
243 if (label !== undefined) query.set("label", label);
244 // An explicit assignee narrows on Source; being assigned too is checked on the rows.
245 if (input.assignee !== undefined) query.set("assignee", input.assignee);
246 else if (input.involvement === "assigned") query.set("assignee", "@me");
247 if (input.involvement === "authored") query.set("author", "@me");
248 if (input.involvement === "mentioned") query.set("mention", "@me");
249 const viewer = input.involvement === "all" ? null : input.viewer.toLowerCase();
250 const listing = yield* Listing.readMerged({
251 states: input.state === "all" ? ["open", "closed"] : [input.state],
252 cursor: input.cursor,
253 limit: Math.max(1, input.limit),
254 maxPages: PAGE_LIMIT,
255 readPage: (state, page) => {
256 const params = new URLSearchParams(query);
257 params.set("state", state);
258 if (page !== null) params.set("cursor", page);
259 return read("listIssues", input, { path: `${path}/issues?${params}` }, IssueRows);
260 },
261 keep: (issue) =>
262 (issue.moderation === undefined || issue.moderation === "visible") &&
263 moreLabels.every((name) => issue.labels?.includes(name) === true) &&
264 (input.involvement !== "assigned" ||
265 input.assignee === undefined ||
266 (issue.assignees ?? []).some(
267 (assignee) => assigneeLogin(assignee).toLowerCase() === viewer,
268 )),
269 });
270 return {
271 items: listing.items.map((issue) => toSummary(issue, input)),
272 nextCursor: listing.next,
273 };
274 }),
275
276 getIssue: Effect.fn("TanStackSourceIssueTracker.getIssue")(function* (input) {
277 const [detail, viewer] = yield* Effect.all(
278 [
279 readDetail("getIssue", input),
280 tracker.getViewer(input).pipe(Effect.orElseSucceed(() => null)),
281 ],
282 { concurrency: 2 },
283 );
284 if (detail.kind === "pull")
285 return yield* failure("getIssue", `#${input.key} is a pull request, not an issue.`);
286 const { comments, events } = toConversation(detail, input);
287 const latest = detail.timeline.reduce((newest, entry) => Math.max(newest, entry.at), 0);
288 return {
289 ...toSummary(detail, input, latest),
290 commentCount: detail.comments ?? comments.length,
291 body: detail.body ?? "",
292 viewer,
293 viewerPermissions: {
294 setState: viewer !== null,
295 comment: viewer !== null && detail.locked !== true,
296 edit: viewer !== null,
297 labels: viewer !== null,
298 assignees: viewer !== null,
299 },
300 states: STATES,
301 comments,
302 commentsCursor: detail.next,
303 events,
304 linkedPullRequests: (detail.fixedBy ?? []).map((pull) => ({
305 repository: input.scope,
306 number: pull.number,
307 title: pull.title.trim() || `#${pull.number}`,
308 url: Json.pullUrl(input.host, input.scope, pull.number),
309 state: pullState(pull.state),
310 isDraft: false,
311 closesIssue: true,
312 })),
313 };
314 }),
315
316 getComments: Effect.fn("TanStackSourceIssueTracker.getComments")(function* (input) {
317 const path = yield* base("getComments", input);
318 const detail = yield* read(
319 "getComments",
320 input,
321 {
322 path: `${path}/issues/${input.key}?${new URLSearchParams({ cursor: input.cursor })}`,
323 },
324 IssueDetail,
325 );
326 return { comments: toConversation(detail, input).comments, nextCursor: detail.next };
327 }),
328
329 create: Effect.fn("TanStackSourceIssueTracker.create")(function* (input) {
330 const path = yield* base("create", input);
331 const created = yield* read(
332 "create",
333 input,
334 {
335 method: "POST",
336 path: `${path}/issues`,
337 body: {
338 title: input.title,
339 ...(input.body.trim() === "" ? {} : { body: input.body }),
340 },
341 },
342 Created,
343 );
344 const key = String(created.number);
345 // Source takes labels and assignees on their own routes.
346 if (input.labels.length > 0)
347 yield* send("create", input, {
348 method: "PUT",
349 path: `${path}/issues/${key}/labels`,
350 body: { labels: input.labels },
351 });
352 if (input.assignees.length > 0)
353 yield* send("create", input, {
354 method: "PUT",
355 path: `${path}/issues/${key}/assignees`,
356 body: { assignees: input.assignees },
357 });
358 return { key, displayKey: `#${key}`, url: issueUrl(input.host, input.scope, key) };
359 }),
360
361 comment: Effect.fn("TanStackSourceIssueTracker.comment")(function* (input) {
362 const path = yield* base("comment", input);
363 yield* send("comment", input, {
364 method: "POST",
365 path: `${path}/issues/${input.key}/comments`,
366 body: { body: input.body },
367 });
368 }),
369
370 update: Effect.fn("TanStackSourceIssueTracker.update")(function* (input) {
371 const path = `${yield* base("update", input)}/issues/${input.key}`;
372 if (input.title !== undefined || input.body !== undefined)
373 yield* send("update", input, {
374 method: "PATCH",
375 path,
376 body: {
377 ...(input.title === undefined ? {} : { title: input.title }),
378 ...(input.body === undefined ? {} : { body: input.body }),
379 },
380 });
381 if (input.labels !== undefined)
382 yield* send("update", input, {
383 method: "PUT",
384 path: `${path}/labels`,
385 body: { labels: input.labels },
386 });
387 if (input.assignees !== undefined)
388 yield* send("update", input, {
389 method: "PUT",
390 path: `${path}/assignees`,
391 body: { assignees: input.assignees },
392 });
393 }),
394
395 setState: Effect.fn("TanStackSourceIssueTracker.setState")(function* (input) {
396 const state = STATES.find((candidate) => candidate.name === input.state);
397 if (state === undefined)
398 return yield* failure("setState", `TanStack Source issues have no "${input.state}" state.`);
399 const path = yield* base("setState", input);
400 yield* send("setState", input, {
401 method: "PATCH",
402 path: `${path}/issues/${input.key}`,
403 body: { state: state.category },
404 });
405 }),
406
407 listCandidates: Effect.fn("TanStackSourceIssueTracker.listCandidates")(function* (input) {
408 const path = yield* base("listCandidates", input);
409 const [labels, viewer] = yield* Effect.all(
410 [
411 read("listCandidates", input, { path: `${path}/labels` }, Json.SourceLabels),
412 tracker.getViewer(input).pipe(Effect.orElseSucceed(() => null)),
413 ],
414 { concurrency: 2 },
415 );
416 const self = Json.toActor(viewer, input.host);
417 return {
418 labels: labels.map((label) => ({
419 name: label.name,
420 color: label.color,
421 description: label.description ?? null,
422 })),
423 // Source lists no collaborators, so only the viewer is offered.
424 assignees: self === null ? [] : [{ ...self, id: self.login }],
425 truncated: true,
426 };
427 }),
428 };
429 return tracker;
430});