@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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