Open History to see the last commit
1// A project bound to a standalone tracker (Linear) in settings lists it beside its git host's.
2// References outside the project's own repositories (upstream and fork) may be read on the host,
3// but every write must pass through requireWritable.
4import * as Context from "effect/Context";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import {
9 IssueOperationError,
10 IssueTrackerKind,
11 IssueUnavailableError,
12 type IssueTrackerAccountId,
13 SourceControlProviderKind,
14 type IssueCandidates,
15 type IssueCommentInput,
16 type IssueCommentsPage,
17 type IssueCommentsPageInput,
18 type IssueCreateInput,
19 type IssueCreateResult,
20 type IssueDetail,
21 type IssueError,
22 type IssueListEntry,
23 type IssueListInput,
24 type IssueListProjectError,
25 type IssueListResult,
26 type IssueReactionInput,
27 type IssueRef,
28 type IssueScopeRef,
29 type IssueSetStateInput,
30 type IssueTemplateList,
31 type IssueTrackerSummary,
32 type IssueTrackerProjectBinding,
33 issueTrackerBindingScopes,
34 type IssueUpdateInput,
35 type OrchestrationProjectShell,
36 type ProjectId,
37} from "@t3tools/contracts";
38import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
39import {
40 IssueTrackerError,
41 isStandaloneIssueTracker,
42 type IssueInvolvementFilter,
43 type IssueTrackerApi,
44 type StandaloneIssueTrackerApi,
45 type TrackerIssueDetail,
46 type TrackerIssueLink,
47} from "@t3tools/source-control-core/server/IssueTracker";
48import { asIssueTrackerAccount } from "@t3tools/source-control-core/server/IssueTrackerHost";
49import { parseUrl } from "@t3tools/shared/url";
50
51import * as IssueTrackerBindings from "../persistence/IssueTrackerBindings.ts";
52import * as ProjectService from "../project/ProjectService.ts";
53import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
54import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
55import * as IssueTrackerRegistry from "./IssueTrackerRegistry.ts";
56
57const DEFAULT_LIST_LIMIT = 50;
58const SCOPE_CONCURRENCY = 4;
59
60const interactive =
61 <I, A>(call: (input: I) => Effect.Effect<A, IssueError>) =>
62 (input: I) =>
63 call(input).pipe(Effect.provideService(SourceControlRateLimit.Interactive, true));
64
65const traced =
66 <I, A>(operation: string, call: (input: I) => Effect.Effect<A, IssueError>) =>
67 (input: I) =>
68 call(input).pipe(Effect.withSpan(`IssueService.${operation}`));
69
70/** A tracker may fail with no detail; the wire errors carry a non-empty one. */
71export function trackerDetail(error: IssueTrackerError): string {
72 return error.detail.trim() || "The issue tracker request failed.";
73}
74
75/** One project's resolved tracker: which driver, where it is served from, and its container. */
76interface ProjectTrackerBinding {
77 readonly tracker: IssueTrackerKind;
78 readonly host: string;
79 readonly scope: string;
80 /** The standalone tracker account the scope is read with; null for git hosts and first accounts. */
81 readonly accountId: IssueTrackerAccountId | null;
82}
83
84/** A project the registry has a tracker for, ready to serve reads and writes. */
85interface SupportedProject extends ProjectTrackerBinding {
86 readonly project: OrchestrationProjectShell;
87 readonly api: IssueTrackerApi;
88}
89
90/**
91 * The git-host path of resolution: the tracker is the host's own, named like the remote's
92 * provider kind. A fork reads its upstream and its own repository.
93 */
94function resolveGitHostBindings(
95 project: OrchestrationProjectShell,
96): ReadonlyArray<ProjectTrackerBinding> {
97 return sourceControlDefinitions.issueBindings(project.repositoryIdentity).map((binding) => ({
98 ...binding,
99 tracker: IssueTrackerKind.make(binding.tracker),
100 accountId: null,
101 }));
102}
103
104function findStandaloneIssueUrl(trackers: ReadonlyArray<StandaloneIssueTrackerApi>, value: string) {
105 const url = parseUrl(value);
106 if (url === null) return null;
107 for (const api of trackers) {
108 const link = api.parseIssueUrl(url);
109 if (link !== null) return { api, tracker: api.kind, link };
110 }
111 return null;
112}
113
114/** Lower case, so a scope keeps its cursor whichever project's spelling is read. Clients group by the leading host. */
115function listCursorKey(project: ProjectTrackerBinding): string {
116 const scope = project.scope.toLowerCase();
117 return project.accountId === null
118 ? `${project.host} ${scope}`
119 : `${project.host} ${project.accountId}/${scope}`;
120}
121
122function viewerKey(project: ProjectTrackerBinding): string {
123 return project.accountId === null ? project.host : `${project.host} ${project.accountId}`;
124}
125
126function isTrackerUnusable(error: IssueTrackerError): boolean {
127 return error.reason === "missing-tool" || error.reason === "unauthenticated";
128}
129
130function toIssueError(operation: string): (error: IssueTrackerError) => IssueError {
131 return (error) =>
132 isTrackerUnusable(error)
133 ? new IssueUnavailableError({
134 reason: error.reason === "missing-tool" ? "tool-missing" : "unauthenticated",
135 tracker: error.tracker,
136 cause: error,
137 })
138 : new IssueOperationError({
139 operation,
140 detail: trackerDetail(error),
141 ...(error.reason === "not-found" || error.reason === "rate-limited"
142 ? { reason: error.reason }
143 : {}),
144 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
145 cause: error,
146 });
147}
148
149const isNotFound = (error: IssueError) =>
150 error._tag === "IssueOperationError" && error.reason === "not-found";
151
152const readOnly = (operation: string) =>
153 new IssueOperationError({
154 operation,
155 reason: "read-only",
156 detail:
157 "This issue belongs to a repository outside the selected project and cannot be changed from here.",
158 });
159
160const unsupported = (operation: string, what: string) =>
161 new IssueOperationError({ operation, detail: `This tracker does not support ${what}.` });
162
163export class IssueService extends Context.Service<
164 IssueService,
165 {
166 readonly list: (input: IssueListInput) => Effect.Effect<IssueListResult, IssueError>;
167 readonly detail: (input: IssueRef) => Effect.Effect<IssueDetail, IssueError>;
168 readonly linkMetadata: (input: IssueRef) => Effect.Effect<TrackerIssueLink, IssueError>;
169 readonly comments: (
170 input: IssueCommentsPageInput,
171 ) => Effect.Effect<IssueCommentsPage, IssueError>;
172 readonly templates: (input: IssueScopeRef) => Effect.Effect<IssueTemplateList, IssueError>;
173 readonly candidates: (input: IssueScopeRef) => Effect.Effect<IssueCandidates, IssueError>;
174 readonly create: (input: IssueCreateInput) => Effect.Effect<IssueCreateResult, IssueError>;
175 readonly comment: (input: IssueCommentInput) => Effect.Effect<void, IssueError>;
176 readonly update: (input: IssueUpdateInput) => Effect.Effect<void, IssueError>;
177 readonly setState: (input: IssueSetStateInput) => Effect.Effect<void, IssueError>;
178 readonly react: (input: IssueReactionInput) => Effect.Effect<void, IssueError>;
179 /**
180 * The tracker and container a project's own issues live in: the bound `scope` when named, else
181 * the one `key`'s prefix names, else the project's default.
182 */
183 readonly projectScope: (
184 projectId: ProjectId,
185 select?: { readonly key?: string | undefined; readonly scope?: string | undefined },
186 ) => Effect.Effect<IssueScopeRef & { readonly host: string }, IssueError>;
187 /**
188 * Resolve through a matching project, preferring `preferredProjectId`; other scopes are read-only.
189 * Standalone links must match the workspace in the issue's canonical URL from the connected
190 * tracker; that read comes back as `issue`, so callers need not read it again.
191 */
192 readonly resolveUrl: (
193 url: string,
194 preferredProjectId?: ProjectId,
195 ) => Effect.Effect<
196 IssueRef & {
197 readonly host: string;
198 readonly writable: boolean;
199 readonly issue?: IssueDetail;
200 },
201 IssueError
202 >;
203 }
204>()("t3/issue/IssueService") {}
205
206const make = Effect.gen(function* () {
207 const registry = yield* IssueTrackerRegistry.IssueTrackerRegistry;
208 const projects = yield* ProjectService.ProjectService;
209 const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
210 const bindings = yield* IssueTrackerBindings.IssueTrackerBindingsRepository;
211
212 const resolveStandaloneBindings = (
213 binding: IssueTrackerProjectBinding | undefined,
214 ): ReadonlyArray<ProjectTrackerBinding> => {
215 if (binding === undefined) return [];
216 const api = registry.get(binding.tracker);
217 if (api === null || !isStandaloneIssueTracker(api)) return [];
218 const host = api.standalone.host;
219 const accountId = binding.accountId ?? null;
220 return issueTrackerBindingScopes(binding).map((scope) => ({
221 tracker: binding.tracker,
222 host,
223 scope,
224 accountId,
225 }));
226 };
227
228 /**
229 * Where a project's issues live: its bound standalone tracker, its git host's, or both. The
230 * tracker bound in Settings leads, as the one the user chose for the project.
231 */
232 const resolveProjectTracker = (
233 project: OrchestrationProjectShell,
234 binding: IssueTrackerProjectBinding | undefined,
235 ) =>
236 (project.repositoryIdentity != null
237 ? Effect.succeed(project.repositoryIdentity)
238 : repositoryIdentities.resolve(project.workspaceRoot)
239 ).pipe(
240 Effect.map((repositoryIdentity) => {
241 const gitHost = resolveGitHostBindings({ ...project, repositoryIdentity });
242 return [...resolveStandaloneBindings(binding), ...gitHost];
243 }),
244 );
245
246 const listProjects = (filter: {
247 readonly projectId?: IssueListInput["projectId"];
248 readonly excludeProjectIds?: IssueListInput["excludeProjectIds"];
249 readonly host?: string | undefined;
250 /** The link's `host:port`, for a host whose binding keeps its port. */
251 readonly authority?: string | undefined;
252 }) =>
253 (filter.projectId === undefined
254 ? projects.listShells()
255 : projects.getShell(filter.projectId).pipe(Effect.map(Option.toArray))
256 ).pipe(
257 Effect.mapError(
258 (cause) =>
259 new IssueOperationError({
260 operation: "listProjects",
261 detail: "The project list could not be read.",
262 cause,
263 }),
264 ),
265 Effect.flatMap(
266 Effect.fnUntraced(function* (allShells) {
267 const shells = allShells.filter(
268 (project) => !filter.excludeProjectIds?.includes(project.id),
269 );
270 if (shells.length === 0) return [];
271 // One read per listing, not per project, and never cached so Settings changes apply.
272 const bound = yield* bindings.list(filter.projectId).pipe(
273 // A failed read is not an unbound project: that would list the git host's issues alone.
274 Effect.mapError(
275 (cause) =>
276 new IssueOperationError({
277 operation: "listProjects",
278 detail: "The project's issue tracker binding could not be read.",
279 cause,
280 }),
281 ),
282 );
283 return yield* Effect.forEach(
284 shells,
285 (project) =>
286 resolveProjectTracker(project, bound.get(project.id)).pipe(
287 Effect.map((candidates) =>
288 candidates.map((candidate) => ({ project, ...candidate })),
289 ),
290 ),
291 { concurrency: SCOPE_CONCURRENCY },
292 );
293 }),
294 ),
295 Effect.map((bound) => {
296 const host = filter.host?.trim().toLowerCase();
297 const supported: SupportedProject[] = [];
298 const unimplemented = new Map<
299 string,
300 { tracker: IssueTrackerKind; projectIds: Set<ProjectId> }
301 >();
302 for (const candidate of bound.flat()) {
303 if (host !== undefined && candidate.host !== host && candidate.host !== filter.authority)
304 continue;
305 const api = registry.get(candidate.tracker);
306 if (api === null) {
307 const counted = unimplemented.get(candidate.host);
308 if (counted === undefined)
309 unimplemented.set(candidate.host, {
310 tracker: candidate.tracker,
311 projectIds: new Set([candidate.project.id]),
312 });
313 else counted.projectIds.add(candidate.project.id);
314 continue;
315 }
316 supported.push({ ...candidate, api: asIssueTrackerAccount(api, candidate.accountId) });
317 }
318 return { supported, unimplemented };
319 }),
320 );
321
322 /**
323 * The project whose checkout and credentials serve a reference, and whether the reference is
324 * one of the project's own scopes. A reference naming another scope on the same tracker and
325 * host is served by the project but marked read-only. A project with two trackers serves the
326 * one the reference names.
327 */
328 const requireProject = (
329 ref: IssueScopeRef,
330 ): Effect.Effect<SupportedProject & { readonly writable: boolean }, IssueError> =>
331 listProjects({ projectId: ref.projectId }).pipe(
332 Effect.flatMap(({ supported }) => {
333 const host = ref.host?.trim().toLowerCase();
334 const onHost = supported.filter(
335 (candidate) =>
336 candidate.tracker === ref.tracker && (host === undefined || candidate.host === host),
337 );
338 const scope = ref.scope.trim();
339 const own = onHost.find(
340 (candidate) => candidate.scope.toLowerCase() === scope.toLowerCase(),
341 );
342 const served = own ?? onHost[0];
343 if (served === undefined) {
344 return Effect.fail(new IssueUnavailableError({ reason: "tracker-unsupported" }));
345 }
346 return Effect.succeed({ ...served, scope, writable: own !== undefined });
347 }),
348 );
349
350 const requireWritable = (ref: IssueScopeRef, operation: string) =>
351 requireProject(ref).pipe(
352 Effect.filterOrFail(
353 (project) => project.writable,
354 () => readOnly(operation),
355 ),
356 );
357
358 const list: IssueService["Service"]["list"] = Effect.fn("IssueService.list")(function* (input) {
359 // Trackers name every host so a client narrowed to one can switch to another; only the
360 // narrowed host's scopes are read.
361 const { supported, unimplemented } = yield* listProjects({
362 projectId: input.projectId,
363 excludeProjectIds: input.excludeProjectIds,
364 });
365 const host = input.host?.trim().toLowerCase();
366 const limit = input.limit ?? DEFAULT_LIST_LIMIT;
367 // Worktrees of one repository are separate projects, and every repository of an Azure
368 // DevOps project shares its work items; read each scope once.
369 const scopes = new Map<string, SupportedProject>();
370 for (const project of supported) {
371 if (host !== undefined && project.host !== host) continue;
372 const key = listCursorKey(project);
373 if (!scopes.has(key)) scopes.set(key, project);
374 }
375 const continuing = input.cursors;
376 const viewers = new Map<string, string>();
377 const trackers = new Map<string, IssueTrackerSummary>();
378 const entries: IssueListEntry[] = [];
379 const errors: IssueListProjectError[] = [];
380 const nextCursors: Record<string, string> = {};
381
382 const involvement = input.involvement ?? "all";
383 // Only a narrowed listing compares against the signed-in account; `all` never reads it.
384 const viewerRequests = new Map<string, Effect.Effect<string, IssueTrackerError>>();
385 for (const project of involvement === "all" ? [] : scopes.values()) {
386 const key = viewerKey(project);
387 if (viewerRequests.has(key)) continue;
388 const request = yield* Effect.cached(
389 project.api
390 .getViewer({ cwd: project.project.workspaceRoot, host: project.host })
391 .pipe(Effect.tap((viewer) => Effect.sync(() => viewers.set(key, viewer)))),
392 );
393 viewerRequests.set(key, request);
394 }
395
396 // Every project counts once, including worktrees of a scope read once below and forks.
397 const counted = new Set<string>();
398 for (const project of supported) {
399 const countKey = `${project.host} ${project.project.id}`;
400 if (counted.has(countKey)) continue;
401 counted.add(countKey);
402 const existing = trackers.get(project.host);
403 trackers.set(
404 project.host,
405 existing === undefined
406 ? {
407 tracker: project.tracker,
408 host: project.host,
409 projectCount: 1,
410 capabilities: project.api.capabilities,
411 configured: true,
412 detail: null,
413 }
414 : { ...existing, projectCount: existing.projectCount + 1 },
415 );
416 }
417 // Accounts of one tracker share its host: the host is unusable only when every account read
418 // failed for want of a tool or credential. Otherwise a failure stays its projects' error.
419 const hostAccounts = new Map<string, Set<string>>();
420 for (const project of scopes.values()) {
421 const accounts = hostAccounts.get(project.host) ?? new Set();
422 hostAccounts.set(project.host, accounts.add(viewerKey(project)));
423 }
424 const unusable = new Map<string, string>();
425 const usable = new Set<string>();
426 const recordFailure = (project: SupportedProject, failure: IssueTrackerError) => {
427 if (isTrackerUnusable(failure)) unusable.set(viewerKey(project), trackerDetail(failure));
428 else usable.add(project.host);
429 };
430
431 yield* Effect.forEach(
432 scopes.values(),
433 (project) =>
434 Effect.gen(function* () {
435 const key = listCursorKey(project);
436 // A continuation names the scopes it wants; one not named has nothing to add.
437 if (continuing !== undefined && continuing[key] === undefined) return;
438 const cursor = continuing?.[key];
439 const filter: Effect.Effect<IssueInvolvementFilter, IssueTrackerError> =
440 involvement === "all"
441 ? Effect.succeed({ involvement })
442 : viewerRequests
443 .get(viewerKey(project))!
444 .pipe(Effect.map((viewer) => ({ involvement, viewer })));
445 const page = yield* filter.pipe(
446 Effect.flatMap((filter) =>
447 project.api.listIssues({
448 ...filter,
449 cwd: project.project.workspaceRoot,
450 host: project.host,
451 scope: project.scope,
452 state: input.state,
453 limit,
454 query: input.query,
455 labels: input.labels,
456 assignee: input.assignee,
457 sort: input.sort ?? "updated",
458 cursor,
459 refresh: input.refresh,
460 }),
461 ),
462 Effect.result,
463 );
464 if (page._tag === "Failure") {
465 if (cursor !== undefined) nextCursors[key] = cursor;
466 recordFailure(project, page.failure);
467 // A fork or a multi-team binding reads several scopes; the failure names its own.
468 const forked = supported.some(
469 (other) => other.project.id === project.project.id && other.scope !== project.scope,
470 );
471 errors.push({
472 projectId: project.project.id,
473 projectTitle: forked
474 ? `${project.project.title} (${project.scope})`
475 : project.project.title,
476 message: trackerDetail(page.failure),
477 });
478 return;
479 }
480 usable.add(project.host);
481 for (const item of page.success.items) {
482 entries.push({
483 ...item,
484 tracker: project.tracker,
485 host: project.host,
486 scope: project.scope,
487 projectId: project.project.id,
488 projectTitle: project.project.title,
489 });
490 }
491 if (page.success.nextCursor !== null) nextCursors[key] = page.success.nextCursor;
492 }),
493 { concurrency: SCOPE_CONCURRENCY, discard: true },
494 );
495
496 for (const [host, accounts] of hostAccounts) {
497 const details = [...accounts].map((account) => unusable.get(account));
498 const existing = trackers.get(host);
499 if (existing === undefined || usable.has(host) || details.includes(undefined)) continue;
500 trackers.set(host, { ...existing, configured: false, detail: details[0] ?? null });
501 }
502 for (const [host, { tracker, projectIds }] of unimplemented) {
503 trackers.set(host, {
504 tracker,
505 host,
506 projectCount: projectIds.size,
507 capabilities: null,
508 configured: false,
509 detail: "Issues cannot be browsed for this host yet.",
510 });
511 }
512 entries.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
513 return {
514 viewers: Object.fromEntries(viewers),
515 trackers: [...trackers.values()],
516 entries,
517 errors,
518 nextCursors,
519 scopes: [...scopes.values()].map((project) => ({
520 projectId: project.project.id,
521 tracker: project.tracker,
522 host: project.host,
523 scope: project.scope,
524 })),
525 };
526 });
527
528 const toDetail = (
529 project: SupportedProject & { readonly writable: boolean },
530 issue: TrackerIssueDetail,
531 ): IssueDetail => ({
532 ...issue,
533 tracker: project.tracker,
534 host: project.host,
535 scope: project.scope,
536 projectId: project.project.id,
537 projectTitle: project.project.title,
538 writable: project.writable,
539 capabilities: project.api.capabilities,
540 });
541
542 const detail: IssueService["Service"]["detail"] = (input) =>
543 requireProject(input).pipe(
544 Effect.flatMap((project) =>
545 project.api
546 .getIssue({
547 cwd: project.project.workspaceRoot,
548 host: project.host,
549 scope: project.scope,
550 key: input.key,
551 })
552 .pipe(
553 Effect.mapError(toIssueError("detail")),
554 Effect.map((issue) => toDetail(project, issue)),
555 ),
556 ),
557 );
558
559 const linkMetadata: IssueService["Service"]["linkMetadata"] = (input) =>
560 requireProject(input).pipe(
561 Effect.flatMap((project) => {
562 const read = project.api.getIssueLink ?? project.api.getIssue;
563 return read({
564 cwd: project.project.workspaceRoot,
565 host: project.host,
566 scope: project.scope,
567 key: input.key,
568 }).pipe(
569 Effect.map(({ title, url, displayKey }) => ({ title, url, displayKey })),
570 Effect.mapError(toIssueError("detail")),
571 );
572 }),
573 );
574
575 const comments: IssueService["Service"]["comments"] = (input) =>
576 requireProject(input).pipe(
577 Effect.flatMap((project) =>
578 project.api
579 .getComments({
580 cwd: project.project.workspaceRoot,
581 host: project.host,
582 scope: project.scope,
583 key: input.key,
584 cursor: input.cursor,
585 })
586 .pipe(Effect.mapError(toIssueError("comments"))),
587 ),
588 );
589
590 const templates: IssueService["Service"]["templates"] = (input) =>
591 requireProject(input).pipe(
592 Effect.flatMap((project) =>
593 project.api.listTemplates === undefined || !project.api.capabilities.templates
594 ? Effect.fail(unsupported("templates", "issue templates"))
595 : project.api
596 .listTemplates({
597 cwd: project.project.workspaceRoot,
598 host: project.host,
599 scope: project.scope,
600 })
601 .pipe(Effect.mapError(toIssueError("templates"))),
602 ),
603 );
604
605 const candidates: IssueService["Service"]["candidates"] = (input) =>
606 requireProject(input).pipe(
607 Effect.flatMap((project) =>
608 project.api.listCandidates === undefined ||
609 !(project.api.capabilities.labels || project.api.capabilities.assignees)
610 ? Effect.fail(unsupported("candidates", "labels or assignees"))
611 : project.api
612 .listCandidates({
613 cwd: project.project.workspaceRoot,
614 host: project.host,
615 scope: project.scope,
616 })
617 .pipe(Effect.mapError(toIssueError("candidates"))),
618 ),
619 );
620
621 const create: IssueService["Service"]["create"] = (input) =>
622 requireWritable(input, "create").pipe(
623 Effect.flatMap((project) =>
624 project.api.create === undefined || !project.api.capabilities.create
625 ? Effect.fail(unsupported("create", "filing issues"))
626 : project.api
627 .create({
628 cwd: project.project.workspaceRoot,
629 host: project.host,
630 scope: project.scope,
631 title: input.title,
632 body: input.body,
633 labels: input.labels,
634 assignees: input.assignees,
635 })
636 .pipe(Effect.mapError(toIssueError("create"))),
637 ),
638 );
639
640 const comment: IssueService["Service"]["comment"] = (input) =>
641 requireWritable(input, "comment").pipe(
642 Effect.flatMap((project) => {
643 if (input.body.trim().length === 0) {
644 return Effect.fail(
645 new IssueOperationError({ operation: "comment", detail: "A comment needs some text." }),
646 );
647 }
648 return project.api.comment === undefined || !project.api.capabilities.comment
649 ? Effect.fail(unsupported("comment", "comments"))
650 : project.api
651 .comment({
652 cwd: project.project.workspaceRoot,
653 host: project.host,
654 scope: project.scope,
655 key: input.key,
656 body: input.body,
657 })
658 .pipe(Effect.mapError(toIssueError("comment")));
659 }),
660 );
661
662 const update: IssueService["Service"]["update"] = (input) =>
663 requireWritable(input, "update").pipe(
664 Effect.flatMap((project) => {
665 const { capabilities } = project.api;
666 const wantsWords = input.title !== undefined || input.body !== undefined;
667 if (!wantsWords && input.labels === undefined && input.assignees === undefined) {
668 return Effect.fail(
669 new IssueOperationError({ operation: "update", detail: "Nothing to change." }),
670 );
671 }
672 if (project.api.update === undefined) return Effect.fail(unsupported("update", "edits"));
673 if (wantsWords && !capabilities.edit)
674 return Effect.fail(unsupported("update", "editing the title or body"));
675 if (input.labels !== undefined && !capabilities.labels)
676 return Effect.fail(unsupported("update", "labels"));
677 if (input.assignees !== undefined && !capabilities.assignees)
678 return Effect.fail(unsupported("update", "assignees"));
679 return project.api
680 .update({
681 cwd: project.project.workspaceRoot,
682 host: project.host,
683 scope: project.scope,
684 key: input.key,
685 title: input.title,
686 body: input.body,
687 labels: input.labels,
688 assignees: input.assignees,
689 })
690 .pipe(Effect.mapError(toIssueError("update")));
691 }),
692 );
693
694 const setState: IssueService["Service"]["setState"] = (input) =>
695 requireWritable(input, "setState").pipe(
696 Effect.flatMap((project) => {
697 if (project.api.setState === undefined)
698 return Effect.fail(unsupported("setState", "changing an issue's state"));
699 return project.api
700 .setState({
701 cwd: project.project.workspaceRoot,
702 host: project.host,
703 scope: project.scope,
704 key: input.key,
705 state: input.state,
706 })
707 .pipe(Effect.mapError(toIssueError("setState")));
708 }),
709 );
710
711 const react: IssueService["Service"]["react"] = (input) =>
712 requireWritable(input, "react").pipe(
713 Effect.flatMap((project) =>
714 project.api.setReaction === undefined || !project.api.capabilities.reactions
715 ? Effect.fail(unsupported("react", "reactions"))
716 : project.api
717 .setReaction({
718 cwd: project.project.workspaceRoot,
719 host: project.host,
720 scope: project.scope,
721 key: input.key,
722 subjectId: input.subjectId,
723 content: input.content,
724 reacted: input.reacted,
725 })
726 .pipe(Effect.mapError(toIssueError("react"))),
727 ),
728 );
729
730 const projectScope: IssueService["Service"]["projectScope"] = Effect.fn(
731 "IssueService.projectScope",
732 )(function* (projectId, select) {
733 const { supported } = yield* listProjects({ projectId });
734 if (supported.length === 0) {
735 return yield* new IssueUnavailableError({ reason: "tracker-unsupported" });
736 }
737 const named = select?.scope?.trim().toLowerCase();
738 const prefix = select?.key?.toLowerCase();
739 const own =
740 named === undefined
741 ? (supported.find((candidate) => prefix?.startsWith(`${candidate.scope.toLowerCase()}-`)) ??
742 supported[0])
743 : supported.find((candidate) => candidate.scope.toLowerCase() === named);
744 if (own === undefined) {
745 return yield* new IssueOperationError({
746 operation: "scope",
747 reason: "not-found",
748 detail: `This project does not track ${select?.scope?.trim()}. Use one of: ${[...new Set(supported.map((candidate) => candidate.scope))].join(", ")}.`,
749 });
750 }
751 return { projectId, tracker: own.tracker, host: own.host, scope: own.scope };
752 });
753
754 /** A host whose hostname does not name it, such as GitHub Enterprise Server, is vouched for by a project on it. */
755 const parseOnProjectHost = (value: string) => {
756 const url = parseUrl(value);
757 if (url === null) return Effect.succeed(null);
758 return listProjects({ host: url.hostname, authority: url.host.toLowerCase() }).pipe(
759 Effect.map(({ supported }) => {
760 for (const project of supported) {
761 const parsed = sourceControlDefinitions.parseIssueUrl(
762 value,
763 SourceControlProviderKind.make(project.tracker),
764 );
765 if (parsed !== null) return parsed;
766 }
767 return null;
768 }),
769 );
770 };
771
772 const resolveUrl: IssueService["Service"]["resolveUrl"] = Effect.fn("IssueService.resolveUrl")(
773 function* (url, preferredProjectId) {
774 const recognized = sourceControlDefinitions.parseIssueUrl(url);
775 const standalone =
776 recognized === null ? findStandaloneIssueUrl(registry.standalone, url) : null;
777 const gitHost = recognized ?? (standalone === null ? yield* parseOnProjectHost(url) : null);
778 const parsed =
779 gitHost === null
780 ? standalone
781 : { tracker: IssueTrackerKind.make(gitHost.definition.kind), link: gitHost.link };
782 if (parsed === null) {
783 return yield* new IssueOperationError({
784 operation: "resolveUrl",
785 reason: "not-found",
786 detail: "This is not a recognised issue URL.",
787 });
788 }
789 const { tracker, link } = parsed;
790 // A link names its server's port; a binding does only when its remote or web URL did.
791 const authority = new URL(url).host.toLowerCase();
792 const { supported } = yield* listProjects({ host: link.host, authority });
793 const onHost = supported.filter((project) => project.tracker === tracker);
794 const onAuthority = onHost.filter((project) => project.host === authority);
795 const onTracker = onAuthority.length > 0 ? onAuthority : onHost;
796 const preferFirst = (projects: ReadonlyArray<SupportedProject>) =>
797 projects.find((project) => project.project.id === preferredProjectId) ?? projects[0];
798 const scope = link.scope.toLowerCase();
799 const serve = (candidates: ReadonlyArray<SupportedProject>) => {
800 const own =
801 preferFirst(candidates.filter((project) => project.scope.toLowerCase() === scope)) ??
802 preferFirst(
803 candidates.filter(
804 (project) => project.scope.toLowerCase() === gitHost?.link.scopeAlias,
805 ),
806 );
807 const lender = own ?? preferFirst(candidates);
808 if (lender === undefined) return null;
809 const served = {
810 ...lender,
811 scope: own === undefined ? link.scope : lender.scope,
812 writable: own !== undefined,
813 };
814 const resolved = {
815 projectId: lender.project.id,
816 tracker: lender.tracker,
817 host: lender.host,
818 scope: served.scope,
819 key: link.key,
820 writable: served.writable,
821 };
822 return { lender, served, resolved };
823 };
824 if (standalone === null) {
825 const found = serve(onTracker);
826 if (found === null) {
827 return yield* new IssueOperationError({
828 operation: "resolveUrl",
829 detail: `No project in T3 Code is on ${link.host}. Add any ${link.host} project to read its issues.`,
830 });
831 }
832 return found.resolved;
833 }
834 // Team keys repeat across workspaces, and each account reaches one: try the accounts in
835 // preference order, and keep the one whose canonical issue URL names the link's workspace.
836 // The exact team before a fallback, as `serve` and the client resolver pick it.
837 const exact = onTracker.filter((project) => project.scope.toLowerCase() === scope);
838 const preferred = (projects: ReadonlyArray<SupportedProject>) => [
839 ...projects.filter((project) => project.project.id === preferredProjectId),
840 ...projects,
841 ];
842 const ordered = [...preferred(exact), ...preferred(onTracker)];
843 const accounts = [...new Set(ordered.map((project) => project.accountId))];
844 if (accounts.length === 0) {
845 return yield* new IssueUnavailableError({ reason: "tracker-unsupported" });
846 }
847 let failure: IssueError | null = null;
848 for (const accountId of accounts) {
849 const found = serve(onTracker.filter((project) => project.accountId === accountId));
850 if (found === null) continue;
851 const read = yield* found.lender.api
852 .getIssue({
853 cwd: found.lender.project.workspaceRoot,
854 host: found.lender.host,
855 scope: link.scope,
856 key: link.key,
857 })
858 .pipe(Effect.mapError(toIssueError("resolveUrl")), Effect.result);
859 if (read._tag === "Failure") {
860 // Another workspace's account not having the key is a miss, not why the link failed.
861 if (failure === null || isNotFound(failure)) failure = read.failure;
862 continue;
863 }
864 const canonicalUrl = parseUrl(read.success.url);
865 const canonical = canonicalUrl === null ? null : standalone.api.parseIssueUrl(canonicalUrl);
866 if (canonical !== null && canonical.workspace === standalone.link.workspace) {
867 return { ...found.resolved, issue: toDetail(found.served, read.success) };
868 }
869 }
870 return yield* (
871 failure ??
872 new IssueOperationError({
873 operation: "resolveUrl",
874 reason: "not-found",
875 detail: "This issue URL does not belong to the connected workspace.",
876 })
877 );
878 },
879 );
880
881 return IssueService.of({
882 list,
883 detail: traced("detail", detail),
884 linkMetadata: traced("linkMetadata", linkMetadata),
885 comments: traced("comments", comments),
886 templates: traced("templates", templates),
887 candidates: interactive(traced("candidates", candidates)),
888 create: interactive(traced("create", create)),
889 comment: interactive(traced("comment", comment)),
890 update: interactive(traced("update", update)),
891 setState: interactive(traced("setState", setState)),
892 react: interactive(traced("react", react)),
893 projectScope,
894 resolveUrl,
895 });
896});
897
898export const layer = Layer.effect(IssueService, make);