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

IssueService.ts

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