diff --git a/apps/mobile/src/features/issues/IssueRouteScreen.tsx b/apps/mobile/src/features/issues/IssueRouteScreen.tsx index 874ecfba20b6d..d7db0b665206d 100644 --- a/apps/mobile/src/features/issues/IssueRouteScreen.tsx +++ b/apps/mobile/src/features/issues/IssueRouteScreen.tsx @@ -1,7 +1,9 @@ import { RegistryContext, useAtomValue } from "@effect/atom-react"; import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native"; -import { issueEventSentence } from "@t3tools/client-runtime/issue-presentation"; -import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; +import { + issueEventSentence, + issueLinksOpenInApp, +} from "@t3tools/client-runtime/issue-presentation"; import { createIssueCommentPager } from "@t3tools/client-runtime/state/issues"; import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads"; import type { @@ -249,8 +251,7 @@ function LinkedPullRequests(props: { }) { const gt = useGT(); const navigation = useNavigation(); - // Only a git host's tracker shares its host with the change request it links. - const sameHost = sourceControlClients.find(props.params.tracker) !== undefined; + const sameHost = issueLinksOpenInApp(props.params.tracker); return ( diff --git a/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx b/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx index 43d5af0363558..e52a237b5693b 100644 --- a/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx +++ b/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx @@ -1,4 +1,7 @@ -import { issueTrackerSummary } from "@t3tools/client-runtime/state/issue-trackers"; +import { + issueTrackerFieldsToken, + issueTrackerSummary, +} from "@t3tools/client-runtime/state/issue-trackers"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId, @@ -23,6 +26,7 @@ import { useProjects } from "../../../state/entities"; import { issueTrackerEnvironment } from "../../../state/issueTrackers"; import { useEnvironmentQuery } from "../../../state/query"; import { useAtomCommand } from "../../../state/use-atom-command"; +import { ConnectionFormField } from "../../connection/ConnectionFormField"; import type { SettingsTarget } from "../settings-environment-filter"; import { SettingsProviderRow } from "./SettingsProviderRow"; import { SettingsRow } from "./SettingsRow"; @@ -33,9 +37,25 @@ const ThemedSvg = withUniwind(Svg); const ICON_SIZE = Platform.OS === "android" ? 20 : 18; /** Art per tracker kind; the server supplies everything else about a tracker. */ -const TRACKER_MARKS: Partial> = { - linear: - "M1.225 61.523c-.222-.949.908-1.546 1.597-.857l36.512 36.512c.69.69.092 1.82-.857 1.597C20.15 94.612 5.388 79.85 1.225 61.523ZM.002 46.889a.99.99 0 0 0 .29.76l52.062 52.061a.99.99 0 0 0 .76.29c2.765-.169 5.47-.559 8.1-1.152.75-.169 1.014-1.084.47-1.63L2.784 38.32c-.545-.545-1.46-.28-1.63.47A50.229 50.229 0 0 0 .002 46.89ZM4.472 29.34a.99.99 0 0 0 .208 1.104l64.878 64.877a.99.99 0 0 0 1.104.208 50.293 50.293 0 0 0 5.807-3.132.99.99 0 0 0 .154-1.53L9.135 23.38a.99.99 0 0 0-1.53.154 50.29 50.29 0 0 0-3.132 5.807ZM12.293 18.229c-.309-.309-.334-.803-.045-1.13C21.376 6.626 34.637 0 49.45 0 76.869 0 99.1 22.231 99.1 49.65c0 14.813-6.626 28.074-17.099 37.202-.327.29-.821.264-1.13-.045L12.293 18.23Z", +const TRACKER_MARKS: Partial< + Record +> = { + // Tabler's `brand-jira` mark (MIT). + jira: { + viewBox: "0 0 24 24", + stroke: true, + paths: [ + "M20 4h-9v1.5a2.5 2.5 0 0 0 2.5 2.5h1.5a1 1 0 0 1 1 1v1.5a2.5 2.5 0 0 0 2.5 2.5h1.5v-9", + "M15 8h-8v1.5a2.5 2.5 0 0 0 2.5 2.5h1.5a1 1 0 0 1 1 1v1.5a2.5 2.5 0 0 0 2.5 2.5h1.5v-8a1 1 0 0 0 -1 -1", + "M11 12h-8v1.5a2.5 2.5 0 0 0 2.5 2.5h1.5a1 1 0 0 1 1 1v1.5a2.5 2.5 0 0 0 2.5 2.5h1.5v-8a1 1 0 0 0 -1 -1", + ], + }, + linear: { + viewBox: "0 0 100 100", + paths: [ + "M1.225 61.523c-.222-.949.908-1.546 1.597-.857l36.512 36.512c.69.69.092 1.82-.857 1.597C20.15 94.612 5.388 79.85 1.225 61.523ZM.002 46.889a.99.99 0 0 0 .29.76l52.062 52.061a.99.99 0 0 0 .76.29c2.765-.169 5.47-.559 8.1-1.152.75-.169 1.014-1.084.47-1.63L2.784 38.32c-.545-.545-1.46-.28-1.63.47A50.229 50.229 0 0 0 .002 46.89ZM4.472 29.34a.99.99 0 0 0 .208 1.104l64.878 64.877a.99.99 0 0 0 1.104.208 50.293 50.293 0 0 0 5.807-3.132.99.99 0 0 0 .154-1.53L9.135 23.38a.99.99 0 0 0-1.53.154 50.29 50.29 0 0 0-3.132 5.807ZM12.293 18.229c-.309-.309-.334-.803-.045-1.13C21.376 6.626 34.637 0 49.45 0 76.869 0 99.1 22.231 99.1 49.65c0 14.813-6.626 28.074-17.099 37.202-.327.29-.821.264-1.13-.045L12.293 18.23Z", + ], + }, }; /** @@ -112,10 +132,24 @@ export function IssueTrackerMark(props: { readonly tracker: string }) { - + {mark.paths.map((d) => + mark.stroke ? ( + + ) : ( + + ), + )} ) : ( @@ -131,7 +165,7 @@ export function IssueTrackerCredentialForm(props: { const gt = useGT(); const { environmentId, tracker } = props; const connect = useAtomCommand(issueTrackerEnvironment.connect, { reportFailure: false }); - const [draft, setDraft] = useState(""); + const [drafts, setDrafts] = useState>>({}); const [busy, setBusy] = useState(false); const [failure, setFailure] = useState(null); const submit = async (token: string | null) => { @@ -140,7 +174,7 @@ export function IssueTrackerCredentialForm(props: { const result = await connect({ environmentId, input: { tracker: tracker.tracker, token } }); setBusy(false); if (!AsyncResult.isFailure(result)) { - setDraft(""); + setDrafts({}); return; } const error = squashAtomCommandFailure(result); @@ -148,22 +182,53 @@ export function IssueTrackerCredentialForm(props: { }; const helpUrl = tracker.credential.helpUrl; const locked = props.disabled || busy; + // A single-part credential is the one secret field, keyed by nothing. + const fields = tracker.credential.fields ?? [ + { key: "", label: tracker.credential.label, secret: true }, + ]; + const token = tracker.credential.fields + ? issueTrackerFieldsToken(tracker.credential.fields, drafts) + : drafts[""]?.trim() || null; + const send = () => { + if (token !== null) void submit(token); + }; return ( - { - if (value.trim()) void submit(value.trim()); - }} - editable={!locked} - /> + {fields.map((field) => + field.secret ? ( + + {tracker.credential.fields ? ( + + {field.label} + + ) : null} + setDrafts({ ...drafts, [field.key]: value })} + onSubmitEditing={send} + editable={!locked} + /> + + ) : ( + setDrafts({ ...drafts, [field.key]: value })} + onSubmitEditing={send} + editable={!locked} + /> + ), + )} {failure ? ( {failure} @@ -196,8 +261,8 @@ export function IssueTrackerCredentialForm(props: { tone="primary" size="compact" loading={busy} - disabled={locked || !draft.trim()} - onPress={() => void submit(draft.trim())} + disabled={locked || token === null} + onPress={send} /> diff --git a/apps/server/package.json b/apps/server/package.json index bea918f407870..91b9c9e2e8abc 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -43,6 +43,7 @@ "@ff-labs/fff-node": "0.11.0", "@muse-code/sdk": "1.4.6", "@napi-rs/keyring": "^1.3.0", + "@t3tools/issue-tracker-jira": "workspace:*", "@t3tools/issue-tracker-linear": "workspace:*", "@t3tools/provider-acp": "workspace:*", "@t3tools/provider-acp-registry": "workspace:*", diff --git a/apps/server/src/issue/IssueTrackerRegistry.ts b/apps/server/src/issue/IssueTrackerRegistry.ts index 6f2343e990479..04265c6989d2f 100644 --- a/apps/server/src/issue/IssueTrackerRegistry.ts +++ b/apps/server/src/issue/IssueTrackerRegistry.ts @@ -2,6 +2,7 @@ import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import type { IssueTrackerKind } from "@t3tools/contracts"; +import * as JiraDriver from "@t3tools/issue-tracker-jira/server/driver"; import * as LinearDriver from "@t3tools/issue-tracker-linear/server/driver"; import { isStandaloneIssueTracker, @@ -36,7 +37,7 @@ export function fromTrackers( } /** Trackers that are not a git host's own. Each signs requests with a credential from Settings. */ -const STANDALONE_TRACKERS = [LinearDriver.make]; +const STANDALONE_TRACKERS = [LinearDriver.make, JiraDriver.make]; const make = Effect.gen(function* () { const drivers = yield* BuiltInDrivers.SourceControlDrivers; diff --git a/apps/web/src/components/Icons.tsx b/apps/web/src/components/Icons.tsx index 080618e5c66bd..4c24d2cb16c4e 100644 --- a/apps/web/src/components/Icons.tsx +++ b/apps/web/src/components/Icons.tsx @@ -131,6 +131,23 @@ export const LinearIcon: Icon = (props) => ( ); +/** Tabler's `brand-jira` mark (MIT). */ +export const JiraIcon: Icon = (props) => ( + + + + + +); + export const CursorIcon: Icon = ({ className, ...props }) => ( onSelectPullRequest({ projectId: reference.projectId, diff --git a/apps/web/src/components/issue/issuePresentation.tsx b/apps/web/src/components/issue/issuePresentation.tsx index a8a02f41f5a47..fa77a21c80310 100644 --- a/apps/web/src/components/issue/issuePresentation.tsx +++ b/apps/web/src/components/issue/issuePresentation.tsx @@ -3,7 +3,7 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-cli import { CircleCheckIcon, CircleDotIcon, CircleSlashIcon, TicketIcon } from "lucide-react"; import { cn } from "~/lib/utils"; -import { LinearIcon, type Icon } from "~/components/Icons"; +import { JiraIcon, LinearIcon, type Icon } from "~/components/Icons"; import { getSourceControlPresentationForKind } from "~/sourceControlPresentation"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -13,6 +13,7 @@ export const IssueGlyph = { issue: CircleDotIcon } as const; /** Name and mark per standalone tracker kind; one missing here falls back to its kind and a ticket. */ const STANDALONE_TRACKERS: Partial> = { + jira: { providerName: "Jira", Icon: JiraIcon }, linear: { providerName: "Linear", Icon: LinearIcon }, }; diff --git a/apps/web/src/components/settings/IssueTrackerSettings.tsx b/apps/web/src/components/settings/IssueTrackerSettings.tsx index a397a84439f7a..7d374c4801df8 100644 --- a/apps/web/src/components/settings/IssueTrackerSettings.tsx +++ b/apps/web/src/components/settings/IssueTrackerSettings.tsx @@ -1,9 +1,12 @@ import { useAtomValue } from "@effect/atom-react"; -import { issueTrackerSummary } from "@t3tools/client-runtime/state/issue-trackers"; +import { + issueTrackerFieldsToken, + issueTrackerSummary, +} from "@t3tools/client-runtime/state/issue-trackers"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { T, useGT, useMessages } from "gt-react"; import { ChevronDownIcon, ExternalLinkIcon, XIcon } from "lucide-react"; -import { useState, type ElementType } from "react"; +import { useState, type ElementType, type ReactNode } from "react"; import type { EnvironmentId, IssueTrackerConnection, @@ -15,12 +18,13 @@ import { useEnvironmentQuery } from "../../state/query"; import { issueTrackerEnvironment } from "../../state/issueTrackers"; import { useProjects } from "../../state/entities"; import { useAtomCommand } from "../../state/use-atom-command"; -import { LinearIcon } from "../Icons"; +import { JiraIcon, LinearIcon } from "../Icons"; import { cn } from "~/lib/utils"; import { Badge } from "../ui/badge"; import { Button, InlineButton } from "../ui/button"; import { Collapsible, CollapsibleContent } from "../ui/collapsible"; +import { Input } from "../ui/input"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; import { Skeleton } from "../ui/skeleton"; import { SecretInput } from "./SecretInput"; @@ -31,6 +35,7 @@ type TrackerIcon = ElementType<{ className?: string }>; /** Web art per tracker kind; the server supplies everything else about a tracker. */ const TRACKER_ICONS: Partial> = { + jira: JiraIcon, linear: LinearIcon, }; @@ -118,15 +123,47 @@ function TrackerRow({ input: { tracker: tracker.tracker, token }, }); setBusy(false); - if (result._tag === "Success") return; + if (result._tag === "Success") return true; const error = squashAtomCommandFailure(result); setFailure(error instanceof Error ? error.message : gt("The request failed.")); + return false; }; const inputId = `issue-tracker-${tracker.tracker}-${environmentId}`; const usable = tracker.connected && tracker.account !== null; const summary = issueTrackerSummary(tracker, bindings, messages); + const description = ( + <> + Stored on the server. + {tracker.credential.helpUrl ? ( + <> + {" "} + + } + > + Create one + + + > + ) : null} + {failure ? {failure} : null} + > + ); + const disconnect = tracker.connected ? ( + void submit(null)} + aria-label={gt("Disconnect {tracker}", { tracker: tracker.displayName })} + > + + + ) : null; + return ( @@ -170,57 +207,36 @@ function TrackerRow({ {/* Locked while saving, so an edit made mid-request is not overwritten by the saved value. */} - {tracker.credential.label}} - description={ - <> - Stored on the server. - {tracker.credential.helpUrl ? ( - <> - {" "} - - } - > - Create one - - - > - ) : null} - {failure ? {failure} : null} - > - } - control={ - - { - if (next.trim()) void submit(next.trim()); - }} - /> - {tracker.connected ? ( - void submit(null)} - aria-label={gt("Disconnect {tracker}", { tracker: tracker.displayName })} - > - - - ) : null} - - } - /> + {tracker.credential.fields ? ( + + ) : ( + {tracker.credential.label}} + description={description} + control={ + + { + if (next.trim()) void submit(next.trim()); + }} + /> + {disconnect} + + } + /> + )} {usable ? ( ; + readonly connected: boolean; + readonly description: ReactNode; + readonly disconnect: ReactNode; + readonly onSubmit: (token: string) => Promise; +}) { + const gt = useGT(); + const [drafts, setDrafts] = useState>>({}); + // The last credential sent, so moving between fields does not resend one that just failed. + // Enter always sends, so a failed attempt can be retried as it is. + const [sent, setSent] = useState(null); + const token = issueTrackerFieldsToken(fields, drafts); + const send = (retry: boolean) => { + if (token === null || (!retry && token === sent)) return; + setSent(token); + void onSubmit(token).then((connected) => { + if (!connected) return; + setDrafts({}); + setSent(null); + }); + }; + return fields.map((field) => { + const id = `${idPrefix}-${field.key}`; + return ( + {field.label}} + description={field.secret ? description : undefined} + control={ + + setDrafts({ ...drafts, [field.key]: event.target.value })} + onBlur={() => send(false)} + onKeyDown={(event) => { + if (event.key === "Enter" && !event.nativeEvent.isComposing) send(true); + }} + /> + {field.secret ? disconnect : null} + + } + /> + ); + }); +} + /** One picker per project of this environment: which of the tracker's scopes it reads, if any. */ function ProjectBindings({ environmentId, diff --git a/docs/user/source-control.md b/docs/user/source-control.md index ce57f727ff6ae..b456840af3fe0 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -374,8 +374,15 @@ itself where it can search. Press **Load more** at the end of a group to read fu The **Views** menu saves and restores a search, filter, and sort setup, as it does for pull requests. -To list a Linear team's issues beside a project's, connect Linear with an API key under -Settings → Source control & issues, then choose the team for that project there. +To list a Linear team's or a Jira Cloud project's issues beside a project's, connect the tracker +under Settings → Source control & issues, then choose the team or project for that project there. +Linear takes an API key. Jira takes your site (`example.atlassian.net`), your account email and an +[API token](https://id.atlassian.com/manage-profile/security/api-tokens) created with **Create API +token**, not a token with scopes. Jira issues move between statuses through your workflow's +transitions. For Jira, "mentioning you" lists the issues you watch. A Jira description with +attachments, mentions or other Jira-only content is edited in Jira. Jira's linked pull requests come +from the tools connected to its Development panel. Linear's and Jira's linked pull requests open in +the browser. Jira reactions are not shown, because Jira Cloud has no API for them. Select an issue to open it beside the list: description, comments, state changes, linked pull requests, labels, assignees, and reactions. Linked pull requests open in the same panel. You can diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index c09deef7e4b39..3399f304a67f4 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -635,6 +635,7 @@ "dependencies": { "@pierre/diffs": "catalog:", "@t3tools/contracts": "workspace:*", + "@t3tools/issue-tracker-jira": "workspace:*", "@t3tools/issue-tracker-linear": "workspace:*", "@t3tools/provider-acp-registry": "workspace:*", "@t3tools/provider-core": "workspace:*", diff --git a/packages/client-runtime/src/issueLinks.test.ts b/packages/client-runtime/src/issueLinks.test.ts index fd206063bfcff..37d32d0ed4d5c 100644 --- a/packages/client-runtime/src/issueLinks.test.ts +++ b/packages/client-runtime/src/issueLinks.test.ts @@ -6,7 +6,7 @@ import { } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { resolveIssueLinkTarget } from "./issueLinks.ts"; +import { mayContainStandaloneIssueLink, resolveIssueLinkTarget } from "./issueLinks.ts"; const project = (id: string, repository: string) => ({ @@ -112,6 +112,41 @@ describe("resolveIssueLinkTarget", () => { ).toBeNull(); }); + it("reads a Jira link only on the connected site", () => { + const trackers = { + trackers: [ + { + tracker: IssueTrackerKind.make("jira"), + displayName: "Jira", + host: "atlassian.net", + scopeNoun: "project", + credential: { label: "API token", helpUrl: null }, + connected: true, + account: "Julius", + detail: null, + workspace: "acme", + scopes: [], + }, + ], + bindings: { + [ProjectId.make("p1")]: { tracker: IssueTrackerKind.make("jira"), scope: "ENG" }, + }, + }; + const resolve = (url: string) => resolveIssueLinkTarget({ url, projects, trackers }); + expect(resolve("https://acme.atlassian.net/browse/ENG-4")?.ref).toEqual({ + projectId: "p1", + tracker: "jira", + host: "atlassian.net", + scope: "ENG", + key: "ENG-4", + }); + const upper = "See https://ACME.ATLASSIAN.NET/browse/ENG-4"; + expect(mayContainStandaloneIssueLink(upper)).toBe(true); + expect(resolve(upper.slice(4))?.ref.key).toBe("ENG-4"); + // Project keys repeat across sites; only the connected one's links are its issues. + expect(resolve("https://othercorp.atlassian.net/browse/ENG-4")).toBeNull(); + }); + it.each([ "https://github.com.evil.example/acme/web/issues/7", "https://github.com/acme/web/pull/7", diff --git a/packages/client-runtime/src/issueLinks.ts b/packages/client-runtime/src/issueLinks.ts index 4e1d4ec15a543..98affacf94cc5 100644 --- a/packages/client-runtime/src/issueLinks.ts +++ b/packages/client-runtime/src/issueLinks.ts @@ -1,4 +1,9 @@ import type { IssueRef, IssueTrackerConnectionList } from "@t3tools/contracts"; +import { + JIRA_HOST, + JIRA_KIND, + parseJiraIssueUrl, +} from "@t3tools/issue-tracker-jira/shared/issueUrl"; import { LINEAR_HOST, LINEAR_KIND, @@ -53,10 +58,19 @@ function parseIssueLink( return null; } +const STANDALONE_TRACKERS = [ + { tracker: LINEAR_KIND, parse: parseLinearIssueUrl }, + { tracker: JIRA_KIND, parse: parseJiraIssueUrl }, +]; + function parseStandaloneIssueLink(url: string) { try { - const link = parseLinearIssueUrl(new URL(url)); - return link === null ? null : { tracker: LINEAR_KIND, link }; + const parsed = new URL(url); + for (const { tracker, parse } of STANDALONE_TRACKERS) { + const link = parse(parsed); + if (link !== null) return { tracker, link }; + } + return null; } catch { return null; } @@ -69,7 +83,8 @@ export function isStandaloneIssueLink(url: string): boolean { /** A cheap pre-check, so text without such a link never asks for the bindings. */ export function mayContainStandaloneIssueLink(text: string): boolean { - return text.includes(`${LINEAR_HOST}/`); + const lower = text.toLowerCase(); + return lower.includes(`${LINEAR_HOST}/`) || lower.includes(`.${JIRA_HOST}/`); } /** diff --git a/packages/client-runtime/src/issuePresentation.test.ts b/packages/client-runtime/src/issuePresentation.test.ts index a3a7e981e9052..592aa3cc6b9bf 100644 --- a/packages/client-runtime/src/issuePresentation.test.ts +++ b/packages/client-runtime/src/issuePresentation.test.ts @@ -1,7 +1,7 @@ import type { IssueDetail, IssueState } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { issueWriteAccess } from "./issuePresentation.ts"; +import { issueLinksOpenInApp, issueWriteAccess } from "./issuePresentation.ts"; const workflow: ReadonlyArray = [ { category: "open", name: "Backlog" }, @@ -40,3 +40,9 @@ describe("issueWriteAccess", () => { expect(issueWriteAccess(issue({ states: [] }), true).states).toEqual([]); }); }); + +it("opens linked pull requests in the app only for a git host's own tracker", () => { + expect(issueLinksOpenInApp("github")).toBe(true); + expect(issueLinksOpenInApp("jira")).toBe(false); + expect(issueLinksOpenInApp("linear")).toBe(false); +}); diff --git a/packages/client-runtime/src/issuePresentation.ts b/packages/client-runtime/src/issuePresentation.ts index 001e585035ea1..ea945804922a0 100644 --- a/packages/client-runtime/src/issuePresentation.ts +++ b/packages/client-runtime/src/issuePresentation.ts @@ -2,6 +2,8 @@ import type { IssueDetail, IssueEvent } from "@t3tools/contracts"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; +import { sourceControlClients } from "./sourceControlClients.ts"; + /** "completed" → "Completed"; a reason the tracker spells with a dash reads as words. */ function issueCloseReasonLabel(reason: string): string { const words = reason.replace(/[-_]+/g, " ").trim(); @@ -80,3 +82,11 @@ export function issueWriteAccess( : [], }; } + +/** + * Whether a tracker's linked pull requests open in the app: only a git host's own tracker shares + * its host with them. A standalone tracker's links (Linear, Jira) open in the browser. + */ +export function issueLinksOpenInApp(tracker: string): boolean { + return sourceControlClients.find(tracker) !== undefined; +} diff --git a/packages/client-runtime/src/state/issueTrackers.ts b/packages/client-runtime/src/state/issueTrackers.ts index 045f283f310ee..5bf76eec7a621 100644 --- a/packages/client-runtime/src/state/issueTrackers.ts +++ b/packages/client-runtime/src/state/issueTrackers.ts @@ -59,6 +59,20 @@ export function createIssueTrackerEnvironmentAtoms( }; } +/** + * A credential of several parts as the one token a connect sends: a JSON object of every part, + * or null until each is filled, so a half-entered credential is never sent. + */ +export function issueTrackerFieldsToken( + fields: NonNullable, + drafts: Readonly>, +): string | null { + const values = fields.map((field) => [field.key, drafts[field.key]?.trim() ?? ""] as const); + return values.every(([, value]) => value !== "") + ? JSON.stringify(Object.fromEntries(values)) + : null; +} + // Tracker packages name their credential and scope in English, so a sentence is translated only // when it matches a known tracker's whole sentence; any other tracker keeps the English one. function knownTrackerSentence( diff --git a/packages/contracts/src/issue.ts b/packages/contracts/src/issue.ts index 07f2eab6e6a42..6bb65df4634ed 100644 --- a/packages/contracts/src/issue.ts +++ b/packages/contracts/src/issue.ts @@ -562,6 +562,20 @@ export const StandaloneIssueTrackerDescriptor = Schema.Struct({ label: TrimmedNonEmptyString, /** Where to mint one, or null when the tracker has no stable page for it. */ helpUrl: Schema.NullOr(TrimmedNonEmptyString), + /** + * A credential of several parts, such as a site, an email and a token. Clients ask for each + * and send them as one JSON object keyed by `key` in place of a single token. + */ + fields: Schema.optional( + Schema.Array( + Schema.Struct({ + key: TrimmedNonEmptyString, + label: TrimmedNonEmptyString, + placeholder: Schema.optional(TrimmedNonEmptyString), + secret: Schema.Boolean, + }), + ), + ), }), }); export type StandaloneIssueTrackerDescriptor = typeof StandaloneIssueTrackerDescriptor.Type; diff --git a/packages/issue-tracker-jira/package.json b/packages/issue-tracker-jira/package.json new file mode 100644 index 0000000000000..f775c0dcb5b56 --- /dev/null +++ b/packages/issue-tracker-jira/package.json @@ -0,0 +1,33 @@ +{ + "name": "@t3tools/issue-tracker-jira", + "private": true, + "type": "module", + "exports": { + "./shared/issueUrl": { + "types": "./src/shared/issueUrl.ts", + "import": "./src/shared/issueUrl.ts" + }, + "./server/driver": { + "types": "./src/server/driver.ts", + "import": "./src/server/driver.ts" + } + }, + "scripts": { + "typecheck": "effect-tsgo tsrs --noEmit", + "test": "vp test run --config ../../vite.config.ts --dir ." + }, + "dependencies": { + "@t3tools/contracts": "workspace:*", + "@t3tools/source-control-core": "workspace:*", + "effect": "catalog:", + "mdast-util-from-markdown": "2.0.3", + "mdast-util-gfm": "3.1.0", + "micromark-extension-gfm": "3.0.0" + }, + "devDependencies": { + "@effect/vitest": "catalog:", + "@types/mdast": "^4.0.4", + "@types/node": "catalog:", + "vite-plus": "catalog:" + } +} diff --git a/packages/issue-tracker-jira/src/server/JiraApi.ts b/packages/issue-tracker-jira/src/server/JiraApi.ts new file mode 100644 index 0000000000000..2e6a02bd3deb8 --- /dev/null +++ b/packages/issue-tracker-jira/src/server/JiraApi.ts @@ -0,0 +1,620 @@ +/** + * Jira Cloud's REST API (v3), signed with the credential saved in Settings: the site, the + * account's email and an API token, stored together as one JSON value. Every call goes to that + * credential's own site, so a stored credential never reaches another one. + */ +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { IssueTrackerError } from "@t3tools/source-control-core/server/IssueTracker"; +import * as IssueTrackerHost from "@t3tools/source-control-core/server/IssueTrackerHost"; +import { retryAtFromHeader } from "@t3tools/source-control-core/server/SourceControlRateLimit"; + +import { JIRA_KIND } from "../shared/issueUrl.ts"; + +export const KIND = JIRA_KIND; +const REQUEST_TIMEOUT = "30 seconds"; + +const Credential = Schema.Struct({ + site: Schema.String, + email: Schema.String, + token: Schema.String, +}); +const decodeCredential = Schema.decodeUnknownOption(Schema.fromJsonString(Credential)); + +export interface JiraCredential { + /** The site's subdomain: `acme` for `acme.atlassian.net`. */ + readonly site: string; + readonly email: string; + readonly token: string; +} + +/** + * The credential as Settings stores it, or null when a field is missing or the site is not a + * Jira Cloud site: the host must never come from anything but `.atlassian.net`. + */ +export function parseJiraCredential(value: string): JiraCredential | null { + const decoded = decodeCredential(value); + if (decoded._tag === "None") return null; + const site = decoded.value.site + .trim() + .toLowerCase() + .replace(/^https:\/\//, "") + .replace(/\/+$/, "") + .replace(/\.atlassian\.net$/, ""); + const email = decoded.value.email.trim(); + const token = decoded.value.token.trim(); + if (!/^[a-z0-9][a-z0-9-]*$/.test(site) || email === "" || token === "") return null; + return { site, email, token }; +} + +export const JiraUser = Schema.Struct({ + accountId: Schema.String, + displayName: Schema.optional(Schema.String), + emailAddress: Schema.optional(Schema.String), + avatarUrls: Schema.optional(Schema.Record(Schema.String, Schema.String)), +}); +export type JiraUser = typeof JiraUser.Type; + +export const JiraStatus = Schema.Struct({ + id: Schema.String, + name: Schema.String, + statusCategory: Schema.Struct({ key: Schema.String }), +}); +export type JiraStatus = typeof JiraStatus.Type; + +/** Jira documents are Atlassian Document Format; `jiraAdf.ts` reads and writes them. */ +const Document = Schema.NullOr(Schema.Unknown); + +const IssueFields = Schema.Struct({ + summary: Schema.String, + status: JiraStatus, + created: Schema.String, + updated: Schema.String, + resolutiondate: Schema.optional(Schema.NullOr(Schema.String)), + creator: Schema.optional(Schema.NullOr(JiraUser)), + reporter: Schema.optional(Schema.NullOr(JiraUser)), + assignee: Schema.optional(Schema.NullOr(JiraUser)), + labels: Schema.optional(Schema.Array(Schema.String)), + project: Schema.Struct({ key: Schema.String }), + description: Schema.optional(Document), +}); + +export const JiraIssue = Schema.Struct({ + id: Schema.String, + key: Schema.String, + fields: IssueFields, +}); +export type JiraIssue = typeof JiraIssue.Type; + +export const JiraComment = Schema.Struct({ + id: Schema.String, + author: Schema.optional(Schema.NullOr(JiraUser)), + body: Document, + created: Schema.String, +}); +export type JiraComment = typeof JiraComment.Type; + +const HistoryItem = Schema.Struct({ + field: Schema.String, + fromString: Schema.optional(Schema.NullOr(Schema.String)), + toString: Schema.optional(Schema.NullOr(Schema.String)), +}); +export const JiraHistory = Schema.Struct({ + id: Schema.String, + author: Schema.optional(Schema.NullOr(JiraUser)), + created: Schema.String, + items: Schema.Array(HistoryItem), +}); +export type JiraHistory = typeof JiraHistory.Type; + +export const JiraTransition = Schema.Struct({ + id: Schema.String, + to: JiraStatus, +}); +export type JiraTransition = typeof JiraTransition.Type; + +export const JiraIssueDetail = Schema.Struct({ + ...JiraIssue.fields, + changelog: Schema.optional(Schema.Struct({ histories: Schema.Array(JiraHistory) })), + transitions: Schema.optional(Schema.Array(JiraTransition)), +}); +export type JiraIssueDetail = typeof JiraIssueDetail.Type; + +const SearchPage = Schema.Struct({ + issues: Schema.Array(JiraIssue), + nextPageToken: Schema.optional(Schema.NullOr(Schema.String)), +}); + +const CommentPage = Schema.Struct({ + startAt: Schema.Number, + total: Schema.Number, + comments: Schema.Array(JiraComment), +}); +export type JiraCommentPage = typeof CommentPage.Type; + +const MAX_PROJECTS = 1_000; +const ProjectPage = Schema.Struct({ + isLast: Schema.optional(Schema.Boolean), + values: Schema.Array( + Schema.Struct({ id: Schema.String, key: Schema.String, name: Schema.String }), + ), +}); + +const IssueTypes = Schema.Struct({ + issueTypes: Schema.Array( + Schema.Struct({ + id: Schema.String, + name: Schema.String, + subtask: Schema.optional(Schema.Boolean), + }), + ), +}); + +const Labels = Schema.Struct({ + values: Schema.Array(Schema.String), + isLast: Schema.optional(Schema.Boolean), +}); + +const Created = Schema.Struct({ key: Schema.String }); + +/** Jira's development panel: which connected tools (GitHub, GitLab, Bitbucket) hold PRs. */ +const DevelopmentSummary = Schema.Struct({ + summary: Schema.Struct({ + pullrequest: Schema.optional( + Schema.Struct({ + byInstanceType: Schema.Record(Schema.String, Schema.Struct({ count: Schema.Number })), + }), + ), + }), +}); + +export const JiraPullRequest = Schema.Struct({ + name: Schema.String, + url: Schema.String, + status: Schema.optional(Schema.String), +}); +export type JiraPullRequest = typeof JiraPullRequest.Type; + +const DevelopmentDetail = Schema.Struct({ + detail: Schema.Array( + Schema.Struct({ pullRequests: Schema.optional(Schema.Array(JiraPullRequest)) }), + ), +}); + +const SUMMARY_FIELDS = [ + "summary", + "status", + "created", + "updated", + "resolutiondate", + "creator", + "reporter", + "assignee", + "labels", + "project", +]; + +/** What a write sends as a field, already in Jira's own shape. */ +export type JiraFields = Record; + +export class JiraApi extends Context.Service< + JiraApi, + { + /** The stored credential's site, which every issue URL and request is for. */ + readonly site: Effect.Effect; + /** Who a credential is and which projects it reaches. Takes one so it can vet a new one. */ + readonly probe: (credential?: string) => Effect.Effect< + { + readonly site: string; + readonly user: JiraUser; + readonly projects: ReadonlyArray<{ readonly key: string; readonly name: string }>; + }, + IssueTrackerError + >; + readonly myself: Effect.Effect; + readonly search: (input: { + readonly jql: string; + readonly limit: number; + readonly cursor?: string | undefined; + }) => Effect.Effect< + { readonly issues: ReadonlyArray; readonly nextCursor: string | null }, + IssueTrackerError + >; + /** Null when Jira has no such issue, or the credential cannot see it. */ + readonly getIssue: (key: string) => Effect.Effect; + /** Newest first, so the first page is the latest conversation. */ + readonly getComments: (input: { + readonly key: string; + readonly startAt: number; + readonly limit: number; + }) => Effect.Effect; + /** + * The pull requests Jira's development panel shows for an issue, from every connected tool. + * Jira serves these from an undocumented API, so callers treat a failure as none. + */ + readonly pullRequests: ( + issueId: string, + ) => Effect.Effect, IssueTrackerError>; + readonly createIssue: (fields: JiraFields) => Effect.Effect; + readonly updateIssue: ( + key: string, + fields: JiraFields, + ) => Effect.Effect; + readonly addComment: (key: string, body: unknown) => Effect.Effect; + readonly transition: (key: string, id: string) => Effect.Effect; + readonly issueTypes: ( + project: string, + ) => Effect.Effect; + readonly assignableUsers: (input: { + readonly project?: string | undefined; + readonly issueKey?: string | undefined; + readonly query?: string | undefined; + readonly limit: number; + }) => Effect.Effect, IssueTrackerError>; + readonly labels: ( + limit: number, + ) => Effect.Effect< + { readonly values: ReadonlyArray; readonly truncated: boolean }, + IssueTrackerError + >; + } +>()("@t3tools/issue-tracker-jira/server/JiraApi") {} + +const fail = ( + operation: string, + reason: IssueTrackerError["reason"], + detail: string, + extra: { readonly retryAt?: number | undefined; readonly cause?: unknown } = {}, +) => + new IssueTrackerError({ + tracker: KIND, + operation, + reason, + detail, + ...(extra.retryAt === undefined ? {} : { retryAt: extra.retryAt }), + ...(extra.cause === undefined ? {} : { cause: extra.cause }), + }); + +const ErrorBody = Schema.Struct({ + errorMessages: Schema.optional(Schema.Array(Schema.String)), + errors: Schema.optional(Schema.Record(Schema.String, Schema.String)), +}); + +/** Jira writes its refusals for people; the first one is what the user is shown. */ +const refusal = Effect.fn("JiraApi.refusal")(function* ( + operation: string, + response: HttpClientResponse.HttpClientResponse, +) { + const now = yield* Clock.currentTimeMillis; + if (response.status === 429) { + return fail(operation, "rate-limited", "Jira's rate limit was reached.", { + retryAt: retryAtFromHeader(response.headers["retry-after"], now), + }); + } + if (response.status === 401) { + return fail(operation, "unauthenticated", "Jira rejected the email and API token."); + } + const body = yield* HttpClientResponse.schemaBodyJson(ErrorBody)(response).pipe( + Effect.orElseSucceed(() => ({ errorMessages: [], errors: {} })), + ); + const messages = [...(body.errorMessages ?? []), ...Object.values(body.errors ?? {})].filter( + (text): text is string => typeof text === "string", + ); + const message = messages.map((text) => text.trim()).find((text) => text !== ""); + if (response.status === 404) { + return fail(operation, "not-found", message ?? "Jira has no such issue or project."); + } + return fail(operation, "failed", message ?? `Jira returned HTTP ${response.status}.`); +}); + +export const make = Effect.gen(function* () { + const httpClient = yield* HttpClient.HttpClient; + const host = yield* IssueTrackerHost.IssueTrackerHost; + + const credential = (operation: string, given?: string) => + (given === undefined + ? host.credentials + .get(KIND) + .pipe( + Effect.flatMap( + Effect.fromOption(() => + fail(operation, "unauthenticated", "Jira is not connected on this server."), + ), + ), + ) + : Effect.succeed(given) + ).pipe( + Effect.flatMap((value) => { + const parsed = parseJiraCredential(value); + return parsed === null + ? Effect.fail( + fail( + operation, + "unauthenticated", + "Enter a Jira Cloud site, the account's email and an API token.", + ), + ) + : Effect.succeed(parsed); + }), + ); + + const call = Effect.fn("JiraApi.call")(function* < + S extends Schema.Top & { readonly DecodingServices: never }, + >(input: { + readonly operation: string; + readonly method: "GET" | "POST" | "PUT"; + /** Under the REST API root, unless `api` names another of the site's APIs. */ + readonly path: string; + readonly api?: string | undefined; + readonly params?: Record | undefined; + readonly body?: unknown; + /** Null for a call that answers with no body. */ + readonly schema: S | null; + readonly credential?: string | undefined; + }): Effect.fn.Return { + yield* Effect.annotateCurrentSpan({ "jira.operation": input.operation }); + const { site, email, token } = yield* credential(input.operation, input.credential); + const url = `https://${site}.atlassian.net${input.api ?? "/rest/api/3"}${input.path}`; + let request = HttpClientRequest.make(input.method)(url).pipe( + HttpClientRequest.acceptJson, + HttpClientRequest.basicAuth(email, token), + HttpClientRequest.setUrlParams(input.params ?? {}), + ); + if (input.body !== undefined) { + request = yield* HttpClientRequest.bodyJson(request, input.body).pipe( + Effect.mapError((cause) => + fail(input.operation, "failed", "The request could not be encoded.", { cause }), + ), + ); + } + const unreachable = (cause?: unknown) => + fail(input.operation, "failed", "Jira could not be reached.", { cause }); + const exchange = Effect.gen(function* () { + const response = yield* httpClient.execute(request).pipe(Effect.mapError(unreachable)); + if (response.status < 200 || response.status >= 300) { + return yield* Effect.flatMap(refusal(input.operation, response), Effect.fail); + } + if (input.schema === null) return null; + return yield* HttpClientResponse.schemaBodyJson(input.schema)(response).pipe( + Effect.mapError((cause) => + fail(input.operation, "failed", "Jira returned an unexpected body.", { cause }), + ), + ); + }); + // The deadline covers the body too: Jira can send its headers, then stall. + return yield* exchange.pipe( + Effect.timeoutOrElse({ + duration: REQUEST_TIMEOUT, + orElse: () => Effect.fail(unreachable()), + }), + ); + }); + + const read = ( + input: Omit>[0], "schema"> & { readonly schema: S }, + ) => call(input) as Effect.Effect; + const write = (input: Omit[0], "schema">) => + call({ ...input, schema: null }).pipe(Effect.asVoid); + + const myself = (operation: string, given?: string) => + read({ operation, method: "GET", path: "/myself", schema: JiraUser, credential: given }); + + const probe: JiraApi["Service"]["probe"] = Effect.fn("JiraApi.probe")(function* (given) { + const { site } = yield* credential("probe", given); + // A site name that is no Jira site answers 404, which would read as a missing issue. + const user = yield* myself("probe", given).pipe( + Effect.catchIf( + (error) => error.reason === "not-found", + () => + Effect.fail( + fail("probe", "unauthenticated", `${site}.atlassian.net is not a Jira site.`), + ), + ), + ); + const projects: Array<{ readonly key: string; readonly name: string }> = []; + // shortcut: stops at MAX_PROJECTS, page the picker itself if sites outgrow it. + while (projects.length < MAX_PROJECTS) { + const page = yield* read({ + operation: "probe", + method: "GET", + path: "/project/search", + params: { startAt: String(projects.length), maxResults: "100", orderBy: "key" }, + schema: ProjectPage, + credential: given, + }); + projects.push(...page.values.map(({ key, name }) => ({ key, name }))); + if (page.isLast !== false || page.values.length === 0) break; + } + return { site, user, projects }; + }); + + const getIssue: JiraApi["Service"]["getIssue"] = (key) => + read({ + operation: "getIssue", + method: "GET", + path: `/issue/${encodeURIComponent(key)}`, + params: { + fields: [...SUMMARY_FIELDS, "description"].join(","), + expand: "changelog,transitions", + }, + schema: JiraIssueDetail, + }).pipe( + Effect.map((issue): JiraIssueDetail | null => issue), + Effect.catchIf( + (error) => error.reason === "not-found", + () => Effect.succeed(null), + ), + ); + + const search: JiraApi["Service"]["search"] = Effect.fn("JiraApi.search")(function* (input) { + const page = yield* read({ + operation: "listIssues", + method: "POST", + path: "/search/jql", + body: { + jql: input.jql, + maxResults: input.limit, + fields: SUMMARY_FIELDS, + ...(input.cursor === undefined ? {} : { nextPageToken: input.cursor }), + }, + schema: SearchPage, + }); + return { issues: page.issues, nextCursor: page.nextPageToken ?? null }; + }); + + const getComments: JiraApi["Service"]["getComments"] = Effect.fn("JiraApi.getComments")( + function* (input) { + return yield* read({ + operation: "getComments", + method: "GET", + path: `/issue/${encodeURIComponent(input.key)}/comment`, + params: { + startAt: String(input.startAt), + maxResults: String(input.limit), + orderBy: "-created", + }, + schema: CommentPage, + }); + }, + ); + + const createIssue: JiraApi["Service"]["createIssue"] = Effect.fn("JiraApi.createIssue")( + function* (fields) { + const created = yield* read({ + operation: "createIssue", + method: "POST", + path: "/issue", + body: { fields }, + schema: Created, + }); + return created.key; + }, + ); + + const updateIssue: JiraApi["Service"]["updateIssue"] = Effect.fn("JiraApi.updateIssue")( + function* (key, fields) { + yield* write({ + operation: "updateIssue", + method: "PUT", + path: `/issue/${encodeURIComponent(key)}`, + body: { fields }, + }); + }, + ); + + const addComment: JiraApi["Service"]["addComment"] = Effect.fn("JiraApi.addComment")( + function* (key, body) { + yield* write({ + operation: "addComment", + method: "POST", + path: `/issue/${encodeURIComponent(key)}/comment`, + body: { body }, + }); + }, + ); + + const transition: JiraApi["Service"]["transition"] = Effect.fn("JiraApi.transition")( + function* (key, id) { + yield* write({ + operation: "transition", + method: "POST", + path: `/issue/${encodeURIComponent(key)}/transitions`, + body: { transition: { id } }, + }); + }, + ); + + const pullRequests: JiraApi["Service"]["pullRequests"] = Effect.fn("JiraApi.pullRequests")( + function* (issueId) { + const api = "/rest/dev-status/latest"; + const { summary } = yield* read({ + operation: "pullRequests", + method: "GET", + api, + path: "/issue/summary", + params: { issueId }, + schema: DevelopmentSummary, + }); + const tools = Object.entries(summary.pullrequest?.byInstanceType ?? {}) + .filter(([, tool]) => tool.count > 0) + .map(([applicationType]) => applicationType); + const details = yield* Effect.forEach( + tools, + (applicationType) => + read({ + operation: "pullRequests", + method: "GET", + api, + path: "/issue/detail", + params: { issueId, applicationType, dataType: "pullrequest" }, + schema: DevelopmentDetail, + }).pipe(Effect.orElseSucceed(() => ({ detail: [] }))), + { concurrency: "unbounded" }, + ); + return details.flatMap(({ detail }) => detail.flatMap((entry) => entry.pullRequests ?? [])); + }, + ); + + const issueTypes: JiraApi["Service"]["issueTypes"] = Effect.fn("JiraApi.issueTypes")( + function* (project) { + const types = yield* read({ + operation: "issueTypes", + method: "GET", + path: `/issue/createmeta/${encodeURIComponent(project)}/issuetypes`, + schema: IssueTypes, + }); + return types.issueTypes; + }, + ); + + const assignableUsers: JiraApi["Service"]["assignableUsers"] = Effect.fn( + "JiraApi.assignableUsers", + )(function* (input) { + return yield* read({ + operation: "assignableUsers", + method: "GET", + path: "/user/assignable/search", + params: { + maxResults: String(input.limit), + ...(input.project === undefined ? {} : { project: input.project }), + ...(input.issueKey === undefined ? {} : { issueKey: input.issueKey }), + ...(input.query === undefined ? {} : { query: input.query }), + }, + schema: Schema.Array(JiraUser), + }); + }); + + const labels: JiraApi["Service"]["labels"] = Effect.fn("JiraApi.labels")(function* (limit) { + const page = yield* read({ + operation: "labels", + method: "GET", + path: "/label", + params: { maxResults: String(limit) }, + schema: Labels, + }); + return { values: page.values, truncated: page.isLast === false }; + }); + + return JiraApi.of({ + site: credential("site").pipe(Effect.map(({ site }) => site)), + probe, + myself: myself("myself"), + search, + getIssue, + getComments, + pullRequests, + createIssue, + updateIssue, + addComment, + transition, + issueTypes, + assignableUsers, + labels, + }); +}); + +export const layer = Layer.effect(JiraApi, make); diff --git a/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts b/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts new file mode 100644 index 0000000000000..97d60c92a8aaf --- /dev/null +++ b/packages/issue-tracker-jira/src/server/JiraIssueTracker.test.ts @@ -0,0 +1,400 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as TestClock from "effect/testing/TestClock"; +import { HttpClient, HttpClientResponse, UrlParams } from "effect/http"; +import type { StandaloneIssueTrackerApi } from "@t3tools/source-control-core/server/IssueTracker"; +import * as IssueTrackerHost from "@t3tools/source-control-core/server/IssueTrackerHost"; + +import * as JiraApi from "./JiraApi.ts"; +import * as JiraIssueTracker from "./JiraIssueTracker.ts"; + +const STORED = JSON.stringify({ site: "acme", email: "julius@acme.test", token: "tok" }); + +const user = (accountId: string, displayName: string) => ({ accountId, displayName }); +const JULIUS = user("5b10a2844c20165700ede21g", "Julius"); +const THEO = user("5b10ac8d82e05b22cc7d4ef5", "Theo"); + +const status = (name: string, category: "indeterminate" | "done") => ({ + id: `st_${name}`, + name, + statusCategory: { key: category }, +}); + +const issue = (key: string, overrides: Record = {}) => ({ + id: `id_${key}`, + key, + fields: { + summary: `Issue ${key}`, + status: status("In Progress", "indeterminate"), + created: "2026-07-01T10:00:00.000+0000", + updated: "2026-07-02T10:00:00.000+0000", + resolutiondate: null, + reporter: JULIUS, + assignee: THEO, + labels: ["bug"], + project: { key: key.split("-")[0] }, + ...overrides, + }, +}); + +const doc = (...content: ReadonlyArray) => ({ type: "doc", version: 1, content }); +const paragraph = (text: string) => ({ type: "paragraph", content: [{ type: "text", text }] }); + +interface Seen { + readonly method: string; + readonly path: string; + readonly params: URLSearchParams; + readonly body: unknown; + readonly authorization: string | undefined; +} + +/** Answers each request by `METHOD /path` under the REST API root, the way Jira Cloud would. */ +function fakeJira( + answers: Record unknown>, + stored: string | null = STORED, +) { + const requests: Seen[] = []; + const http = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.sync(() => { + const url = new URL(request.url); + const body = request.body; + const seen: Seen = { + method: request.method, + path: url.pathname.replace("/rest/api/3", ""), + params: new URLSearchParams(UrlParams.toString(request.urlParams)), + body: + body._tag === "Uint8Array" + ? JSON.parse(new TextDecoder().decode(body.body)) + : undefined, + authorization: request.headers.authorization, + }; + expect(url.origin).toBe("https://acme.atlassian.net"); + requests.push(seen); + const answer = answers[`${seen.method} ${seen.path}`]; + const answered = answer?.(seen); + const response = + answered instanceof Response + ? answered + : answer === undefined + ? new Response(JSON.stringify({ errorMessages: [`No answer for ${seen.path}`] }), { + status: 400, + headers: { "content-type": "application/json" }, + }) + : answered === undefined + ? new Response(null, { status: 204 }) + : new Response(JSON.stringify(answered), { + status: 200, + headers: { "content-type": "application/json" }, + }); + return HttpClientResponse.fromWeb(request, response); + }), + ), + ); + const host = Layer.succeed( + IssueTrackerHost.IssueTrackerHost, + IssueTrackerHost.IssueTrackerHost.of({ + credentials: { get: () => Effect.succeed(Option.fromNullishOr(stored)) }, + }), + ); + // Every optional write that Jira supports is implemented; the type says so for the calls below. + const tracker = JiraIssueTracker.make.pipe( + Effect.map((api) => api as Required), + Effect.provide(JiraApi.layer.pipe(Layer.provide(Layer.merge(http, host)))), + ); + return { tracker, requests }; +} + +const target = { cwd: "/w/web", host: "atlassian.net", scope: "ENG" }; +describe("JiraIssueTracker", () => { + it.effect("parses only Jira Cloud issue links", () => + Effect.gen(function* () { + const api = yield* fakeJira({}).tracker; + expect( + api.parseIssueUrl(new URL("https://acme.atlassian.net/browse/ENG-12?focusedCommentId=1")), + ).toEqual({ host: "atlassian.net", workspace: "acme", scope: "ENG", key: "ENG-12" }); + for (const url of [ + "https://acme.atlassian.net:444/browse/ENG-12", + "https://acme.atlassian.net.evil.test/browse/ENG-12", + "https://acme.atlassian.net/browse/ENG-12/extra", + ]) { + expect(api.parseIssueUrl(new URL(url)), url).toBeNull(); + } + }), + ); + + it.effect("vets a credential against its own site, reading every project page", () => + Effect.gen(function* () { + const { tracker, requests } = fakeJira( + { + "GET /myself": () => JULIUS, + "GET /project/search": (seen) => + seen.params.get("startAt") === "0" + ? { isLast: false, values: [{ id: "1", key: "ENG", name: "Engineering" }] } + : { isLast: true, values: [{ id: "2", key: "OPS", name: "Operations" }] }, + }, + null, + ); + const api = yield* tracker; + const probe = yield* api.probeCredential( + JSON.stringify({ + site: "https://ACME.atlassian.net/", + email: "julius@acme.test", + token: "t", + }), + ); + expect(probe).toEqual({ + account: "Julius", + workspace: "acme", + scopes: [ + { key: "ENG", name: "Engineering" }, + { key: "OPS", name: "Operations" }, + ], + }); + expect(requests[0]?.authorization).toBe(`Basic ${btoa("julius@acme.test:t")}`); + // A site that is not a Jira Cloud subdomain is never asked anything. + const refused = yield* Effect.flip( + api.probeCredential(JSON.stringify({ site: "acme/../x", email: "a@b.c", token: "t" })), + ); + expect(refused.reason).toBe("unauthenticated"); + expect(requests).toHaveLength(3); + const { tracker: missing } = fakeJira( + { "GET /myself": () => new Response("", { status: 404 }) }, + null, + ); + const unknownSite = yield* Effect.flip( + (yield* missing).probeCredential( + JSON.stringify({ site: "acme", email: "a@b.c", token: "t" }), + ), + ); + expect(unknownSite.detail).toBe("acme.atlassian.net is not a Jira site."); + }), + ); + + it.effect("lists a project's issues with JQL built from the filters", () => + Effect.gen(function* () { + const { tracker, requests } = fakeJira({ + "GET /user/assignable/search": () => [THEO], + "POST /search/jql": () => ({ + issues: [issue("ENG-2", { status: status("Done", "done") })], + nextPageToken: "tok_2", + }), + }); + const api = yield* tracker; + const page = yield* api.listIssues({ + ...target, + involvement: "assigned", + viewer: "Julius", + state: "open", + limit: 25, + query: 'say "hi" 7', + assignee: "Theo", + sort: "created", + }); + expect(requests.at(-1)?.body).toMatchObject({ + jql: + 'project = "ENG" AND statusCategory != Done AND assignee = currentUser() AND ' + + `assignee = "${THEO.accountId}" AND text ~ "say \\"hi\\" 7" ORDER BY created DESC`, + }); + expect(page.nextCursor).toBe("tok_2"); + expect(page.items[0]?.state).toMatchObject({ category: "closed", name: "Done" }); + const injected = yield* Effect.flip( + api.listIssues({ + ...target, + scope: 'ENG" OR project = "OPS', + involvement: "all", + state: "all", + limit: 1, + sort: "updated", + }), + ); + expect(injected.detail).toContain("not a Jira project key"); + }), + ); + + it.effect("reads an issue with its newest comments oldest first, its history and its moves", () => + Effect.gen(function* () { + const { tracker, requests } = fakeJira({ + "GET /myself": () => JULIUS, + "GET /issue/ENG-1": () => ({ + ...issue("ENG-1", { description: doc(paragraph("Steps")) }), + changelog: { + histories: [ + { + id: "100", + author: THEO, + created: "2026-07-01T11:00:00.000+0000", + items: [ + { field: "status", fromString: "To Do", toString: "In Progress" }, + { field: "labels", fromString: "old", toString: "bug" }, + ], + }, + ], + }, + transitions: [{ id: "31", to: status("Done", "done") }], + }), + "GET /issue/ENG-1/comment": (seen) => { + const startAt = Number(seen.params.get("startAt")); + const comment = (n: number) => ({ + id: `c${n}`, + author: THEO, + body: doc(paragraph(`comment ${n}`)), + created: "2026-07-02T09:00:00.000+0000", + }); + return { startAt, total: 51, comments: [comment(startAt + 2), comment(startAt + 1)] }; + }, + "GET /rest/dev-status/latest/issue/summary": () => ({ + summary: { + pullrequest: { + byInstanceType: { GitHub: { count: 1 }, GitLab: { count: 1 }, stash: { count: 0 } }, + }, + }, + }), + "GET /rest/dev-status/latest/issue/detail": (seen) => { + expect(seen.params.get("applicationType")).not.toBe("stash"); + if (seen.params.get("applicationType") === "GitLab") + return new Response("", { status: 403 }); + const pull = { name: "Fix", url: "https://github.com/acme/web/pull/7", status: "MERGED" }; + return { detail: [{ pullRequests: [pull, pull] }] }; + }, + }); + const api = yield* tracker; + const detail = yield* api.getIssue({ ...target, key: "eng-1" }); + expect(detail).toMatchObject({ key: "ENG-1", body: "Steps", viewer: "Julius" }); + expect(detail.comments.map((comment) => comment.id)).toEqual(["c1", "c2"]); + expect(detail.commentsCursor).toBe("2"); + expect(detail.states.map((state) => state.name)).toEqual(["In Progress", "Done"]); + expect(detail.linkedPullRequests).toEqual([ + { + repository: "acme/web", + number: 7, + title: "Fix", + url: "https://github.com/acme/web/pull/7", + state: "merged", + isDraft: false, + closesIssue: false, + }, + ]); + expect(detail.events.map((event) => [event.kind, event.detail])).toEqual([ + ["state-changed", "In Progress"], + ["labeled", "bug"], + ["unlabeled", "old"], + ]); + const older = yield* api.getComments({ ...target, key: "ENG-1", cursor: "2" }); + expect(requests.at(-1)?.params.get("orderBy")).toBe("-created"); + expect(older.comments.map((comment) => comment.id)).toEqual(["c3", "c4"]); + }), + ); + + it.effect("writes only to issues in the bound project, as Markdown turned into ADF", () => + Effect.gen(function* () { + const writes: Seen[] = []; + const { tracker } = fakeJira({ + "GET /issue/ENG-1": () => ({ + ...issue("ENG-1"), + transitions: [{ id: "31", to: status("Done", "done") }], + }), + "GET /issue/OPS-3": () => issue("OPS-3"), + "GET /issue/ENG-5": () => + issue("ENG-5", { description: doc({ type: "mediaSingle", content: [] }) }), + "PUT /issue/ENG-1": (seen) => void writes.push(seen), + "POST /issue/ENG-1/comment": (seen) => void writes.push(seen), + "POST /issue/ENG-1/transitions": (seen) => void writes.push(seen), + "GET /user/assignable/search": () => [THEO, user("5b10ac8d82e05b22cc7d4ef6", "Theo")], + "GET /issue/createmeta/ENG/issuetypes": () => ({ + issueTypes: [ + { id: "5", name: "Sub-task", subtask: true }, + { id: "10001", name: "Task", subtask: false }, + ], + }), + "POST /issue": (seen) => { + writes.push(seen); + return { id: "100", key: "ENG-42" }; + }, + }); + const api = yield* tracker; + // A key from another project resolves in Jira, so the project is checked before writing. + const foreign = yield* Effect.flip(api.comment({ ...target, key: "OPS-3", body: "hi" })); + expect(foreign.detail).toBe("OPS-3 belongs to Jira project OPS, not ENG."); + // Its attachment would not survive the Markdown round trip, so the body is not rewritten. + const attached = yield* Effect.flip(api.update({ ...target, key: "ENG-5", body: "new" })); + expect(attached.detail).toContain("Edit it in Jira"); + const ambiguous = yield* Effect.flip( + api.update({ ...target, key: "ENG-1", assignees: ["Theo"] }), + ); + expect(ambiguous.detail).toContain("More than one"); + + yield* api.comment({ ...target, key: "ENG-1", body: "**Done**" }); + yield* api.update({ ...target, key: "ENG-1", title: "Renamed", assignees: [THEO.accountId] }); + yield* api.setState({ ...target, key: "ENG-1", state: "Done" }); + const created = yield* api.create({ + ...target, + title: "New", + body: "", + labels: [], + assignees: [], + }); + expect(created.url).toBe("https://acme.atlassian.net/browse/ENG-42"); + expect(writes.map((write) => [write.method, write.path, write.body])).toEqual([ + [ + "POST", + "/issue/ENG-1/comment", + { + body: doc({ + type: "paragraph", + content: [{ type: "text", text: "Done", marks: [{ type: "strong" }] }], + }), + }, + ], + [ + "PUT", + "/issue/ENG-1", + { fields: { summary: "Renamed", assignee: { accountId: THEO.accountId } } }, + ], + ["POST", "/issue/ENG-1/transitions", { transition: { id: "31" } }], + [ + "POST", + "/issue", + { fields: { project: { key: "ENG" }, issuetype: { id: "10001" }, summary: "New" } }, + ], + ]); + }), + ); + + it.effect("maps Jira's refusals to the tracker's failure reasons", () => + Effect.gen(function* () { + const { tracker } = fakeJira({ + "GET /myself": () => new Response("", { status: 401 }), + "POST /search/jql": () => + new Response("", { status: 429, headers: { "retry-after": "30" } }), + "GET /issue/ENG-1": () => + new Response(new ReadableStream(), { headers: { "content-type": "application/json" } }), + "GET /issue/createmeta/ENG/issuetypes": () => + new Response(JSON.stringify({ errors: { project: "You cannot create issues here." } }), { + status: 403, + }), + }); + const api = yield* tracker; + const unauthenticated = yield* Effect.flip(api.getViewer({ cwd: "", host: "atlassian.net" })); + expect(unauthenticated.reason).toBe("unauthenticated"); + const limited = yield* Effect.flip( + api.listIssues({ ...target, involvement: "all", state: "all", limit: 1, sort: "updated" }), + ); + expect(limited.retryAt).toBeGreaterThan(0); + const refused = yield* Effect.flip( + api.create({ ...target, title: "x", body: "", labels: [], assignees: [] }), + ); + expect(refused.detail).toBe("You cannot create issues here."); + // A reply that sends its headers and then stalls still ends at the deadline. + const stalled = yield* Effect.forkChild( + Effect.flip(api.getIssue({ ...target, key: "ENG-1" })), + ); + yield* TestClock.adjust("31 seconds"); + expect((yield* Fiber.join(stalled)).detail).toBe("Jira could not be reached."); + }), + ); +}); diff --git a/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts b/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts new file mode 100644 index 0000000000000..fddcbf00ff63f --- /dev/null +++ b/packages/issue-tracker-jira/src/server/JiraIssueTracker.ts @@ -0,0 +1,538 @@ +/** + * Jira Cloud as an issue tracker. A scope is a project key (`ENG`) and an issue key its own + * (`ENG-123`). A status is closed when its category is `done`; moving between statuses goes + * through the workflow transitions Jira offers for the issue, never a status set directly. + */ +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import type { + IssueActor, + IssueCapabilities, + IssueComment, + IssueEvent, + IssueLinkedPullRequest, + IssueState, + IssueViewerPermissions, + StandaloneIssueTrackerDescriptor, +} from "@t3tools/contracts"; +import { + IssueTrackerError, + type IssueInvolvementFilter, + type StandaloneIssueTrackerApi, + type TrackerIssueSummary, +} from "@t3tools/source-control-core/server/IssueTracker"; + +import { JIRA_HOST, parseJiraIssueUrl } from "../shared/issueUrl.ts"; +import * as JiraApi from "./JiraApi.ts"; +import { adfToMarkdown, hasJiraOnlyContent, markdownToAdf } from "./jiraAdf.ts"; + +const DESCRIPTOR: StandaloneIssueTrackerDescriptor = { + tracker: JiraApi.KIND, + displayName: "Jira", + host: JIRA_HOST, + scopeNoun: "project", + credential: { + label: "Personal API token", + helpUrl: "https://id.atlassian.com/manage-profile/security/api-tokens", + fields: [ + { key: "site", label: "Site", placeholder: "example.atlassian.net", secret: false }, + { key: "email", label: "Email", placeholder: "you@example.com", secret: false }, + { key: "token", label: "API token", placeholder: "Without scopes", secret: true }, + ], + }, +}; + +/** Reactions and templates have no Jira Cloud API an API token can reach. */ +const CAPABILITIES: IssueCapabilities = { + create: true, + edit: true, + comment: true, + labels: true, + assignees: true, + reactions: false, + templates: false, + linkedPullRequests: true, + events: true, + search: true, +}; + +/** Everything granted: Jira refuses a write the account may not make, and says why. */ +const VIEWER_PERMISSIONS: IssueViewerPermissions = { + setState: true, + comment: true, + edit: true, + labels: true, + assignees: true, +}; + +const COMMENTS_PAGE = 50; +const CANDIDATES = 100; +const KEY = /^[A-Za-z][A-Za-z0-9_]*-[1-9]\d*$/; +const PROJECT = /^[A-Za-z][A-Za-z0-9_]*$/; + +/** `ENG-123`, or null for anything that is not a Jira key. */ +function parseKey(key: string): string | null { + return KEY.test(key.trim()) ? key.trim().toUpperCase() : null; +} + +/** A JQL string literal: Jira reads backslash escapes inside double quotes. */ +export function jqlString(value: string): string { + return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`; +} + +/** Jira answers with `+0000` offsets; the contract carries ISO 8601 with a `Z`. */ +function isoDate(value: string): string { + return Option.match(DateTime.make(value), { onNone: () => value, onSome: DateTime.formatIso }); +} + +function toState(status: JiraApi.JiraStatus): IssueState { + return status.statusCategory.key === "done" + ? { category: "closed", name: status.name, closeReason: "completed" } + : { category: "open", name: status.name }; +} + +/** + * The login is the display name, which is what people see and filter by: Jira Cloud has no + * handle. Writes and filters name people by account id, which `requireAccountId` resolves. + */ +function toActor(user: JiraApi.JiraUser): IssueActor { + return { + login: user.displayName?.trim() || user.accountId, + name: user.displayName?.trim() || null, + avatarUrl: user.avatarUrls?.["48x48"] ?? null, + }; +} + +/** Jira Cloud account ids: 24 hex digits, or `:`. */ +const ACCOUNT_ID = /^(?:[0-9a-z]{24}|\d+:[0-9a-f-]{36})$/i; + +/** `//pull/1`, as GitHub, GitLab (`-/merge_requests`) or Bitbucket write it. */ +const PULL_REQUEST_URL = + /^https:\/\/[^/]+\/(.+?)\/(?:pull|-\/merge_requests|pull-requests)\/(\d+)\/?(?:[?#]|$)/u; + +function toLinkedPullRequests( + pulls: ReadonlyArray, +): IssueLinkedPullRequest[] { + const seen = new Set(); + return pulls.flatMap((pull) => { + const match = PULL_REQUEST_URL.exec(pull.url); + if (match === null || seen.has(pull.url)) return []; + seen.add(pull.url); + const status = pull.status?.toUpperCase(); + return [ + { + repository: match[1]!, + number: Number(match[2]), + title: pull.name.trim() || pull.url, + url: pull.url, + state: + status === "MERGED" + ? "merged" + : status === "OPEN" || status === "DRAFT" + ? "open" + : "closed", + isDraft: status === "DRAFT", + closesIssue: false, + } as const, + ]; + }); +} + +const issueUrl = (site: string, key: string) => `https://${site}.atlassian.net/browse/${key}`; + +/** A search reports no comment totals cheaply, so a listing shows no comment count. */ +function toSummary(site: string, issue: JiraApi.JiraIssue, commentCount = 0): TrackerIssueSummary { + const fields = issue.fields; + const author = fields.reporter ?? fields.creator ?? null; + const closed = fields.status.statusCategory.key === "done"; + return { + key: issue.key, + displayKey: issue.key, + title: fields.summary.trim() || issue.key, + url: issueUrl(site, issue.key), + author: author === null ? null : toActor(author), + state: toState(fields.status), + createdAt: isoDate(fields.created), + updatedAt: isoDate(fields.updated), + closedAt: closed && fields.resolutiondate ? isoDate(fields.resolutiondate) : null, + assignees: fields.assignee ? [toActor(fields.assignee)] : [], + labels: (fields.labels ?? []).map((name) => ({ name, color: null })), + commentCount, + }; +} + +function toComment(site: string, key: string, comment: JiraApi.JiraComment): IssueComment { + return { + id: comment.id, + author: comment.author ? toActor(comment.author) : null, + body: adfToMarkdown(comment.body), + createdAt: isoDate(comment.created), + url: `${issueUrl(site, key)}?focusedCommentId=${encodeURIComponent(comment.id)}`, + }; +} + +/** Jira's changelog names fields by their display name; only the common vocabulary is kept. */ +function toEvents(histories: ReadonlyArray): IssueEvent[] { + const events: IssueEvent[] = []; + for (const history of histories) { + const actor = history.author ? toActor(history.author) : null; + const createdAt = isoDate(history.created); + history.items.forEach((item, index) => { + const add = (kind: IssueEvent["kind"], detail: string | null | undefined, suffix = "") => + events.push({ + id: `${history.id}:${index}${suffix}`, + kind, + actor, + createdAt, + detail: detail?.trim() || null, + }); + switch (item.field) { + case "status": + add("state-changed", item.toString); + break; + case "resolution": + add(item.toString ? "closed" : "reopened", item.toString); + break; + case "summary": + add("renamed", item.toString); + break; + case "assignee": + if (item.fromString) add("unassigned", item.fromString, "-"); + if (item.toString) add("assigned", item.toString, "+"); + break; + case "labels": { + // Labels arrive as the whole space-separated set before and after. + const before = new Set((item.fromString ?? "").split(" ").filter(Boolean)); + const after = new Set((item.toString ?? "").split(" ").filter(Boolean)); + for (const label of after) if (!before.has(label)) add("labeled", label, `+${label}`); + for (const label of before) if (!after.has(label)) add("unlabeled", label, `-${label}`); + break; + } + } + }); + } + return events; +} + +/** JQL names the signed-in account itself, so the viewer's display name is never matched on. */ +function involvementClause(input: IssueInvolvementFilter): string | null { + switch (input.involvement) { + case "assigned": + return "assignee = currentUser()"; + case "authored": + return "reporter = currentUser()"; + case "mentioned": + return "watcher = currentUser()"; + case "all": + return null; + } +} + +/** + * A comment cursor is the offset of the next older page, counted from the newest comment, so a + * comment added meanwhile shifts it by one at most and only repeats a comment the client drops. + */ +function parseCursor(cursor: string): number | null { + return /^[1-9]\d{0,8}$/.test(cursor) ? Number(cursor) : null; +} + +const notFound = (operation: string) => + new IssueTrackerError({ + tracker: JiraApi.KIND, + operation, + reason: "not-found", + detail: "Jira has no issue by that key, or this account cannot see it.", + }); + +const failed = (operation: string, detail: string) => + new IssueTrackerError({ tracker: JiraApi.KIND, operation, reason: "failed", detail }); + +export const make: Effect.Effect = Effect.gen( + function* () { + const jira = yield* JiraApi.JiraApi; + + const requireKey = (operation: string, key: string) => { + const parsed = parseKey(key); + return parsed === null ? Effect.fail(notFound(operation)) : Effect.succeed(parsed); + }; + + const requireProject = (operation: string, scope: string) => { + const project = scope.trim().toUpperCase(); + return PROJECT.test(project) + ? Effect.succeed(project) + : Effect.fail(failed(operation, `"${scope}" is not a Jira project key.`)); + }; + + /** + * The issue a write names, refused unless it sits in the bound project: a key from another + * project, or an issue moved away, still resolves in Jira. + */ + const requireProjectIssue = Effect.fn("JiraIssueTracker.requireProjectIssue")(function* ( + operation: string, + input: { readonly scope: string; readonly key: string }, + ) { + const key = yield* requireKey(operation, input.key); + const project = yield* requireProject(operation, input.scope); + const issue = yield* jira.getIssue(key); + if (issue === null) return yield* notFound(operation); + if (issue.fields.project.key.toUpperCase() !== project) { + return yield* failed( + operation, + `${issue.key} belongs to Jira project ${issue.fields.project.key}, not ${project}.`, + ); + } + return issue; + }); + + /** The comments page that ends `offset` comments back from the newest, oldest first. */ + const commentsPage = Effect.fn("JiraIssueTracker.commentsPage")(function* ( + key: string, + offset: number, + ) { + const [site, page] = yield* Effect.all([ + jira.site, + jira.getComments({ key, startAt: offset, limit: COMMENTS_PAGE }), + ]); + const next = offset + page.comments.length; + return { + total: page.total, + page: { + comments: page.comments.map((comment) => toComment(site, key, comment)).toReversed(), + nextCursor: page.comments.length > 0 && next < page.total ? String(next) : null, + }, + }; + }); + + /** Names as Jira stores them: one word each, since Jira splits labels on whitespace. */ + const requireLabels = (operation: string, labels: ReadonlyArray) => { + const bad = labels.find((label) => /\s/.test(label.trim()) || label.trim() === ""); + return bad === undefined + ? Effect.succeed(labels.map((label) => label.trim())) + : Effect.fail(failed(operation, `Jira labels cannot contain spaces: "${bad}".`)); + }; + + /** An account id as given, else the project's one assignable person by that display name. */ + const requireAccountId = Effect.fn("JiraIssueTracker.requireAccountId")(function* ( + operation: string, + project: string, + person: string, + ) { + const name = person.trim(); + if (ACCOUNT_ID.test(name)) return name; + const users = yield* jira.assignableUsers({ project, query: name, limit: CANDIDATES }); + const matches = users.filter( + (user) => user.displayName?.trim().toLowerCase() === name.toLowerCase(), + ); + if (matches.length === 1) return matches[0]!.accountId; + return yield* failed( + operation, + matches.length === 0 + ? `"${name}" cannot be assigned issues in Jira project ${project}.` + : `More than one person in Jira project ${project} is named "${name}".`, + ); + }); + + /** One assignee at most: a Jira issue has a single assignee. */ + const requireAssignee = Effect.fn("JiraIssueTracker.requireAssignee")(function* ( + operation: string, + project: string, + assignees: ReadonlyArray, + ) { + const [first, ...rest] = assignees; + if (first === undefined) return null; + if (rest.length > 0) + return yield* failed(operation, "A Jira issue has one assignee at most."); + return { accountId: yield* requireAccountId(operation, project, first) }; + }); + + const api: StandaloneIssueTrackerApi = { + kind: JiraApi.KIND, + capabilities: CAPABILITIES, + standalone: DESCRIPTOR, + parseIssueUrl: parseJiraIssueUrl, + + probeCredential: (credential) => + jira.probe(credential).pipe( + Effect.map((probe) => ({ + account: + probe.user.displayName?.trim() || probe.user.emailAddress || probe.user.accountId, + workspace: probe.site, + scopes: probe.projects, + })), + ), + + getViewer: () => jira.myself.pipe(Effect.map((user) => toActor(user).login)), + + listIssues: Effect.fn("JiraIssueTracker.listIssues")(function* (input) { + const project = yield* requireProject("listIssues", input.scope); + const text = input.query?.trim() ?? ""; + const reference = /^(?:[A-Za-z][A-Za-z0-9_]*-|#)?(\d+)$/.exec(text); + const involvement = involvementClause(input); + const clauses = [ + `project = ${jqlString(project)}`, + ...(input.state === "all" + ? [] + : [`statusCategory ${input.state === "closed" ? "=" : "!="} Done`]), + ...(involvement === null ? [] : [involvement]), + ...(input.assignee === undefined + ? [] + : [ + `assignee = ${jqlString(yield* requireAccountId("listIssues", project, input.assignee))}`, + ]), + ...(input.labels ?? []).map((label) => `labels = ${jqlString(label)}`), + ...(text === "" + ? [] + : [ + reference === null + ? `text ~ ${jqlString(text)}` + : `(text ~ ${jqlString(text)} OR key = ${jqlString(`${project}-${reference[1]}`)})`, + ]), + ]; + const order = input.sort === "created" ? "created" : "updated"; + const [site, page] = yield* Effect.all([ + jira.site, + jira.search({ + jql: `${clauses.join(" AND ")} ORDER BY ${order} DESC`, + limit: input.limit, + cursor: input.cursor, + }), + ]); + return { + items: page.issues.map((issue) => toSummary(site, issue)), + nextCursor: page.nextCursor, + }; + }), + + getIssue: Effect.fn("JiraIssueTracker.getIssue")(function* (input) { + const key = yield* requireKey("getIssue", input.key); + const [site, issue, viewer] = yield* Effect.all([ + jira.site, + jira.getIssue(key), + jira.myself.pipe( + Effect.map((user) => toActor(user).login), + Effect.orElseSucceed(() => null), + ), + ]); + if (issue === null) return yield* notFound("getIssue"); + const [comments, pulls] = yield* Effect.all( + [ + commentsPage(key, 0), + // An undocumented API: when it moves or refuses, the issue still opens. + jira.pullRequests(issue.id).pipe(Effect.orElseSucceed(() => [])), + ], + { concurrency: "unbounded" }, + ); + // A transition's target is a state the issue can move to; the current one is listed too. + const states = [issue.fields.status, ...(issue.transitions ?? []).map((t) => t.to)]; + const seen = new Set(); + return { + ...toSummary(site, issue, comments.total), + body: adfToMarkdown(issue.fields.description), + viewer, + viewerPermissions: VIEWER_PERMISSIONS, + states: states + .filter((status) => !seen.has(status.name) && seen.add(status.name) !== undefined) + .map(toState), + comments: comments.page.comments, + commentsCursor: comments.page.nextCursor, + events: toEvents(issue.changelog?.histories ?? []), + linkedPullRequests: toLinkedPullRequests(pulls), + }; + }), + + getComments: Effect.fn("JiraIssueTracker.getComments")(function* (input) { + const key = yield* requireKey("getComments", input.key); + const offset = parseCursor(input.cursor); + if (offset === null) + return yield* failed("getComments", "The cursor was not one Jira handed out."); + return (yield* commentsPage(key, offset)).page; + }), + + create: Effect.fn("JiraIssueTracker.create")(function* (input) { + const project = yield* requireProject("create", input.scope); + const labels = yield* requireLabels("create", input.labels); + const assignee = yield* requireAssignee("create", project, input.assignees); + const types = yield* jira.issueTypes(project); + // The project's first standard type, as Jira's own create dialog picks by default. + const type = types.find((candidate) => candidate.subtask !== true); + if (type === undefined) + return yield* failed( + "create", + `Jira project ${project} has no issue type to file under.`, + ); + const key = yield* jira.createIssue({ + project: { key: project }, + issuetype: { id: type.id }, + summary: input.title, + ...(input.body.trim() === "" ? {} : { description: markdownToAdf(input.body) }), + ...(labels.length === 0 ? {} : { labels }), + ...(assignee === null ? {} : { assignee }), + }); + const site = yield* jira.site; + return { key, displayKey: key, url: issueUrl(site, key) }; + }), + + comment: Effect.fn("JiraIssueTracker.comment")(function* (input) { + const issue = yield* requireProjectIssue("comment", input); + yield* jira.addComment(issue.key, markdownToAdf(input.body)); + }), + + update: Effect.fn("JiraIssueTracker.update")(function* (input) { + const issue = yield* requireProjectIssue("update", input); + // The Markdown a client edited lost these nodes on read; writing it back would delete them. + if (input.body !== undefined && hasJiraOnlyContent(issue.fields.description)) { + return yield* failed( + "update", + "This description has attachments or other content only Jira can edit. Edit it in Jira.", + ); + } + yield* jira.updateIssue(issue.key, { + ...(input.title === undefined ? {} : { summary: input.title }), + ...(input.body === undefined + ? {} + : { description: input.body.trim() === "" ? null : markdownToAdf(input.body) }), + ...(input.labels === undefined + ? {} + : { labels: yield* requireLabels("update", input.labels) }), + ...(input.assignees === undefined + ? {} + : { + assignee: yield* requireAssignee( + "update", + issue.fields.project.key, + input.assignees, + ), + }), + }); + }), + + setState: Effect.fn("JiraIssueTracker.setState")(function* (input) { + const issue = yield* requireProjectIssue("setState", input); + if (issue.fields.status.name === input.state) return; + const transition = (issue.transitions ?? []).find((t) => t.to.name === input.state); + if (transition === undefined) { + return yield* failed( + "setState", + `Jira's workflow offers no move from "${issue.fields.status.name}" to "${input.state}".`, + ); + } + yield* jira.transition(issue.key, transition.id); + }), + + listCandidates: Effect.fn("JiraIssueTracker.listCandidates")(function* (input) { + const project = yield* requireProject("listCandidates", input.scope); + const [labels, users] = yield* Effect.all([ + jira.labels(CANDIDATES), + jira.assignableUsers({ project, limit: CANDIDATES }), + ]); + return { + labels: labels.values.map((name) => ({ name, color: null, description: null })), + assignees: users.map((user) => ({ ...toActor(user), id: user.accountId })), + truncated: labels.truncated || users.length >= CANDIDATES, + }; + }), + }; + return api; + }, +); diff --git a/packages/issue-tracker-jira/src/server/driver.ts b/packages/issue-tracker-jira/src/server/driver.ts new file mode 100644 index 0000000000000..8b0939d4455a5 --- /dev/null +++ b/packages/issue-tracker-jira/src/server/driver.ts @@ -0,0 +1,12 @@ +import * as Effect from "effect/Effect"; + +import * as JiraApi from "./JiraApi.ts"; +import * as JiraIssueTracker from "./JiraIssueTracker.ts"; + +/** + * The Jira Cloud tracker over its REST API. Needs the platform HttpClient, and the server's + * `IssueTrackerHost` for the site, email and API token saved in Settings. + */ +export const make = JiraIssueTracker.make.pipe( + Effect.provideServiceEffect(JiraApi.JiraApi, JiraApi.make), +); diff --git a/packages/issue-tracker-jira/src/server/jiraAdf.test.ts b/packages/issue-tracker-jira/src/server/jiraAdf.test.ts new file mode 100644 index 0000000000000..fb40b536ac789 --- /dev/null +++ b/packages/issue-tracker-jira/src/server/jiraAdf.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { adfToMarkdown, hasJiraOnlyContent, markdownToAdf } from "./jiraAdf.ts"; + +const text = (value: string, marks?: ReadonlyArray) => + marks === undefined ? { type: "text", text: value } : { type: "text", text: value, marks }; +const doc = (...content: ReadonlyArray) => ({ type: "doc", version: 1, content }); +const paragraph = (...content: ReadonlyArray) => ({ type: "paragraph", content }); +const item = (...content: ReadonlyArray) => ({ type: "listItem", content }); +const link = { type: "link", attrs: { href: "https://x.test" } }; + +describe("jiraAdf", () => { + it("reads a Jira document as Markdown, naming what Markdown cannot hold", () => { + expect( + adfToMarkdown( + doc( + paragraph(text("the guide", [link, { type: "strong" }]), { + type: "mention", + attrs: { text: "@Theo" }, + }), + { + type: "orderedList", + attrs: { order: 3 }, + content: [ + item(paragraph(text("three")), { + type: "bulletList", + content: [item(paragraph(text("nested")))], + }), + ], + }, + { type: "mediaSingle", content: [{ type: "media", attrs: { id: "m1" } }] }, + ), + ), + ).toBe( + "[**the guide**](https://x.test)@Theo\n\n3. three\n - nested\n\n_(attachment, open in Jira to view)_", + ); + }); + + it("writes Markdown as the document Jira's editor would have stored", () => { + // Jira allows only a link beside a code mark; the first definition of a reference wins. + expect( + markdownToAdf("[`code` link][g]\n\n> [g]: https://x.test\n\n[g]: https://y.test").content[0], + ).toEqual(paragraph(text("code", [link, { type: "code" }]), text(" link", [link]))); + }); + + it("keeps a document's text through a round trip", () => { + const markdown = "Fix **this** and ~~that~~.\n\n- one\n- two\n\n```\nraw\n```"; + expect(adfToMarkdown(markdownToAdf(markdown))).toBe(markdown); + // Literal Markdown characters and a fence inside code stay what Jira stored. + const literal = doc( + paragraph(text("**draft** [x]"), text("a`b", [{ type: "code" }])), + paragraph(text("1. not a list")), + { type: "codeBlock", content: [text("```\nstill code")] }, + ); + expect(markdownToAdf(adfToMarkdown(literal))).toEqual(literal); + }); + + it("treats only what Markdown would lose as Jira-only", () => { + const table = (attrs: Record) => + doc({ + type: "table", + content: [{ type: "tableRow", content: [{ type: "tableHeader", attrs }] }], + }); + expect(hasJiraOnlyContent(table({ colspan: 1 }))).toBe(false); + expect(hasJiraOnlyContent(table({ colspan: 2 }))).toBe(true); + expect(hasJiraOnlyContent(doc(paragraph(text("x", [{ type: "textColor" }]))))).toBe(true); + }); +}); diff --git a/packages/issue-tracker-jira/src/server/jiraAdf.ts b/packages/issue-tracker-jira/src/server/jiraAdf.ts new file mode 100644 index 0000000000000..d14ff54efbd39 --- /dev/null +++ b/packages/issue-tracker-jira/src/server/jiraAdf.ts @@ -0,0 +1,394 @@ +/** + * Jira Cloud keeps descriptions and comments as Atlassian Document Format; T3 Code reads and + * writes Markdown. A read keeps the text and structure Markdown can carry and names what it + * cannot (an attachment, an unknown macro) instead of dropping it silently. + */ +import * as DateTime from "effect/DateTime"; +import * as Option from "effect/Option"; +import type * as Mdast from "mdast"; +import { fromMarkdown } from "mdast-util-from-markdown"; +import { gfmFromMarkdown } from "mdast-util-gfm"; +import { gfm } from "micromark-extension-gfm"; + +interface AdfMark { + readonly type: string; + readonly attrs?: Record; +} + +export interface AdfNode { + readonly type: string; + readonly text?: string; + readonly attrs?: Record; + readonly marks?: ReadonlyArray; + readonly content?: ReadonlyArray; +} + +const isNode = (value: unknown): value is AdfNode => + typeof value === "object" && + value !== null && + typeof (value as { type?: unknown }).type === "string"; + +const attr = (node: AdfNode, name: string): string | null => { + const value = node.attrs?.[name]; + return typeof value === "string" && value !== "" ? value : null; +}; + +function inline(nodes: ReadonlyArray | undefined): string { + return (nodes ?? []).map(inlineNode).join(""); +} + +/** Literal Jira text, escaped so Markdown reads it back as the same characters. */ +const escape = (text: string) => + text + .replace(/[\\`*_~[\]<&]/g, "\\$&") + .replace(/^(\s*)([#>+=-])/gm, "$1\\$2") + .replace(/^(\s*\d+)([.)])/gm, "$1\\$2"); + +/** The shortest run of backticks that `text` does not contain, at least `min` long. */ +const fence = (text: string, min: number) => + "`".repeat(Math.max(min, ...Array.from(text.matchAll(/`+/g), (run) => run[0].length + 1))); + +function marked(text: string, marks: ReadonlyArray | undefined): string { + const code = marks?.some((mark) => mark.type === "code") ?? false; + let out = code ? text : escape(text); + if (code) { + const ticks = fence(text, 1); + const pad = text.startsWith("`") || text.endsWith("`") ? " " : ""; + out = `${ticks}${pad}${out}${pad}${ticks}`; + } + for (const mark of marks ?? []) { + if (mark.type === "strong") out = `**${out}**`; + else if (mark.type === "em") out = `*${out}*`; + else if (mark.type === "strike") out = `~~${out}~~`; + } + const link = marks?.find((mark) => mark.type === "link")?.attrs?.["href"]; + return typeof link === "string" ? `[${out}](${link})` : out; +} + +function inlineNode(node: AdfNode): string { + switch (node.type) { + case "text": + return marked(node.text ?? "", node.marks); + case "hardBreak": + return "\n"; + case "mention": + return attr(node, "text") ?? "@someone"; + case "emoji": + return attr(node, "text") ?? attr(node, "shortName") ?? ""; + case "inlineCard": + case "blockCard": + return attr(node, "url") ?? ""; + case "status": + return attr(node, "text") ?? ""; + case "date": { + const timestamp = Number(attr(node, "timestamp")); + return Option.match(DateTime.make(timestamp), { + onNone: () => "", + onSome: (date) => DateTime.formatIsoDateUtc(date), + }); + } + default: + return inline(node.content); + } +} + +const indent = (text: string, prefix: string) => + text + .split("\n") + .map((line, index) => (index === 0 ? line : line === "" ? line : prefix + line)) + .join("\n"); + +function blocks(nodes: ReadonlyArray | undefined): string { + return (nodes ?? []) + .map(block) + .filter((text) => text !== "") + .join("\n\n"); +} + +function list(node: AdfNode, ordered: boolean): string { + const start = ordered ? Number(node.attrs?.["order"] ?? 1) || 1 : 1; + return (node.content ?? []) + .map((item, index) => { + const bullet = ordered ? `${start + index}. ` : "- "; + const done = + item.type === "taskItem" ? (attr(item, "state") === "DONE" ? "[x] " : "[ ] ") : ""; + // A nested list sits right under its item's text, so the item stays one tight list entry. + const body = + item.type === "taskItem" + ? inline(item.content) + : (item.content ?? []) + .map(block) + .filter((text) => text !== "") + .join("\n"); + return bullet + done + indent(body, " ".repeat(bullet.length)); + }) + .join("\n"); +} + +function table(node: AdfNode): string { + const rows = (node.content ?? []).map((row) => + (row.content ?? []).map((cell) => + blocks(cell.content).replaceAll("\n", " ").replaceAll("|", "\\|"), + ), + ); + const width = Math.max(0, ...rows.map((row) => row.length)); + if (width === 0) return ""; + const line = (cells: ReadonlyArray) => + `| ${Array.from({ length: width }, (_, index) => cells[index] ?? "").join(" | ")} |`; + const [head = [], ...body] = rows; + return [line(head), line(Array(width).fill("---")), ...body.map(line)].join("\n"); +} + +function block(node: AdfNode): string { + switch (node.type) { + case "paragraph": + return inline(node.content); + case "heading": + return `${"#".repeat(Math.min(Math.max(Number(node.attrs?.["level"]) || 1, 1), 6))} ${inline(node.content)}`; + case "bulletList": + case "taskList": + return list(node, false); + case "orderedList": + return list(node, true); + case "codeBlock": { + const code = (node.content ?? []).map((child) => child.text ?? "").join(""); + const ticks = fence(code, 3); + return `${ticks}${attr(node, "language") ?? ""}\n${code}\n${ticks}`; + } + case "blockquote": + case "panel": + return blocks(node.content) + .split("\n") + .map((line) => (line === "" ? ">" : `> ${line}`)) + .join("\n"); + case "rule": + return "---"; + case "table": + return table(node); + case "mediaSingle": + case "mediaGroup": + case "media": + return "_(attachment, open in Jira to view)_"; + case "expand": + case "nestedExpand": + return [attr(node, "title"), blocks(node.content)].filter(Boolean).join("\n\n"); + default: + return node.content === undefined ? inlineNode(node) : blocks(node.content); + } +} + +/** Nodes whose Markdown form is a stand-in, so writing that Markdown back would lose them. */ +const JIRA_ONLY = new Set([ + "media", + "mediaSingle", + "mediaGroup", + "mediaInline", + "mention", + "emoji", + "status", + "date", + "inlineCard", + "blockCard", + "embedCard", + "panel", + "expand", + "nestedExpand", + "extension", + "bodiedExtension", + "inlineExtension", + "layoutSection", + "decisionList", +]); + +export function hasJiraOnlyContent(document: unknown): boolean { + if (!isNode(document)) return false; + const visit = (node: AdfNode): boolean => + JIRA_ONLY.has(node.type) || + Number(node.attrs?.["colspan"] ?? 1) > 1 || + Number(node.attrs?.["rowspan"] ?? 1) > 1 || + (node.marks ?? []).some((mark) => mark.type !== "link" && !MARKDOWN_MARKS.has(mark.type)) || + (node.content ?? []).some((child) => isNode(child) && visit(child)); + return visit(document); +} + +const MARKDOWN_MARKS = new Set(["code", "strong", "em", "strike"]); + +/** A Jira document as Markdown; an empty or absent one is the empty string. */ +export function adfToMarkdown(document: unknown): string { + if (typeof document === "string") return document; + if (!isNode(document)) return ""; + return blocks(document.content).trim(); +} + +type Inline = AdfNode; + +function inlineFromMdast(node: Mdast.PhrasingContent, marks: ReadonlyArray): Inline[] { + const children = (extra: AdfMark) => + "children" in node + ? (node.children as Mdast.PhrasingContent[]).flatMap((child) => + inlineFromMdast(child, [...marks, extra]), + ) + : []; + switch (node.type) { + case "text": + return node.value === "" ? [] : [{ type: "text", text: node.value, ...withMarks(marks) }]; + case "inlineCode": + // Jira only lets code combine with a link. + return node.value === "" + ? [] + : [ + { + type: "text", + text: node.value, + ...withMarks([...marks.filter((mark) => mark.type === "link"), { type: "code" }]), + }, + ]; + case "strong": + return children({ type: "strong" }); + case "emphasis": + return children({ type: "em" }); + case "delete": + return children({ type: "strike" }); + case "link": + return children({ type: "link", attrs: { href: node.url } }); + case "image": + return [ + { + type: "text", + text: node.alt || node.url, + ...withMarks([...marks, { type: "link", attrs: { href: node.url } }]), + }, + ]; + case "break": + return [{ type: "hardBreak" }]; + case "html": + return node.value === "" ? [] : [{ type: "text", text: node.value, ...withMarks(marks) }]; + default: + return "children" in node + ? (node.children as Mdast.PhrasingContent[]).flatMap((child) => + inlineFromMdast(child, marks), + ) + : []; + } +} + +function withMarks(marks: ReadonlyArray): { marks?: AdfMark[] } { + if (marks.length === 0) return {}; + const code = marks.some((mark) => mark.type === "code"); + const kept = code ? marks.filter((mark) => mark.type === "code" || mark.type === "link") : marks; + return { marks: [...new Map(kept.map((mark) => [mark.type, mark])).values()] }; +} + +function paragraph(children: ReadonlyArray): AdfNode { + const content = children.flatMap((child) => inlineFromMdast(child, [])); + return content.length === 0 ? { type: "paragraph" } : { type: "paragraph", content }; +} + +function blockFromMdast(node: Mdast.RootContent): AdfNode[] { + switch (node.type) { + case "paragraph": + return [paragraph(node.children)]; + case "heading": + return [ + { + type: "heading", + attrs: { level: node.depth }, + content: paragraph(node.children).content ?? [], + }, + ]; + case "code": + return [ + { + type: "codeBlock", + ...(node.lang ? { attrs: { language: node.lang } } : {}), + ...(node.value === "" ? {} : { content: [{ type: "text", text: node.value }] }), + }, + ]; + case "blockquote": + return [{ type: "blockquote", content: node.children.flatMap(blockFromMdast) }]; + case "list": + return [ + { + type: node.ordered ? "orderedList" : "bulletList", + ...(node.ordered && node.start != null && node.start !== 1 + ? { attrs: { order: node.start } } + : {}), + content: node.children.map((item) => { + const content = item.children.flatMap(blockFromMdast); + const checkbox = item.checked == null ? null : item.checked ? "[x] " : "[ ] "; + const [first, ...rest] = content; + // A list item must open with a paragraph in Jira. + const opening: AdfNode = + first?.type === "paragraph" + ? checkbox === null + ? first + : { + ...first, + content: [{ type: "text", text: checkbox }, ...(first.content ?? [])], + } + : { + type: "paragraph", + ...(checkbox === null ? {} : { content: [{ type: "text", text: checkbox }] }), + }; + return { + type: "listItem", + content: first?.type === "paragraph" ? [opening, ...rest] : [opening, ...content], + }; + }), + }, + ]; + case "thematicBreak": + return [{ type: "rule" }]; + case "table": + return [ + { + type: "table", + content: node.children.map((row, rowIndex) => ({ + type: "tableRow", + content: row.children.map((cell) => ({ + type: rowIndex === 0 ? "tableHeader" : "tableCell", + content: [paragraph(cell.children)], + })), + })), + }, + ]; + case "html": + return node.value.trim() === "" + ? [] + : [{ type: "paragraph", content: [{ type: "text", text: node.value }] }]; + default: + return []; + } +} + +/** Reference links as the inline links they stand for, since ADF has no definitions. */ +function resolveReferences(node: Mdast.Nodes, definitions: ReadonlyMap): void { + if (!("children" in node)) return; + node.children = node.children.map((child) => { + const url = "identifier" in child ? definitions.get(child.identifier) : undefined; + if (child.type === "linkReference" && url !== undefined) + return { type: "link", url, children: child.children }; + if (child.type === "imageReference" && url !== undefined) + return { type: "image", url, alt: child.alt ?? null }; + return child; + }) as typeof node.children; + for (const child of node.children) resolveReferences(child, definitions); +} + +/** Markdown as a Jira document, the way Jira's own editor would have stored it. */ +export function markdownToAdf(markdown: string) { + const tree = fromMarkdown(markdown, { + extensions: [gfm()], + mdastExtensions: [gfmFromMarkdown()], + }); + // A definition anywhere applies to the whole document; the first one of an identifier wins. + const definitions = new Map(); + const collect = (node: Mdast.Nodes): void => { + if (node.type === "definition" && !definitions.has(node.identifier)) + definitions.set(node.identifier, node.url); + if ("children" in node) node.children.forEach(collect); + }; + collect(tree); + resolveReferences(tree, definitions); + return { type: "doc", version: 1, content: tree.children.flatMap(blockFromMdast) }; +} diff --git a/packages/issue-tracker-jira/src/shared/issueUrl.ts b/packages/issue-tracker-jira/src/shared/issueUrl.ts new file mode 100644 index 0000000000000..f581cac476ecb --- /dev/null +++ b/packages/issue-tracker-jira/src/shared/issueUrl.ts @@ -0,0 +1,19 @@ +import { IssueTrackerKind } from "@t3tools/contracts"; + +export const JIRA_KIND = IssueTrackerKind.make("jira"); +/** Every Jira Cloud site is a subdomain of this; the site itself is the link's workspace. */ +export const JIRA_HOST = "atlassian.net"; + +const SITE = /^([a-z0-9][a-z0-9-]*)\.atlassian\.net$/; +const KEY = /^([A-Z][A-Z0-9_]*)-[1-9][0-9]*$/; + +/** `https://.atlassian.net/browse/-`, keeping the site. */ +export function parseJiraIssueUrl(url: URL) { + if (url.protocol !== "https:" || url.port !== "") return null; + const site = SITE.exec(url.hostname.toLowerCase())?.[1]; + const [, resource, key, ...rest] = url.pathname.split("/"); + if (site === undefined || resource !== "browse" || key === undefined) return null; + if (rest.some((segment) => segment !== "")) return null; + const scope = KEY.exec(key)?.[1]; + return scope === undefined ? null : { host: JIRA_HOST, workspace: site, scope, key }; +} diff --git a/packages/issue-tracker-jira/tsconfig.json b/packages/issue-tracker-jira/tsconfig.json new file mode 100644 index 0000000000000..374bac55202dd --- /dev/null +++ b/packages/issue-tracker-jira/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["src"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e003246a26e8c..779bfdab5c5b4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -877,6 +877,9 @@ importers: '@napi-rs/keyring': specifier: ^1.3.0 version: 1.3.0 + '@t3tools/issue-tracker-jira': + specifier: workspace:* + version: link:../../packages/issue-tracker-jira '@t3tools/issue-tracker-linear': specifier: workspace:* version: link:../../packages/issue-tracker-linear @@ -1525,6 +1528,9 @@ importers: '@t3tools/contracts': specifier: workspace:* version: link:../contracts + '@t3tools/issue-tracker-jira': + specifier: workspace:* + version: link:../issue-tracker-jira '@t3tools/issue-tracker-linear': specifier: workspace:* version: link:../issue-tracker-linear @@ -1662,6 +1668,40 @@ importers: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + packages/issue-tracker-jira: + dependencies: + '@t3tools/contracts': + specifier: workspace:* + version: link:../contracts + '@t3tools/source-control-core': + specifier: workspace:* + version: link:../source-control-core + effect: + specifier: 4.1.3 + version: 4.1.3 + mdast-util-from-markdown: + specifier: 2.0.3 + version: 2.0.3(supports-color@8.1.1) + mdast-util-gfm: + specifier: 3.1.0 + version: 3.1.0(supports-color@8.1.1) + micromark-extension-gfm: + specifier: 3.0.0 + version: 3.0.0 + devDependencies: + '@effect/vitest': + specifier: 4.1.2 + version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.3)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + '@types/mdast': + specifier: ^4.0.4 + version: 4.0.4 + '@types/node': + specifier: 24.12.4 + version: 24.12.4 + vite-plus: + specifier: 1.4.0 + version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + packages/issue-tracker-linear: dependencies: '@t3tools/contracts': diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index b564001c19290..94e879b88cff7 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -40,6 +40,7 @@ const workspaceFiles = [ "packages/provider-kiro/package.json", "packages/provider-muse/package.json", "packages/provider-opencode/package.json", + "packages/issue-tracker-jira/package.json", "packages/issue-tracker-linear/package.json", "packages/secret-provider-core/package.json", "packages/secret-provider-definitions/package.json",