Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

IssueService.ts

799 lines30.3 KB

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