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