Compare commits

..

1 Commits

Author SHA1 Message Date
Kit Langton ec126b1963 fix(tui): sync Mermaid renderer fixes 2026-08-08 21:37:36 -04:00
70 changed files with 2576 additions and 1307 deletions
+1
View File
@@ -577,6 +577,7 @@
"dependencies": {
"@opencode-ai/plugin": "workspace:*",
"@opentui/core": "catalog:",
"entities": "7.0.1",
"string-width": "catalog:",
},
"devDependencies": {
@@ -1,4 +1,4 @@
import type { FormAnswer, IntegrationMethod, IntegrationOauthConnectOutput } from "@opencode-ai/client/promise"
import type { IntegrationMethod, IntegrationOauthConnectOutput } from "@opencode-ai/client/promise"
import { Button } from "@opencode-ai/ui/button"
import { useDialog } from "@opencode-ai/ui/context/dialog"
import { Dialog } from "@opencode-ai/ui/dialog"
@@ -40,8 +40,6 @@ import { decode64 } from "@/utils/base64"
const CUSTOM_ID = "_custom"
type ConnectMethod = Extract<IntegrationMethod, { type: "key" | "oauth" }>
type IntegrationForm = NonNullable<ConnectMethod["form"]>[number]
type StringForm = Extract<IntegrationForm, { type: "string" }>
export function useProviderConnectController(options: { onBack?: () => void } = {}) {
const [store, setStore] = createStore({ selected: undefined as string | undefined })
@@ -436,16 +434,16 @@ function ProviderConnection(props: {
const [store, setStore] = createStore({
methodIndex: undefined as undefined | number,
authorization: undefined as undefined | IntegrationOauthConnectOutput["data"],
formAnswer: undefined as FormAnswer | undefined,
state: "pending" as undefined | "pending" | "complete" | "error" | "form",
promptInputs: undefined as undefined | Record<string, string>,
state: "pending" as undefined | "pending" | "complete" | "error" | "prompt",
error: undefined as string | undefined,
})
type Action =
| { type: "method.select"; index: number }
| { type: "method.reset" }
| { type: "auth.form" }
| { type: "auth.answer"; answer: FormAnswer | undefined }
| { type: "auth.prompt" }
| { type: "auth.inputs"; inputs: Record<string, string> }
| { type: "auth.pending" }
| { type: "auth.complete"; authorization: IntegrationOauthConnectOutput["data"] }
| { type: "auth.error"; error: string }
@@ -456,7 +454,7 @@ function ProviderConnection(props: {
if (action.type === "method.select") {
draft.methodIndex = action.index
draft.authorization = undefined
draft.formAnswer = undefined
draft.promptInputs = undefined
draft.state = undefined
draft.error = undefined
return
@@ -464,18 +462,18 @@ function ProviderConnection(props: {
if (action.type === "method.reset") {
draft.methodIndex = undefined
draft.authorization = undefined
draft.formAnswer = undefined
draft.promptInputs = undefined
draft.state = undefined
draft.error = undefined
return
}
if (action.type === "auth.form") {
draft.state = "form"
if (action.type === "auth.prompt") {
draft.state = "prompt"
draft.error = undefined
return
}
if (action.type === "auth.answer") {
draft.formAnswer = action.answer
if (action.type === "auth.inputs") {
draft.promptInputs = action.inputs
draft.state = undefined
draft.error = undefined
return
@@ -533,7 +531,7 @@ function ProviderConnection(props: {
return fallback
}
async function selectMethod(index: number, answer?: FormAnswer) {
async function selectMethod(index: number, inputs?: Record<string, string>) {
if (timer.current !== undefined) {
clearTimeout(timer.current)
timer.current = undefined
@@ -542,17 +540,9 @@ function ProviderConnection(props: {
const method = methods()[index]
dispatch({ type: "method.select", index })
if (method.form?.length && !answer) {
dispatch({ type: "auth.form" })
return
}
if (method.type === "key") {
dispatch({ type: "auth.answer", answer })
return
}
if (method.type === "oauth") {
if (method.form?.some((field) => field.type !== "string")) {
dispatch({ type: "auth.error", error: "This authentication form contains unsupported fields" })
if (method.prompts?.length && !inputs) {
dispatch({ type: "auth.prompt" })
return
}
dispatch({ type: "auth.pending" })
@@ -560,7 +550,7 @@ function ProviderConnection(props: {
.api.integration.oauth.connect({
integrationID: props.provider,
methodID: method.id,
...(answer ? { answer } : {}),
inputs: inputs ?? {},
location: location(),
})
.then((x) => {
@@ -574,42 +564,41 @@ function ProviderConnection(props: {
}
}
function AuthFormView() {
function AuthPromptsView() {
const [formStore, setFormStore] = createStore({
value: {} as Record<string, string>,
index: 0,
})
const fields = createMemo<StringForm[]>(() => {
const prompts = createMemo(() => {
const value = method()
return (value?.form ?? []).flatMap((field) => (field.type === "string" ? [field] : []))
return value?.type === "oauth" ? (value.prompts ?? []) : []
})
const matches = (field: StringForm, value: Record<string, string>) => {
return (field.when ?? []).every((condition) => {
const actual = value[condition.key]
if (actual === undefined) return false
return condition.op === "eq" ? actual === condition.value : actual !== condition.value
})
const matches = (prompt: NonNullable<ReturnType<typeof prompts>[number]>, value: Record<string, string>) => {
if (!prompt.when) return true
const actual = value[prompt.when.key]
if (actual === undefined) return false
return prompt.when.op === "eq" ? actual === prompt.when.value : actual !== prompt.when.value
}
const current = createMemo(() => {
const all = fields()
const index = all.findIndex((field, index) => index >= formStore.index && matches(field, formStore.value))
const all = prompts()
const index = all.findIndex((prompt, index) => index >= formStore.index && matches(prompt, formStore.value))
if (index === -1) return
return {
index,
field: all[index],
prompt: all[index],
}
})
const valid = createMemo(() => {
const item = current()
if (!item || item.field.options) return false
if (!item.field.required) return true
return (formStore.value[item.field.key] ?? "").trim().length > 0
if (!item || item.prompt.type !== "text") return false
const value = formStore.value[item.prompt.key] ?? ""
return value.trim().length > 0
})
async function next(index: number, value: Record<string, string>) {
if (store.methodIndex === undefined) return
const next = fields().findIndex((field, i) => i > index && matches(field, value))
const next = prompts().findIndex((prompt, i) => i > index && matches(prompt, value))
if (next !== -1) {
setFormStore("index", next)
return
@@ -620,60 +609,60 @@ function ProviderConnection(props: {
async function handleSubmit(e: SubmitEvent) {
e.preventDefault()
const item = current()
if (!item || item.field.options) return
if (!item || item.prompt.type !== "text") return
if (!valid()) return
await next(item.index, formStore.value)
}
const item = () => current()
const text = createMemo(() => {
const field = item()?.field
if (!field || field.options) return
return field
const prompt = item()?.prompt
if (!prompt || prompt.type !== "text") return
return prompt
})
const select = createMemo(() => {
const field = item()?.field
if (!field?.options) return
return field
const prompt = item()?.prompt
if (!prompt || prompt.type !== "select") return
return prompt
})
return (
<form onSubmit={handleSubmit} class="flex flex-col items-start gap-4">
<Switch>
<Match when={item()?.field.options === undefined}>
<Match when={item()?.prompt.type === "text"}>
<TextField
type="text"
label={text()?.title ?? ""}
label={text()?.message ?? ""}
placeholder={text()?.placeholder}
value={text() ? (formStore.value[text()!.key] ?? "") : ""}
onChange={(value) => {
const field = text()
if (!field) return
setFormStore("value", field.key, value)
const prompt = text()
if (!prompt) return
setFormStore("value", prompt.key, value)
}}
/>
<Button class="w-auto" type="submit" size="large" variant="primary" disabled={!valid()}>
{language.t("common.continue")}
</Button>
</Match>
<Match when={item()?.field.options !== undefined}>
<Match when={item()?.prompt.type === "select"}>
<div class="w-full flex flex-col gap-1.5">
<div class="text-14-regular text-text-base">{select()?.title}</div>
<div class="text-14-regular text-text-base">{select()?.message}</div>
<div>
<List
class="px-3"
items={select()?.options ?? []}
key={(x) => x.value}
current={select()?.options?.find((x) => x.value === formStore.value[select()!.key])}
current={select()?.options.find((x) => x.value === formStore.value[select()!.key])}
onSelect={(value) => {
if (!value) return
const field = select()
if (!field) return
const prompt = select()
if (!prompt) return
const nextValue = {
...formStore.value,
[field.key]: value.value,
[prompt.key]: value.value,
}
setFormStore("value", field.key, value.value)
setFormStore("value", prompt.key, value.value)
void next(item()!.index, nextValue)
}}
>
@@ -683,7 +672,7 @@ function ProviderConnection(props: {
<div class="w-2.5 h-0.5 ml-0 bg-icon-strong-base hidden" data-slot="list-item-extra-icon" />
</div>
<span>{option.label}</span>
<span class="text-14-regular text-text-weak">{option.description}</span>
<span class="text-14-regular text-text-weak">{option.hint}</span>
</div>
)}
</List>
@@ -831,7 +820,6 @@ function ProviderConnection(props: {
integrationID: props.provider,
location: location(),
key: apiKey,
...(store.formAnswer ? { answer: store.formAnswer } : {}),
})
await complete()
}
@@ -1155,8 +1143,8 @@ function ProviderConnection(props: {
</div>
</div>
</Match>
<Match when={store.state === "form"}>
<AuthFormView />
<Match when={store.state === "prompt"}>
<AuthPromptsView />
</Match>
<Match when={store.state === "error"}>
<div class="text-14-regular text-text-base">
+2 -1
View File
@@ -662,12 +662,13 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
integrationID: server.integrationID,
location: { directory: key },
})
const method = integration.data?.methods.find((item) => item.type === "oauth" && !item.form?.length)
const method = integration.data?.methods.find((item) => item.type === "oauth" && !item.prompts?.length)
if (!method || method.type !== "oauth")
throw new Error(`MCP server ${name} requires an interactive authentication form`)
const attempt = await serverSDK.api.integration.oauth.connect({
integrationID: server.integrationID,
methodID: method.id,
inputs: {},
location: { directory: key },
})
platform.openLink(attempt.data.url)
@@ -50,7 +50,7 @@ const login = Effect.fn("cli.console.login.run")(function* (timeline: TimelineHo
{
integrationID,
methodID: method.id,
...(server ? { answer: { server } } : {}),
inputs: server ? { server } : {},
location,
},
{ signal },
@@ -32,7 +32,7 @@ export default Runtime.handler(
return yield* Effect.fail(new Error(`MCP server "${input.name}" is not an OAuth-capable remote server`))
const started = yield* Effect.promise(() =>
client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, location }),
client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, inputs: {}, location }),
)
const attempt = started.data
if (attempt.mode === "code")
+2 -3
View File
@@ -23,9 +23,9 @@ import type { Shell } from "@opencode-ai/schema/shell"
import type { DateTime } from "effect"
import type { Provider } from "@opencode-ai/schema/provider"
import type { Integration } from "@opencode-ai/schema/integration"
import type { Form } from "@opencode-ai/schema/form"
import type { Mcp } from "@opencode-ai/schema/mcp"
import type { Credential } from "@opencode-ai/schema/credential"
import type { Form } from "@opencode-ai/schema/form"
import type { Permission } from "@opencode-ai/schema/permission"
import type { PermissionSaved } from "@opencode-ai/schema/permission-saved"
import type { FileSystem } from "@opencode-ai/schema/filesystem"
@@ -1054,7 +1054,6 @@ export type Endpoint10_3Input = {
readonly integrationID: Integration.ID
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
readonly key: string
readonly answer?: Form.Answer | undefined
readonly label?: string | undefined
}
export type Endpoint10_3Output = void
@@ -1066,7 +1065,7 @@ export type Endpoint10_4Input = {
readonly integrationID: Integration.ID
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
readonly methodID: Integration.MethodID
readonly answer?: Form.Answer | undefined
readonly inputs: { readonly [x: string]: string }
readonly label?: string | undefined
}
export type Endpoint10_4Output = { readonly location: Location.Info; readonly data: Integration.Attempt }
@@ -717,7 +717,7 @@ const Endpoint10_3 = (raw: RawClient["server.integration"]) => (input: Endpoint1
raw["integration.connect.key"]({
params: { integrationID: input["integrationID"] },
query: { location: input["location"] },
payload: { key: input["key"], answer: input["answer"], label: input["label"] },
payload: { key: input["key"], label: input["label"] },
}).pipe(Effect.mapError(mapClientError)),
)
@@ -726,7 +726,7 @@ const Endpoint10_4 = (raw: RawClient["server.integration"]) => (input: Endpoint1
raw["integration.oauth.connect"]({
params: { integrationID: input["integrationID"] },
query: { location: input["location"] },
payload: { methodID: input["methodID"], answer: input["answer"], label: input["label"] },
payload: { methodID: input["methodID"], inputs: input["inputs"], label: input["label"] },
}).pipe(Effect.mapError(mapClientError)),
)
@@ -1032,7 +1032,7 @@ export function make(options: ClientOptions) {
method: "POST",
path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/key`,
query: { location: input["location"] },
body: { key: input["key"], answer: input["answer"], label: input["label"] },
body: { key: input["key"], label: input["label"] },
successStatus: 204,
declaredStatuses: [400, 401],
empty: true,
@@ -1047,7 +1047,7 @@ export function make(options: ClientOptions) {
method: "POST",
path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/oauth`,
query: { location: input["location"] },
body: { methodID: input["methodID"], answer: input["answer"], label: input["label"] },
body: { methodID: input["methodID"], inputs: input["inputs"], label: input["label"] },
successStatus: 200,
declaredStatuses: [400, 401],
empty: false,
+80 -70
View File
@@ -195,18 +195,12 @@ export type ProviderInfo = {
body?: { [x: string]: any }
}
export type FormWhen = {
key: string
op: "eq" | "neq"
value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean
}
export type FormOption = { value: string; label: string; description?: string }
export type FormExternalField = { key: string; type: "external"; url: string; title?: string; description?: string }
export type IntegrationWhen = { key: string; op: "eq" | "neq"; value: string }
export type IntegrationCommandMethod = { id: string; type: "command"; label: string; command: Array<string> }
export type IntegrationKeyMethod = { type: "key"; label?: string }
export type IntegrationEnvMethod = { type: "env"; names: Array<string> }
export type ConnectionCredentialInfo = { type: "credential"; id: string; label: string }
@@ -291,6 +285,16 @@ export type ProjectDirectory = { directory: string; strategy?: string }
export type FormMetadata = { [x: string]: JsonValue }
export type FormWhen = {
key: string
op: "eq" | "neq"
value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean
}
export type FormOption = { value: string; label: string; description?: string }
export type FormExternalField = { key: string; type: "external"; url: string; title?: string; description?: string }
export type FormValue = string | number | boolean | Array<string>
export type PermissionSource = { type: "tool"; messageID: string; id: string }
@@ -1273,6 +1277,45 @@ export type ModelCost = {
cache: { read: MoneyUSDPerMillionTokens; write: MoneyUSDPerMillionTokens }
}
export type IntegrationTextPrompt = {
type: "text"
key: string
message: string
placeholder?: string
when?: IntegrationWhen
}
export type IntegrationSelectPrompt = {
type: "select"
key: string
message: string
options: Array<{ label: string; value: string; hint?: string }>
when?: IntegrationWhen
}
export type ConnectionInfo = ConnectionCredentialInfo | ConnectionEnvInfo
export type McpServer = {
name: string
status: McpStatusConnected | McpStatusPending | McpStatusDisabled | McpStatusFailed | McpStatusNeedsAuth
integrationID?: string
}
export type McpResourceCatalog = { resources: Array<McpResource>; templates: Array<McpResourceTemplate> }
export type Project = {
id: string
canonical: string
vcs?: ProjectVcs
name?: string
icon?: ProjectIcon
commands?: ProjectCommands
time: ProjectTime
sandboxes: Array<string>
}
export type ProjectDirectories = Array<ProjectDirectory>
export type FormNumberField = {
key: string
title?: string
@@ -1338,29 +1381,6 @@ export type FormMultiselectField = {
default?: Array<string>
}
export type ConnectionInfo = ConnectionCredentialInfo | ConnectionEnvInfo
export type McpServer = {
name: string
status: McpStatusConnected | McpStatusPending | McpStatusDisabled | McpStatusFailed | McpStatusNeedsAuth
integrationID?: string
}
export type McpResourceCatalog = { resources: Array<McpResource>; templates: Array<McpResourceTemplate> }
export type Project = {
id: string
canonical: string
vcs?: ProjectVcs
name?: string
icon?: ProjectIcon
commands?: ProjectCommands
time: ProjectTime
sandboxes: Array<string>
}
export type ProjectDirectories = Array<ProjectDirectory>
export type FormAnswer = { [x: string]: FormValue }
export type PermissionRequest = {
@@ -1644,6 +1664,13 @@ export type ModelInfo = {
limit: { context: number; input?: number; output: number }
}
export type IntegrationOAuthMethod = {
id: string
type: "oauth"
label: string
prompts?: Array<IntegrationTextPrompt | IntegrationSelectPrompt>
}
export type FormField =
| FormStringField
| FormNumberField
@@ -1897,9 +1924,15 @@ export type SessionMessageAssistantTool = {
time: { created: number; ran?: number; completed?: number }
}
export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationEnvMethod
export type FormFields = [FormField, ...Array<FormField>]
export type FormFields3 = [FormField1, ...Array<FormField1>]
export type FormFields1 = [FormField1, ...Array<FormField1>]
export type SessionPendingInfo = SessionPendingUser | SessionPendingSynthetic | SessionPendingCompaction
@@ -1921,13 +1954,16 @@ export type SessionMessageAssistant = {
retry?: SessionMessageAssistantRetry
}
export type IntegrationOAuthMethod = { id: string; type: "oauth"; label: string; form?: FormFields }
export type IntegrationKeyMethod = { type: "key"; label?: string; form?: FormFields }
export type IntegrationInfo = {
id: string
name: string
methods: Array<IntegrationMethod>
connections: Array<ConnectionInfo>
}
export type FormInfo = { id: string; sessionID: string; title: string; metadata?: FormMetadata; fields: FormFields }
export type FormInfo1 = { id: string; sessionID: string; title: string; metadata?: FormMetadata1; fields: FormFields3 }
export type FormInfo1 = { id: string; sessionID: string; title: string; metadata?: FormMetadata1; fields: FormFields1 }
export type SessionInputAdmitted = {
id: string
@@ -1950,12 +1986,6 @@ export type SessionMessageInfo =
| SessionMessageAssistant
| SessionMessageCompaction
export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationEnvMethod
export type FormCreated = {
id: string
created: number
@@ -2016,13 +2046,6 @@ export type SessionMessagesResponse = {
cursor: { previous?: string | null; next?: string | null }
}
export type IntegrationInfo = {
id: string
name: string
methods: Array<IntegrationMethod>
connections: Array<ConnectionInfo>
}
export type V2Event =
| ModelsDevRefreshed
| IntegrationUpdated
@@ -4022,21 +4045,8 @@ export type IntegrationConnectKeyInput = {
readonly location?: {
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
}["location"]
readonly key: {
readonly key: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly label?: string | undefined
}["key"]
readonly answer?: {
readonly key: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly label?: string | undefined
}["answer"]
readonly label?: {
readonly key: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly label?: string | undefined
}["label"]
readonly key: { readonly key: string; readonly label?: string | undefined }["key"]
readonly label?: { readonly key: string; readonly label?: string | undefined }["label"]
}
export type IntegrationConnectKeyOutput = void
@@ -4048,17 +4058,17 @@ export type IntegrationOauthConnectInput = {
}["location"]
readonly methodID: {
readonly methodID: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly inputs: { readonly [x: string]: string }
readonly label?: string | undefined
}["methodID"]
readonly answer?: {
readonly inputs: {
readonly methodID: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly inputs: { readonly [x: string]: string }
readonly label?: string | undefined
}["answer"]
}["inputs"]
readonly label?: {
readonly methodID: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly inputs: { readonly [x: string]: string }
readonly label?: string | undefined
}["label"]
}
-43
View File
@@ -148,49 +148,6 @@ test("experimental wellknown integration add uses the public HTTP contract", asy
expect(await request?.json()).toEqual({ url: "https://example.com" })
})
test("integration connections optionally submit a form answer", async () => {
const requests: Request[] = []
const client = OpenCode.make({
baseUrl: "http://localhost:3000",
fetch: async (input, init) => {
const request = input instanceof Request ? input : new Request(input, init)
requests.push(request)
if (request.url.endsWith("/connect/key")) return new Response(null, { status: 204 })
return Response.json({
location: { directory: "/tmp/project", project: { id: "proj_test", directory: "/tmp/project" } },
data: {
attemptID: "con_test",
url: "https://example.com/authorize",
instructions: "Authorize",
mode: "auto",
time: { created: 1, expires: 2 },
},
})
},
})
await client.integration.connect.key({
integrationID: "cloudflare-workers-ai",
key: "secret",
answer: { accountId: "account" },
})
await client.integration.oauth.connect({
integrationID: "github-copilot",
methodID: "device",
answer: { deploymentType: "enterprise", enabled: true, scopes: ["read:user"] },
})
await client.integration.connect.key({ integrationID: "openai", key: "secret" })
await client.integration.oauth.connect({ integrationID: "openai", methodID: "device" })
expect(await requests[0].json()).toEqual({ key: "secret", answer: { accountId: "account" } })
expect(await requests[1].json()).toEqual({
methodID: "device",
answer: { deploymentType: "enterprise", enabled: true, scopes: ["read:user"] },
})
expect(await requests[2].json()).toEqual({ key: "secret" })
expect(await requests[3].json()).toEqual({ methodID: "device" })
})
test("health.stop sends exact replacement identity", async () => {
let request: Request | undefined
const client = OpenCode.make({
+5 -5
View File
@@ -180,7 +180,7 @@ export const layer = Layer.effect(
Effect.gen(function* () {
const entry = yield* find(input.id)
if (entry.state.status !== "pending") return yield* new AlreadySettledError({ id: input.id })
const invalid = validateAnswer(entry.form.fields, input.answer)
const invalid = validateAnswer(entry.form, input.answer)
if (invalid) return yield* new InvalidAnswerError({ id: input.id, message: invalid })
const next: TerminalState = { status: "answered", answer: input.answer }
yield* bus.publish(Form.Event.Replied, {
@@ -227,12 +227,12 @@ export const locationLayer = layer
export const node = makeLocationNode({ service: Service, layer, deps: [Bus.node] })
export function validateAnswer(form: ReadonlyArray<Form.Field>, answer: Answer) {
const fields = new Map(form.map((field) => [field.key, field] as const))
function validateAnswer(form: Info, answer: Answer) {
const fields = new Map(form.fields.map((field) => [field.key, field] as const))
for (const key of Object.keys(answer)) {
if (!fields.has(key)) return `Unknown form field: ${key}`
}
for (const field of form) {
for (const field of form.fields) {
const value = answer[field.key]
if (field.type === "external") {
if (value !== true) return `External form field must be acknowledged: ${field.key}`
@@ -268,7 +268,7 @@ function matches(when: Form.When, value: Form.Value | undefined) {
// carry a value matching that field's type, and use a declared option when the field's options
// are closed. Rejecting these at creation surfaces authoring mistakes to the caller instead of
// silently never matching.
export function validateFields(fields: ReadonlyArray<Form.Field>) {
function validateFields(fields: ReadonlyArray<Form.Field>) {
if (fields.length === 0) return "Form must have at least one field"
const earlier = new Map<string, InputField>()
const keys = new Set<string>()
+1 -6
View File
@@ -70,11 +70,6 @@ type UsableModel = RemoteModel & {
}
}
export const Package = {
OpenAI: "@ai-sdk/github-copilot",
Anthropic: "@ai-sdk/github-copilot/anthropic",
} as const
export async function get(baseURL: string, headers: RequestInit["headers"], existing: readonly Model.Info[]) {
const response = await fetch(`${baseURL}/models`, {
headers,
@@ -146,7 +141,7 @@ function build(id: Model.ID, remote: UsableModel, baseURL: string, previous?: Mo
providerID: Provider.ID.githubCopilot,
family: previous?.family ?? Model.Family.make(remote.capabilities.family),
name: previous?.name ?? remote.name,
package: Provider.aisdk(messages ? Package.Anthropic : Package.OpenAI),
package: Provider.aisdk(messages ? "@ai-sdk/anthropic" : "@ai-sdk/github-copilot"),
settings: Provider.mergeOverlay(previous?.settings, {
baseURL: messages ? `${baseURL}/v1` : baseURL,
...(endpoint ? { endpoint } : {}),
+22 -27
View File
@@ -24,7 +24,6 @@ import { Bus } from "./bus"
import { IntegrationConnection } from "./integration/connection"
import { AppProcess } from "@opencode-ai/util/process"
import { ChildProcess } from "effect/unstable/process"
import { Form } from "./form"
export const ID = Integration.ID
export type ID = Integration.ID
@@ -35,6 +34,18 @@ export type MethodID = Integration.MethodID
export const AttemptID = Integration.AttemptID
export type AttemptID = typeof AttemptID.Type
export const When = Integration.When
export type When = Integration.When
export const TextPrompt = Integration.TextPrompt
export type TextPrompt = Integration.TextPrompt
export const SelectPrompt = Integration.SelectPrompt
export type SelectPrompt = Integration.SelectPrompt
export const Prompt = Integration.Prompt
export type Prompt = Integration.Prompt
export const OAuthMethod = Integration.OAuthMethod
export type OAuthMethod = Integration.OAuthMethod
@@ -53,6 +64,9 @@ export type Method = Integration.Method
export const Info = Integration.Info
export type Info = Integration.Info
export const Inputs = Integration.Inputs
export type Inputs = Integration.Inputs
export type OAuthAuthorization = {
readonly url: string
readonly instructions: string
@@ -71,7 +85,7 @@ export type OAuthAuthorization = {
export interface OAuthImplementation {
readonly integrationID: ID
readonly method: OAuthMethod
readonly authorize: (answer: Form.Answer) => Effect.Effect<OAuthAuthorization, unknown, Scope.Scope>
readonly authorize: (inputs: Inputs) => Effect.Effect<OAuthAuthorization, unknown, Scope.Scope>
readonly refresh?: (credential: Credential.OAuth) => Effect.Effect<Credential.OAuth, unknown>
readonly label?: (credential: Credential.OAuth) => string | undefined
}
@@ -161,8 +175,6 @@ export interface Interface extends State.Transformable<Draft> {
readonly integrationID: ID
/** Secret entered by the user. */
readonly key: string
/** Values collected from the method's form fields. */
readonly answer?: Form.Answer
/** User-facing label for the stored credential. */
readonly label?: string
}) => Effect.Effect<void, AuthorizationError>
@@ -179,7 +191,7 @@ export interface Interface extends State.Transformable<Draft> {
readonly connect: (input: {
readonly integrationID: ID
readonly methodID: MethodID
readonly answer?: Form.Answer
readonly inputs: Inputs
readonly label?: string
}) => Effect.Effect<Attempt, AuthorizationError>
/** Returns the current state of an OAuth attempt. */
@@ -344,7 +356,7 @@ const layer = Layer.effect(
return [...credentials, ...env]
}
const project = (entry: Entry, connections: IntegrationConnection.Info[]): Info =>
const project = (entry: Entry, connections: IntegrationConnection.Info[]) =>
Info.make({
id: entry.ref.id,
name: entry.ref.name,
@@ -535,20 +547,15 @@ const layer = Layer.effect(
const connectOAuth = Effect.fn("Integration.oauth.connect")(function* (input: {
readonly integrationID: ID
readonly methodID: MethodID
readonly answer?: Form.Answer
readonly inputs: Inputs
readonly label?: string
}) {
const method = state.get().integrations.get(input.integrationID)?.implementations.get(input.methodID)
if (!method) {
return yield* Effect.die(new Error(`OAuth method not found: ${input.integrationID}/${input.methodID}`))
}
const answer = input.answer ?? {}
if (method.method.form) {
const invalid = Form.validateFields(method.method.form) ?? Form.validateAnswer(method.method.form, answer)
if (invalid) return yield* new AuthorizationError({ cause: new Error(invalid) })
}
const attemptScope = yield* Scope.fork(scope)
const authorization = yield* authorize(method.authorize(answer)).pipe(
const authorization = yield* authorize(method.authorize(input.inputs)).pipe(
Scope.provide(attemptScope),
Effect.onExit((exit) => (Exit.isFailure(exit) ? Scope.close(attemptScope, exit) : Effect.void)),
)
@@ -692,24 +699,12 @@ const layer = Layer.effect(
const method = state
.get()
.integrations.get(input.integrationID)
?.methods.find((method) => method.type === "key")
?.methods.some((method) => method.type === "key")
if (!method) return yield* Effect.die(new Error(`Key method not found: ${input.integrationID}`))
const answer = input.answer ?? {}
if (method.type === "key" && method.form) {
const invalid = Form.validateFields(method.form) ?? Form.validateAnswer(method.form, answer)
if (invalid) return yield* new AuthorizationError({ cause: new Error(invalid) })
}
if (method.type === "key" && !method.form && Object.keys(answer).length > 0) {
return yield* new AuthorizationError({ cause: new Error("Key method does not accept a form answer") })
}
yield* credentials.create({
integrationID: input.integrationID,
label: input.label,
value: Credential.Key.make({
type: "key",
key: input.key,
...(Object.keys(answer).length > 0 ? { configuration: answer } : {}),
}),
value: Credential.Key.make({ type: "key", key: input.key }),
})
yield* bus.publish(Integration.Event.ConnectionUpdated, { integrationID: input.integrationID })
yield* bus.publish(Integration.Event.Updated, {})
+1 -3
View File
@@ -149,7 +149,6 @@ export const fromCatalogModel = (
})
const packageName = Provider.packageName(resolved.package)
const key = apiKey(resolved, credential)
const configuration = credential?.type === "key" ? credential.configuration : undefined
if (Provider.isAISDK(resolved.package) && packageName === "@ai-sdk/openai") {
return Effect.succeed(
@@ -176,7 +175,7 @@ export const fromCatalogModel = (
.model({ id: resolved.modelID ?? resolved.id, compatibility: resolved.compatibility }),
)
}
const configured = { ...resolved.settings, ...credential?.metadata, ...configuration }
const configured = { ...resolved.settings, ...credential?.metadata }
const mapping = Provider.isAISDK(resolved.package)
? AISDKNative.map({
packageName,
@@ -191,7 +190,6 @@ export const fromCatalogModel = (
draft.settings = Provider.mergeOverlay(draft.settings, {
...nativeCredentialSettings(resolved.package ?? "", credential),
...credential?.metadata,
...configuration,
})
})
return dependencies.loadAISDK(runtime).pipe(Effect.mapError(() => unsupported(resolved)))
+7 -8
View File
@@ -190,7 +190,6 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
integration.connection.key({
integrationID: Integration.ID.make(input.integrationID),
key: input.key,
answer: input.answer,
label: input.label,
}),
},
@@ -200,7 +199,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
integration.oauth.connect({
integrationID: Integration.ID.make(input.integrationID),
methodID: Integration.MethodID.make(input.methodID),
answer: input.answer,
inputs: input.inputs,
label: input.label,
}),
),
@@ -261,7 +260,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
update: (id, update) => draft.update(Integration.ID.make(id), update),
remove: (id) => draft.remove(Integration.ID.make(id)),
method: {
list: (id) => draft.method.list(Integration.ID.make(id)),
list: (id) => mutable(draft.method.list(Integration.ID.make(id))),
update: (input) => draft.method.update(methodImplementation(input)),
remove: (id, method) =>
draft.method.remove(Integration.ID.make(id), Schema.decodeUnknownSync(Integration.Method)(method)),
@@ -364,8 +363,8 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
return {
integrationID: Integration.ID.make(input.integrationID),
method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
authorize: (answer) =>
input.authorize(answer).pipe(
authorize: (inputs) =>
input.authorize(inputs).pipe(
Effect.map((authorization) => {
if (authorization.mode === "auto") {
return {
@@ -386,18 +385,18 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
if (input.method.type === "env") {
return {
integrationID: Integration.ID.make(input.integrationID),
method: input.method,
method: { type: "env", names: input.method.names },
}
}
if (input.method.type === "command") {
return {
integrationID: Integration.ID.make(input.integrationID),
method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
method: Schema.decodeUnknownSync(Integration.CommandMethod)(input.method),
}
}
return {
integrationID: Integration.ID.make(input.integrationID),
method: input.method,
method: { type: "key", label: input.method.label },
}
}
+7 -13
View File
@@ -180,8 +180,8 @@ export function fromPromise(plugin: Plugin) {
const refresh = input.refresh
draft.method.update({
...input,
authorize: (answer) =>
Effect.promise(() => input.authorize(answer)).pipe(
authorize: (inputs) =>
Effect.promise(() => input.authorize(inputs)).pipe(
Effect.map((authorization) =>
authorization.mode === "auto"
? {
@@ -362,17 +362,11 @@ type Wire<Value> = unknown extends Value
? Value
: Value extends DateTime.DateTime
? number
: Value extends readonly [infer Head, ...infer Tail]
? [Wire<Head>, ...WireTuple<Tail>]
: Value extends ReadonlyArray<infer Item>
? Array<Wire<Item>>
: Value extends object
? { -readonly [Key in keyof Value]: Wire<Value[Key]> }
: Value
type WireTuple<Value extends ReadonlyArray<unknown>> = {
-readonly [Key in keyof Value]: Wire<Value[Key]>
}
: Value extends ReadonlyArray<infer Item>
? Array<Wire<Item>>
: Value extends object
? { -readonly [Key in keyof Value]: Wire<Value[Key]> }
: Value
function wire<Value>(value: Value): Wire<Value>
function wire(value: unknown): unknown {
@@ -1,9 +1,6 @@
import { Effect } from "effect"
import { define } from "@opencode-ai/plugin/effect/plugin"
import { Form } from "@opencode-ai/schema/form"
import { Provider } from "../../provider"
import { iife } from "../../util/iife"
import { configuredSettings } from "./configured"
function selectLanguage(sdk: any, modelID: string, useChat: boolean) {
if (useChat && sdk.chat) return sdk.chat(modelID)
@@ -16,29 +13,6 @@ function selectLanguage(sdk: any, modelID: string, useChat: boolean) {
export const AzurePlugin = define({
id: "opencode.provider.azure",
effect: Effect.fn(function* (ctx) {
const configured = yield* configuredSettings(Provider.ID.azure)
const form = iife(() => {
if (resolveResourceName(configured) || typeof configured?.baseURL === "string") return
return Form.Fields.make([
{
type: "string",
key: "resourceName",
title: "Enter Azure Resource Name",
placeholder: "e.g. my-models",
required: true,
},
])
})
yield* ctx.integration.transform((draft) => {
draft.method.update({
integrationID: Provider.ID.azure,
method: {
type: "key",
label: "API key",
form,
},
})
})
yield* ctx.catalog.transform((evt) => {
for (const item of evt.provider.list()) {
if (item.provider.id !== Provider.ID.azure && Provider.packageName(item.provider.package) !== "@ai-sdk/azure")
@@ -2,53 +2,10 @@ import os from "os"
import { App } from "../../app"
import { Effect, Option, Schema } from "effect"
import { define } from "@opencode-ai/plugin/effect/plugin"
import { Form } from "@opencode-ai/schema/form"
import { Provider } from "../../provider"
import { iife } from "../../util/iife"
import { configuredSettings } from "./configured"
const providerID = Provider.ID.make("cloudflare-ai-gateway")
export const CloudflareAIGatewayPlugin = define({
id: "opencode.provider.cloudflare-ai-gateway",
effect: Effect.fn(function* (ctx) {
const configured = yield* configuredSettings(providerID)
const form = iife(() => {
if (typeof configured?.baseURL === "string") return
const accountId = process.env.CLOUDFLARE_ACCOUNT_ID || stringOption(configured ?? {}, "accountId")
const gatewayId =
process.env.CLOUDFLARE_GATEWAY_ID ||
stringOption(configured ?? {}, "gatewayId") ||
stringOption(configured ?? {}, "gateway")
if (accountId && gatewayId) return
const accountIdForm = Form.StringField.make({
type: "string",
key: "accountId",
title: "Enter your Cloudflare Account ID",
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
required: true,
})
const gatewayIdForm = Form.StringField.make({
type: "string",
key: "gatewayId",
title: "Enter your Cloudflare AI Gateway ID",
placeholder: "e.g. my-gateway",
required: true,
})
if (accountId) return Form.Fields.make([gatewayIdForm])
if (gatewayId) return Form.Fields.make([accountIdForm])
return Form.Fields.make([accountIdForm, gatewayIdForm])
})
yield* ctx.integration.transform((draft) => {
draft.method.update({
integrationID: providerID,
method: {
type: "key",
label: "Gateway API token",
form,
},
})
})
yield* ctx.aisdk.hook(
"sdk",
Effect.fn(function* (evt) {
@@ -89,7 +46,7 @@ const decodeJson = Schema.decodeUnknownOption(Schema.UnknownFromJsonString)
function gatewayConfig(options: Record<string, unknown>): GatewayConfig | undefined {
const accountId = process.env.CLOUDFLARE_ACCOUNT_ID ?? stringOption(options, "accountId")
// Credential projection copies key metadata into options. The form stores the
// Credential projection copies key metadata into options. The prompt stores the
// gateway as gatewayId, while older config examples may use gateway.
const gatewayId =
process.env.CLOUDFLARE_GATEWAY_ID ?? stringOption(options, "gatewayId") ?? stringOption(options, "gateway")
@@ -2,39 +2,13 @@ import os from "os"
import { App } from "../../app"
import { Effect } from "effect"
import { define } from "@opencode-ai/plugin/effect/plugin"
import { Form } from "@opencode-ai/schema/form"
import { Provider } from "../../provider"
import { iife } from "../../util/iife"
import { configuredSettings } from "./configured"
const providerID = Provider.ID.make("cloudflare-workers-ai")
export const CloudflareWorkersAIPlugin = define({
id: "opencode.provider.cloudflare-workers-ai",
effect: Effect.fn(function* (ctx) {
const configured = yield* configuredSettings(providerID)
const form = iife(() => {
if (typeof configured?.baseURL === "string" || resolveAccountId(configured ?? {})) return
return Form.Fields.make([
{
type: "string",
key: "accountId",
title: "Enter your Cloudflare Account ID",
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
required: true,
},
])
})
yield* ctx.integration.transform((draft) => {
draft.method.update({
integrationID: providerID,
method: {
type: "key",
label: "API key",
form,
},
})
})
yield* ctx.catalog.transform((evt) => {
const item = evt.provider.get(providerID)
if (!item) return
@@ -1,15 +0,0 @@
import { Effect, Option } from "effect"
import type { Document } from "@opencode-ai/schema/config"
import { Catalog } from "../../catalog"
import { Config } from "../../config"
import { Provider } from "../../provider"
export const configuredSettings = Effect.fn("ProviderPlugin.configuredSettings")(function* (id: Provider.ID) {
const catalog = yield* Catalog.Service
const current = (yield* catalog.provider.get(id))?.settings
const service = yield* Effect.serviceOption(Config.Service)
const entries = Option.isSome(service) ? yield* service.value.entries() : []
return entries
.filter((entry): entry is Document => entry.type === "document")
.reduce((settings, entry) => Provider.mergeOverlay(settings, entry.info.providers?.[id]?.settings), current)
})
@@ -15,8 +15,6 @@ import type { PluginInternal } from "../internal"
const clientID = "Ov23li8tweQw6odWQebz"
const apiVersion = "2026-06-01"
const userApiVersion = "2025-04-01"
const copilotVersion = "0.26.7"
const editorVersion = "vscode/1.99.3"
const pollingSafetyMargin = 3000
const methodID = Integration.MethodID.make("device")
@@ -49,33 +47,30 @@ const oauth = (app: App.Info) =>
id: methodID,
type: "oauth",
label: "Login with GitHub Copilot",
form: [
prompts: [
{
type: "string",
type: "select",
key: "deploymentType",
title: "Select GitHub deployment type",
required: true,
message: "Select GitHub deployment type",
options: [
{ label: "GitHub.com", value: "github.com", description: "Public" },
{ label: "GitHub Enterprise", value: "enterprise", description: "Data residency or self-hosted" },
{ label: "GitHub.com", value: "github.com", hint: "Public" },
{ label: "GitHub Enterprise", value: "enterprise", hint: "Data residency or self-hosted" },
],
},
{
type: "string",
type: "text",
key: "enterpriseUrl",
title: "Enter your GitHub Enterprise URL or domain",
message: "Enter your GitHub Enterprise URL or domain",
placeholder: "company.ghe.com or https://company.ghe.com",
required: true,
when: [{ key: "deploymentType", op: "eq", value: "enterprise" }],
when: { key: "deploymentType", op: "eq", value: "enterprise" },
},
],
},
authorize: (answer) =>
authorize: (inputs) =>
Effect.gen(function* () {
const enterprise = answer.deploymentType === "enterprise"
const enterpriseUrl = typeof answer.enterpriseUrl === "string" ? answer.enterpriseUrl : undefined
if (enterprise && !enterpriseUrl) return yield* Effect.fail(new Error("Enterprise URL is required"))
const domain = enterprise ? normalizeDomain(enterpriseUrl ?? "") : "github.com"
const enterprise = inputs.deploymentType === "enterprise"
if (enterprise && !inputs.enterpriseUrl) return yield* Effect.fail(new Error("Enterprise URL is required"))
const domain = enterprise ? normalizeDomain(inputs.enterpriseUrl ?? "") : "github.com"
const urls = oauthURLs(domain)
const device = yield* request(urls.device, {
method: "POST",
@@ -193,28 +188,11 @@ export const GithubCopilotPlugin = define({
})
yield* ctx.integration.transform((draft) => {
draft.method.remove("github-copilot", { type: "key" })
draft.method.update(oauth(ctx.app))
})
yield* ctx.catalog.transform((evt) => {
const item = evt.provider.get(Provider.ID.githubCopilot)
if (!item) return
evt.provider.update(item.provider.id, (provider) => {
if (Provider.packageName(provider.package) === "@ai-sdk/openai-compatible") {
provider.package = Provider.aisdk(CopilotModels.Package.OpenAI)
}
})
for (const model of item.models.values()) {
evt.model.update(item.provider.id, model.id, (draft) => {
const packageName = Provider.packageName(draft.package)
if (packageName === "@ai-sdk/openai-compatible") {
draft.package = Provider.aisdk(CopilotModels.Package.OpenAI)
}
if (packageName === "@ai-sdk/anthropic") {
draft.package = Provider.aisdk(CopilotModels.Package.Anthropic)
}
})
}
if (loaded.models) {
for (const id of item.models.keys()) {
if (!loaded.models.has(Model.ID.make(id))) evt.model.remove(item.provider.id, id)
@@ -248,14 +226,14 @@ export const GithubCopilotPlugin = define({
"sdk",
Effect.fn(function* (evt) {
if (evt.model.providerID !== Provider.ID.githubCopilot) return
if (evt.package !== CopilotModels.Package.OpenAI && evt.package !== CopilotModels.Package.Anthropic) return
const anthropic = evt.package === CopilotModels.Package.Anthropic
if (evt.package !== "@ai-sdk/github-copilot" && evt.package !== "@ai-sdk/anthropic") return
evt.options.fetch = copilotFetch(
typeof evt.options.apiKey === "string" ? evt.options.apiKey : undefined,
evt.options.fetch,
anthropic,
evt.package === "@ai-sdk/anthropic",
ctx.app,
)
if (anthropic) {
if (evt.package === "@ai-sdk/anthropic") {
evt.options.headers = {
...evt.options.headers,
"anthropic-beta": "interleaved-thinking-2025-05-14",
@@ -334,7 +312,12 @@ function request(url: string, init: RequestInit) {
type Fetch = (input: Parameters<typeof fetch>[0], init?: RequestInit) => Promise<Response>
export function copilotFetch(token: string | undefined, upstream: Fetch | undefined, anthropic: boolean): Fetch {
export function copilotFetch(
token: string | undefined,
upstream: Fetch | undefined,
anthropic: boolean,
app: App.Info,
): Fetch {
const send = upstream ?? fetch
return async (input, init) => {
const requestHeaders = new Headers(init?.headers)
@@ -343,10 +326,7 @@ export function copilotFetch(token: string | undefined, upstream: Fetch | undefi
requestHeaders.delete("x-api-key")
requestHeaders.set("Authorization", `Bearer ${token}`)
}
requestHeaders.set("User-Agent", `GitHubCopilotChat/${copilotVersion}`)
requestHeaders.set("Editor-Version", editorVersion)
requestHeaders.set("Editor-Plugin-Version", `copilot-chat/${copilotVersion}`)
requestHeaders.set("Copilot-Integration-Id", "vscode-chat")
requestHeaders.set("User-Agent", App.useragent(app))
requestHeaders.set("Openai-Intent", "conversation-edits")
requestHeaders.set("X-GitHub-Api-Version", apiVersion)
if (anthropic) requestHeaders.set("anthropic-beta", "interleaved-thinking-2025-05-14")
@@ -43,9 +43,9 @@ function oauth(http: HttpClient.HttpClient) {
type: "oauth",
label: "OpenCode Console account",
},
authorize: (answer) =>
authorize: (inputs) =>
Effect.gen(function* () {
const server = yield* normalizeServer(answer.server ?? defaultServer)
const server = yield* normalizeServer(inputs.server ?? defaultServer)
const device = yield* post(http, `${server}/auth/device/code`, { client_id: clientID }, Device)
const verification = URL.canParse(device.verification_uri_complete)
? new URL(device.verification_uri_complete)
@@ -226,10 +226,9 @@ function withoutCredentials(body: Readonly<Record<string, unknown>> | undefined)
return Object.fromEntries(Object.entries(body ?? {}).filter(([key]) => key !== "apiKey" && key !== "headers"))
}
function normalizeServer(input: unknown) {
function normalizeServer(input: string) {
return Effect.try({
try: () => {
if (typeof input !== "string") throw new Error("expected string")
const url = new URL(input)
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("expected HTTP(S)")
return `${url.origin}${url.pathname.replace(/\/+$/, "")}`
@@ -42,18 +42,6 @@ test("defensively syncs advertised Copilot models", async () => {
supports: { tool_calls: false },
},
},
{
model_picker_enabled: true,
id: "claude-sonnet",
name: "Claude Sonnet",
version: "claude-sonnet-2026-06-01",
supported_endpoints: ["/v1/messages"],
capabilities: {
family: "claude",
limits: { max_output_tokens: 16000, max_prompt_tokens: 180000 },
supports: { tool_calls: true },
},
},
{ model_picker_enabled: true, id: "incomplete" },
],
}),
@@ -80,7 +68,6 @@ test("defensively syncs advertised Copilot models", async () => {
Model.VariantID.make("high"),
])
expect(models.get(Model.ID.make("utility"))?.enabled).toBe(false)
expect(models.get(Model.ID.make("claude-sonnet"))?.package).toBe(Provider.aisdk(CopilotModels.Package.Anthropic))
expect(models.has(Model.ID.make("stale"))).toBe(false)
expect(models.has(Model.ID.make("incomplete"))).toBe(false)
} finally {
+8 -19
View File
@@ -140,11 +140,7 @@ describe("Integration", () => {
yield* integrations.transform((editor) =>
editor.method.update({
integrationID,
method: {
type: "key",
label: "API key",
form: [{ type: "string", key: "accountId", title: "Account ID", required: true }],
},
method: { type: "key", label: "API key" },
}),
)
const updated = yield* bus
@@ -152,17 +148,9 @@ describe("Integration", () => {
.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped)
yield* Effect.yieldNow
expect(
yield* integrations.connection.key({ integrationID, key: "secret" }).pipe(
Effect.flip,
Effect.map((error) => error.cause),
),
).toEqual(expect.objectContaining({ message: "Missing required form field: accountId" }))
yield* integrations.connection.key({
integrationID,
key: "secret",
answer: { accountId: "account" },
label: "Work",
})
@@ -170,7 +158,7 @@ describe("Integration", () => {
expect.objectContaining({
integrationID,
label: "Work",
value: Credential.Key.make({ type: "key", key: "secret", configuration: { accountId: "account" } }),
value: Credential.Key.make({ type: "key", key: "secret" }),
}),
])
expect((yield* Fiber.join(updated)).length).toBe(1)
@@ -255,6 +243,7 @@ describe("Integration", () => {
const attempt = yield* integrations.oauth.connect({
integrationID,
methodID,
inputs: {},
label: "Personal",
})
expect(attempt.mode).toBe("code")
@@ -300,7 +289,7 @@ describe("Integration", () => {
}),
)
const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
expect(
yield* integrations.oauth.complete({ integrationID, attemptID: attempt.attemptID }).pipe(Effect.flip),
).toBeInstanceOf(Integration.CodeRequiredError)
@@ -338,7 +327,7 @@ describe("Integration", () => {
}),
)
const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
yield* Effect.yieldNow
expect(yield* integrations.oauth.status({ integrationID, attemptID: attempt.attemptID })).toEqual({
status: "complete",
@@ -376,7 +365,7 @@ describe("Integration", () => {
}),
)
const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
const exit = yield* integrations.oauth
.complete({ integrationID, attemptID: attempt.attemptID, code: "1234" })
.pipe(Effect.exit)
@@ -412,7 +401,7 @@ describe("Integration", () => {
}),
)
const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
expect(attempt.time.expires - attempt.time.created).toBe(Duration.toMillis(Duration.minutes(10)))
yield* TestClock.adjust(Duration.minutes(10))
yield* Effect.yieldNow
@@ -453,7 +442,7 @@ describe("Integration", () => {
}),
)
const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
expect(attempt.time).toEqual({ created, expires: expiresAt })
})
})
+2 -6
View File
@@ -736,11 +736,7 @@ describe("ModelResolver", () => {
headers: { "x-aisdk": "header" },
body: { custom: true },
}),
Credential.Key.make({
type: "key",
key: "fallback-secret",
configuration: { accountId: "account" },
}),
Credential.Key.make({ type: "key", key: "fallback-secret" }),
{
loadAISDK: (runtime) =>
Effect.sync(() => {
@@ -749,7 +745,7 @@ describe("ModelResolver", () => {
modelID: "mistral-api-model",
providerID: "test-provider",
package: Provider.aisdk("@ai-sdk/mistral"),
settings: { project: "test", apiKey: "fallback-secret", accountId: "account" },
settings: { project: "test", apiKey: "fallback-secret" },
headers: { "x-aisdk": "header" },
body: { custom: true },
})
+35 -9
View File
@@ -1,5 +1,5 @@
import { Plugin } from "@opencode-ai/plugin/effect"
import type { IntegrationMethod, IntegrationMethodRegistration } from "@opencode-ai/plugin/effect/integration"
import type { IntegrationMethodRegistration } from "@opencode-ai/plugin/effect/integration"
import { Agent } from "@opencode-ai/core/agent"
import { Catalog } from "@opencode-ai/core/catalog"
import { Credential } from "@opencode-ai/core/credential"
@@ -15,6 +15,7 @@ import { Effect, Stream } from "effect"
type Overrides = Partial<Omit<Plugin.Context, "options" | "session">> & {
readonly session?: Partial<Plugin.Context["session"]>
}
export function host(overrides: Overrides = {}): Plugin.Context {
return {
app: overrides.app ?? { name: "test", version: "test", channel: "test" },
@@ -277,7 +278,7 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
update: (id, update) => draft.update(Integration.ID.make(id), update),
remove: (id) => draft.remove(Integration.ID.make(id)),
method: {
list: (id) => draft.method.list(Integration.ID.make(id)),
list: (id) => draft.method.list(Integration.ID.make(id)).map(method),
update: (input) => {
if ("authorize" in input) {
const methodID = Integration.MethodID.make(input.method.id)
@@ -285,8 +286,8 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
draft.method.update({
integrationID: Integration.ID.make(input.integrationID),
method: { ...input.method, id: methodID },
authorize: (answer) =>
input.authorize(answer).pipe(
authorize: (inputs) =>
input.authorize(inputs).pipe(
Effect.map((authorization) => {
if (authorization.mode === "auto") {
return {
@@ -335,7 +336,7 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
if (input.method.type === "env") {
draft.method.update({
integrationID: Integration.ID.make(input.integrationID),
method: input.method,
method: { ...input.method, names: [...input.method.names] },
})
return
}
@@ -345,6 +346,7 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
method: {
...input.method,
id: Integration.MethodID.make(input.method.id),
command: [...input.method.command],
},
})
return
@@ -399,11 +401,35 @@ function oauthCredential(value: Credential.OAuth) {
return Credential.OAuth.make({ ...value, methodID: Integration.MethodID.make(value.methodID) })
}
function internalMethod(value: IntegrationMethod): Integration.Method {
if (value.type === "oauth" || value.type === "command") {
return { ...value, id: Integration.MethodID.make(value.id) }
function method(value: Integration.Method) {
if (value.type === "env") return { type: value.type, names: [...value.names] }
if (value.type === "key") return { type: value.type, label: value.label }
if (value.type === "command") return { ...value, command: [...value.command] }
return {
type: value.type,
id: value.id,
label: value.label,
prompts: value.prompts?.map((prompt) => {
if (prompt.type === "text") return { ...prompt }
return { ...prompt, options: prompt.options.map((option) => ({ ...option })) }
}),
}
}
function internalMethod(value: IntegrationMethodRegistration["method"]): Integration.Method {
if (value.type === "env") return value
if (value.type === "key") return value
if (value.type === "command") {
return {
...value,
id: Integration.MethodID.make(value.id),
command: [...value.command],
}
}
return {
...value,
id: Integration.MethodID.make(value.id),
}
return value
}
function agentInfo(value: Agent.Info) {
@@ -8,7 +8,6 @@ import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHost } from "@opencode-ai/core/plugin/host"
import { AzurePlugin } from "@opencode-ai/core/plugin/provider/azure"
import { Provider } from "@opencode-ai/core/provider"
import { Integration } from "@opencode-ai/core/integration"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -61,27 +60,6 @@ function fakeSelectorSdk(calls: string[]) {
}
describe("AzurePlugin", () => {
it.effect("registers a resource name form when the environment does not provide one", () =>
withEnv({ AZURE_RESOURCE_NAME: undefined, AZURE_COGNITIVE_SERVICES_RESOURCE_NAME: undefined }, () =>
Effect.gen(function* () {
yield* addPlugin()
expect((yield* (yield* Integration.Service).get(Integration.ID.make("azure")))?.methods).toContainEqual({
type: "key",
label: "API key",
form: [
{
type: "string",
key: "resourceName",
title: "Enter Azure Resource Name",
placeholder: "e.g. my-models",
required: true,
},
],
})
}),
),
)
it.effect("resolves resourceName from env", () =>
withEnv({ AZURE_RESOURCE_NAME: "from-env" }, () =>
Effect.gen(function* () {
@@ -217,17 +195,7 @@ describe("AzurePlugin", () => {
Effect.gen(function* () {
const plugin = yield* Plugin.Service
const aisdk = yield* AISDK.Service
const catalog = yield* Catalog.Service
yield* catalog.transform((catalog) =>
catalog.provider.update(Provider.ID.azure, (provider) => {
provider.settings = { ...provider.settings, baseURL: "https://proxy.example.com/openai" }
}),
)
yield* addPlugin()
expect((yield* (yield* Integration.Service).get(Integration.ID.make("azure")))?.methods).toContainEqual({
type: "key",
label: "API key",
})
const result = yield* aisdk.runSDK({
model: Model.Info.make({
...Model.Info.default(Provider.ID.azure, Model.ID.make("deployment")),
@@ -1,13 +1,11 @@
import { AISDK } from "@opencode-ai/core/aisdk"
import { describe, expect, mock } from "bun:test"
import { Effect } from "effect"
import { Catalog } from "@opencode-ai/core/catalog"
import { Model } from "@opencode-ai/core/model"
import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHost } from "@opencode-ai/core/plugin/host"
import { CloudflareAIGatewayPlugin } from "@opencode-ai/core/plugin/provider/cloudflare-ai-gateway"
import { Provider } from "@opencode-ai/core/provider"
import { Integration } from "@opencode-ai/core/integration"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -104,24 +102,6 @@ mock.module("ai-gateway-provider/providers/unified", () => ({
}))
describe("CloudflareAIGatewayPlugin", () => {
it.effect("registers account and gateway forms when the environment does not provide them", () =>
withEnv({ CLOUDFLARE_ACCOUNT_ID: undefined, CLOUDFLARE_GATEWAY_ID: undefined }, () =>
Effect.gen(function* () {
yield* addPlugin()
expect(
(yield* (yield* Integration.Service).get(Integration.ID.make("cloudflare-ai-gateway")))?.methods,
).toContainEqual({
type: "key",
label: "Gateway API token",
form: [
expect.objectContaining({ type: "string", key: "accountId", required: true }),
expect.objectContaining({ type: "string", key: "gatewayId", required: true }),
],
})
}),
),
)
it.effect("requires account, gateway, and token before creating the unified SDK", () =>
withEnv(
{
@@ -377,16 +357,7 @@ describe("CloudflareAIGatewayPlugin", () => {
resetCalls()
const plugin = yield* Plugin.Service
const aisdk = yield* AISDK.Service
const catalog = yield* Catalog.Service
yield* catalog.transform((catalog) =>
catalog.provider.update(Provider.ID.make("cloudflare-ai-gateway"), (provider) => {
provider.settings = { ...provider.settings, baseURL: "https://proxy.example/v1" }
}),
)
yield* addPlugin()
expect(
(yield* (yield* Integration.Service).get(Integration.ID.make("cloudflare-ai-gateway")))?.methods,
).toContainEqual({ type: "key", label: "Gateway API token" })
const result = yield* aisdk.runSDK({
model: Model.Info.make({
@@ -7,7 +7,6 @@ import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHost } from "@opencode-ai/core/plugin/host"
import { CloudflareWorkersAIPlugin } from "@opencode-ai/core/plugin/provider/cloudflare-workers-ai"
import { Provider } from "@opencode-ai/core/provider"
import { Integration } from "@opencode-ai/core/integration"
import type { LanguageModelV3 } from "@ai-sdk/provider"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -80,29 +79,6 @@ function cloudflareHeaders(sdk: unknown, modelID = "@cf/model") {
}
describe("CloudflareWorkersAIPlugin", () => {
it.effect("registers an account form when the environment does not provide one", () =>
withEnv({ CLOUDFLARE_ACCOUNT_ID: undefined }, () =>
Effect.gen(function* () {
yield* addPlugin()
expect(
(yield* (yield* Integration.Service).get(Integration.ID.make("cloudflare-workers-ai")))?.methods,
).toContainEqual({
type: "key",
label: "API key",
form: [
{
type: "string",
key: "accountId",
title: "Enter your Cloudflare Account ID",
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
required: true,
},
],
})
}),
),
)
it.effect("maps account ID to endpoint URL and creates an OpenAI-compatible SDK", () =>
withEnv({ CLOUDFLARE_ACCOUNT_ID: "acct", CLOUDFLARE_API_KEY: "key" }, () =>
Effect.gen(function* () {
@@ -115,9 +91,6 @@ describe("CloudflareWorkersAIPlugin", () => {
}),
)
yield* addPlugin()
expect(
(yield* (yield* Integration.Service).get(Integration.ID.make("cloudflare-workers-ai")))?.methods,
).toContainEqual({ type: "key", label: "API key" })
const provider = required(yield* catalog.provider.get(Provider.ID.make("cloudflare-workers-ai")))
const sdk = yield* aisdk.runSDK({
model: Model.Info.make({
@@ -162,16 +135,7 @@ describe("CloudflareWorkersAIPlugin", () => {
Effect.gen(function* () {
const plugin = yield* Plugin.Service
const aisdk = yield* AISDK.Service
const catalog = yield* Catalog.Service
yield* catalog.transform((catalog) =>
catalog.provider.update(Provider.ID.make("cloudflare-workers-ai"), (provider) => {
provider.settings = { ...provider.settings, baseURL: "https://proxy.example/v1" }
}),
)
yield* addPlugin()
expect(
(yield* (yield* Integration.Service).get(Integration.ID.make("cloudflare-workers-ai")))?.methods,
).toContainEqual({ type: "key", label: "API key" })
const result = yield* aisdk.runSDK({
model: Model.Info.make({
...Model.Info.default(Provider.ID.make("cloudflare-workers-ai"), Model.ID.make("@cf/model")),
@@ -1,4 +1,5 @@
import { AISDK } from "@opencode-ai/core/aisdk"
import { App } from "@opencode-ai/core/app"
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
import { Catalog } from "@opencode-ai/core/catalog"
@@ -6,11 +7,8 @@ import { Model } from "@opencode-ai/core/model"
import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHost } from "@opencode-ai/core/plugin/host"
import { copilotBaseURL, copilotFetch, GithubCopilotPlugin } from "@opencode-ai/core/plugin/provider/github-copilot"
import { CopilotModels } from "@opencode-ai/core/github-copilot/models"
import { Provider } from "@opencode-ai/core/provider"
import { Integration } from "@opencode-ai/core/integration"
import { Credential } from "@opencode-ai/core/credential"
import { ModelResolver } from "@opencode-ai/core/model-resolver"
import type { LanguageModelV3 } from "@ai-sdk/provider"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -59,37 +57,11 @@ describe("GithubCopilotPlugin", () => {
id: Integration.MethodID.make("device"),
type: "oauth",
label: "Login with GitHub Copilot",
form: expect.any(Array),
prompts: expect.any(Array),
})
}),
)
it.effect("removes the generic key method", () =>
Effect.gen(function* () {
const integrations = yield* Integration.Service
yield* integrations.transform((draft) => {
draft.method.update({
integrationID: Integration.ID.make("github-copilot"),
method: { type: "key" },
})
draft.method.update({
integrationID: Integration.ID.make("github-copilot"),
method: { type: "env", names: ["GITHUB_TOKEN"] },
})
})
yield* addPlugin()
expect((yield* integrations.get(Integration.ID.make("github-copilot")))?.methods).toEqual([
{ type: "env", names: ["GITHUB_TOKEN"] },
{
id: Integration.MethodID.make("device"),
type: "oauth",
label: "Login with GitHub Copilot",
form: expect.any(Array),
},
])
}),
)
it.live("adds Copilot authentication and request metadata headers", () =>
Effect.gen(function* () {
const requests: Headers[] = []
@@ -100,6 +72,7 @@ describe("GithubCopilotPlugin", () => {
return Response.json({ ok: true })
},
false,
App.make({ name: "test", version: "1.2.3", channel: "beta" }),
)
yield* Effect.promise(() =>
send("https://api.githubcopilot.com/chat/completions", {
@@ -115,10 +88,7 @@ describe("GithubCopilotPlugin", () => {
expect(requests[0]?.get("x-initiator")).toBe("user")
expect(requests[0]?.get("copilot-vision-request")).toBe("true")
expect(requests[0]?.get("x-github-api-version")).toBe("2026-06-01")
expect(requests[0]?.get("user-agent")).toBe("GitHubCopilotChat/0.26.7")
expect(requests[0]?.get("editor-version")).toBe("vscode/1.99.3")
expect(requests[0]?.get("editor-plugin-version")).toBe("copilot-chat/0.26.7")
expect(requests[0]?.get("copilot-integration-id")).toBe("vscode-chat")
expect(requests[0]?.get("user-agent")).toBe("opencode/beta/1.2.3/test")
}),
)
@@ -150,54 +120,6 @@ describe("GithubCopilotPlugin", () => {
}),
)
it.effect("routes all Copilot protocols through Copilot-owned SDK hooks", () =>
Effect.gen(function* () {
const catalog = yield* Catalog.Service
yield* catalog.transform((draft) => {
draft.provider.update(Provider.ID.githubCopilot, (provider) => {
provider.package = Provider.aisdk("@ai-sdk/openai-compatible")
})
draft.model.update(Provider.ID.githubCopilot, Model.ID.make("claude-sonnet"), (model) => {
model.package = Provider.aisdk("@ai-sdk/anthropic")
})
})
yield* addPlugin()
expect(required(yield* catalog.provider.get(Provider.ID.githubCopilot)).package).toBe(
Provider.aisdk(CopilotModels.Package.OpenAI),
)
expect(
required(yield* catalog.model.get(Provider.ID.githubCopilot, Model.ID.make("claude-sonnet"))).package,
).toBe(Provider.aisdk(CopilotModels.Package.Anthropic))
const fallback = yield* ModelResolver.fromCatalogModel(
Model.Info.make({
...Model.Info.default(Provider.ID.openai, Model.ID.make("fallback")),
package: Provider.aisdk("@ai-sdk/openai"),
settings: { baseURL: "https://openai.example/v1" },
}),
)
const resolved = yield* ModelResolver.fromCatalogModel(
required(yield* catalog.model.get(Provider.ID.githubCopilot, Model.ID.make("claude-sonnet"))),
Credential.OAuth.make({
type: "oauth",
methodID: Integration.MethodID.make("device"),
refresh: "github-token",
access: "github-token",
expires: 0,
}),
{
loadAISDK: (runtime) =>
Effect.sync(() => {
expect(runtime.settings?.apiKey).toBe("github-token")
return fallback
}),
},
)
expect(resolved).toBe(fallback)
}),
)
it.effect("selects languageModel when responses and chat are absent", () =>
Effect.gen(function* () {
const plugin = yield* Plugin.Service
@@ -128,7 +128,7 @@ describe("OpencodePlugin", () => {
const attempt = yield* integrations.oauth.connect({
integrationID,
methodID: Integration.MethodID.make("device"),
answer: { server: `${server.url.origin}/console///?ignored=true#ignored` },
inputs: { server: `${server.url.origin}/console///?ignored=true#ignored` },
})
expect(attempt.url).toBe(`${server.url.origin}/verify`)
yield* eventually(
@@ -155,7 +155,7 @@ describe("OpencodePlugin", () => {
.connect({
integrationID: Integration.ID.make("opencode"),
methodID: Integration.MethodID.make("device"),
answer: { server: "ftp://console.example.com" },
inputs: { server: "ftp://console.example.com" },
})
.pipe(Effect.flip)
expect(error).toBeInstanceOf(Integration.AuthorizationError)
@@ -163,21 +163,6 @@ describe("OpencodePlugin", () => {
}),
)
it.effect("rejects non-string OpenCode servers", () =>
Effect.gen(function* () {
yield* addPlugin()
const error = yield* (yield* Integration.Service).oauth
.connect({
integrationID: Integration.ID.make("opencode"),
methodID: Integration.MethodID.make("device"),
answer: { server: true },
})
.pipe(Effect.flip)
expect(error).toBeInstanceOf(Integration.AuthorizationError)
expect(String(error.cause)).toContain("Invalid OpenCode server URL: expected string")
}),
)
it.live("loads providers and models from the connected OpenCode server", () =>
Effect.acquireUseRelease(
Effect.sync(() => {
+1 -4
View File
@@ -129,10 +129,7 @@ describe("built-in web search providers", () => {
yield* WebSearchParallel.Plugin.effect(
host({ integration: integrationHost(integrations), websearch: webSearchHost(websearch) }),
)
yield* integrations.connection.key({
integrationID: Integration.ID.make("parallel"),
key: "parallel-secret",
})
yield* integrations.connection.key({ integrationID: Integration.ID.make("parallel"), key: "parallel-secret" })
const output = yield* websearch.query({
query: "effect layers",
+5
View File
@@ -90,10 +90,15 @@ test("Core reuses the canonical shared schemas", async () => {
[coreFileSystem.Match, FileSystem.Match],
[coreIntegration.ID, Integration.ID],
[coreIntegration.MethodID, Integration.MethodID],
[coreIntegration.When, Integration.When],
[coreIntegration.TextPrompt, Integration.TextPrompt],
[coreIntegration.SelectPrompt, Integration.SelectPrompt],
[coreIntegration.Prompt, Integration.Prompt],
[coreIntegration.OAuthMethod, Integration.OAuthMethod],
[coreIntegration.KeyMethod, Integration.KeyMethod],
[coreIntegration.EnvMethod, Integration.EnvMethod],
[coreIntegration.Method, Integration.Method],
[coreIntegration.Inputs, Integration.Inputs],
[coreIntegration.Ref, Integration.Ref],
[coreLocation.Ref, Location.Ref],
[coreAI.ProviderMetadata, AI.ProviderMetadata],
+1
View File
@@ -14,6 +14,7 @@
"dependencies": {
"@opencode-ai/plugin": "workspace:*",
"@opentui/core": "catalog:",
"entities": "7.0.1",
"string-width": "catalog:"
},
"devDependencies": {
+87
View File
@@ -7,6 +7,18 @@ describe("DiagramCanvas", () => {
expect(() => new DiagramCanvas(2_000, 1_000)).toThrow(DiagramCanvasSizeError)
})
test("rejects invalid canvas dimensions", () => {
for (const [width, height] of [
[-1, 10],
[10, -1],
[1.5, 10],
[Number.NaN, 10],
[Number.POSITIVE_INFINITY, 10],
]) {
expect(() => new DiagramCanvas(width, height)).toThrow(DiagramCanvasSizeError)
}
})
test("writes cells and text while clipping out-of-bounds positions", () => {
const canvas = new DiagramCanvas<"label">(5, 2)
@@ -26,6 +38,21 @@ describe("DiagramCanvas", () => {
expect(stringWidth(canvas.toString())).toBe(4)
})
test("keeps custom measurement for ASCII text", () => {
let measurements = 0
const canvas = new DiagramCanvas<"label">(5, 1, {
measure: () => {
measurements += 1
return 2
},
})
canvas.setText(0, 0, "ab", "label")
expect(measurements).toBe(2)
expect(canvas.getCell(2, 0)?.char).toBe("b")
})
test("preserves combined graphemes while placing later text", () => {
const canvas = new DiagramCanvas<"label">(4, 1)
@@ -48,6 +75,9 @@ describe("DiagramCanvas", () => {
canvas.setCell(1, 0, "│", "line")
expect(canvas.toString()).toBe(" ┼")
canvas.replaceCell(1, 0, "│", "line")
expect(canvas.toString()).toBe(" │")
})
test("iterates style and metadata runs", () => {
@@ -93,4 +123,61 @@ describe("DiagramCanvas", () => {
expect(canvas.toString({ trimTop: true })).toBe("end")
expect(canvas.getTextSize({ trimTop: true })).toEqual({ width: 3, height: 1 })
})
test("measures trim-aware text height without measuring row width", () => {
let measurements = 0
const canvas = new DiagramCanvas(8, 5, {
measure: (text) => {
measurements += 1
return stringWidth(text)
},
})
canvas.setText(1, 2, "middle")
measurements = 0
expect(canvas.getTextHeight({ trimTop: true, trimBottom: true })).toBe(1)
expect(measurements).toBe(0)
})
test("updates tracked row extents when the last visible cell is cleared", () => {
const canvas = new DiagramCanvas(8, 1)
canvas.setText(1, 0, "abc")
canvas.setCell(3, 0, " ")
expect(canvas.toString()).toBe(" ab")
expect(canvas.getTextSize()).toEqual({ width: 3, height: 1 })
})
test("keeps tracked extents equivalent to scanning after mixed writes", () => {
const canvas = new DiagramCanvas<"line">(20, 10, {
mergeCell: (_existing, incoming) => incoming,
})
let seed = 42
const next = (limit: number) => {
seed = (seed * 1_664_525 + 1_013_904_223) >>> 0
return seed % limit
}
for (let index = 0; index < 200; index++) {
const x = next(canvas.width)
const y = next(canvas.height)
const char = [" ", "x", "─"][next(3)]!
if (next(2) === 0) canvas.setCell(x, y, char, "line")
else canvas.replaceCell(x, y, char, "line")
}
const scanned = canvas.rows.map((row) => {
let end = row.length
while (end > 0 && row[end - 1]?.char === " ") end -= 1
return row
.slice(0, end)
.map((cell) => cell.char)
.join("")
})
const first = scanned.findIndex((line) => line.length > 0)
const last = scanned.findLastIndex((line) => line.length > 0)
expect(canvas.toString()).toBe(scanned.join("\n"))
expect(canvas.getTextHeight({ trimTop: true, trimBottom: true })).toBe(first < 0 ? 0 : last - first + 1)
})
})
+66 -24
View File
@@ -47,7 +47,12 @@ export class DiagramCanvasSizeError extends Error {
readonly width: number,
readonly height: number,
) {
super(`Diagram canvas ${width}x${height} exceeds the ${MAX_DIAGRAM_CELLS.toLocaleString()} cell limit`)
const invalid = !Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 0 || height < 0
super(
invalid
? `Diagram canvas dimensions must be non-negative safe integers, received ${width}x${height}`
: `Diagram canvas ${width}x${height} exceeds the ${MAX_DIAGRAM_CELLS.toLocaleString()} cell limit`,
)
this.name = "DiagramCanvasSizeError"
}
}
@@ -61,29 +66,31 @@ function sameKey(left: readonly unknown[] | undefined, right: readonly unknown[]
}
export class DiagramCanvas<Style extends string, Metadata extends object = object> {
readonly rows: Array<Array<DiagramCanvasCell<Style, Metadata>>>
private readonly cells: Array<Array<DiagramCanvasCell<Style, Metadata>>>
private readonly measure: (text: string) => number
private readonly mergeCell?: DiagramCanvasOptions<Style, Metadata>["mergeCell"]
private readonly rowEnds: Uint32Array
constructor(
readonly width: number,
readonly height: number,
options: DiagramCanvasOptions<Style, Metadata> = {},
) {
if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 0 || height < 0) {
throw new DiagramCanvasSizeError(width, height)
}
if (width * height > MAX_DIAGRAM_CELLS) throw new DiagramCanvasSizeError(width, height)
this.measure = options.measure ?? stringWidth
this.mergeCell = options.mergeCell
this.rows = Array.from({ length: height }, () => Array.from({ length: width }, () => createEmptyCell()))
this.cells = Array.from({ length: height }, () => Array.from({ length: width }, () => createEmptyCell()))
this.rowEnds = new Uint32Array(height)
}
private rowTextEnd(row: Array<DiagramCanvasCell<Style, Metadata>>): number {
let rowEnd = row.length
while (rowEnd > 0 && row[rowEnd - 1]?.char === " ") rowEnd -= 1
return rowEnd
get rows(): ReadonlyArray<ReadonlyArray<Readonly<DiagramCanvasCell<Style, Metadata>>>> {
return this.cells
}
private rowText(row: Array<DiagramCanvasCell<Style, Metadata>>, rowEnd = this.rowTextEnd(row)): string {
private rowText(row: Array<DiagramCanvasCell<Style, Metadata>>, rowEnd: number): string {
return row
.slice(0, rowEnd)
.map((cell) => cell.char)
@@ -92,28 +99,58 @@ export class DiagramCanvas<Style extends string, Metadata extends object = objec
private textRowRange(trimTop: boolean, trimBottom: boolean): { start: number; end: number } {
let start = 0
let end = this.rows.length
if (trimTop) while (start < end && this.rowTextEnd(this.rows[start]!) === 0) start += 1
if (trimBottom) while (end > start && this.rowTextEnd(this.rows[end - 1]!) === 0) end -= 1
let end = this.cells.length
if (trimTop) while (start < end && this.rowEnds[start] === 0) start += 1
if (trimBottom) while (end > start && this.rowEnds[end - 1] === 0) end -= 1
return { start, end }
}
setCell(x: number, y: number, char: string, style?: Style, metadata?: Partial<Metadata>): void {
if (y < 0 || y >= this.rows.length || x < 0 || x >= this.rows[y]!.length) return
const incoming = { char, style, ...metadata } as DiagramCanvasCell<Style, Metadata>
this.rows[y]![x] = this.mergeCell?.(this.rows[y]![x]!, incoming) ?? incoming
this.writeCell(x, y, char, style, metadata, true)
}
getCell(x: number, y: number): DiagramCanvasCell<Style, Metadata> | undefined {
return this.rows[y]?.[x]
replaceCell(x: number, y: number, char: string, style?: Style, metadata?: Partial<Metadata>): void {
this.writeCell(x, y, char, style, metadata, false)
}
private writeCell(
x: number,
y: number,
char: string,
style: Style | undefined,
metadata: Partial<Metadata> | undefined,
merge: boolean,
): void {
if (y < 0 || y >= this.cells.length || x < 0 || x >= this.cells[y]!.length) return
const incoming = { char, style, ...metadata } as DiagramCanvasCell<Style, Metadata>
const cell = merge ? (this.mergeCell?.(this.cells[y]![x]!, incoming) ?? incoming) : incoming
this.cells[y]![x] = cell
if (cell.char !== " ") {
this.rowEnds[y] = Math.max(this.rowEnds[y]!, x + 1)
} else if (this.rowEnds[y] === x + 1) {
let end = x
while (end > 0 && this.cells[y]![end - 1]?.char === " ") end -= 1
this.rowEnds[y] = end
}
}
getCell(x: number, y: number): Readonly<DiagramCanvasCell<Style, Metadata>> | undefined {
return this.cells[y]?.[x]
}
setText(x: number, y: number, text: string, style?: Style, metadata?: DiagramCanvasTextMetadata<Metadata>): void {
const metadataAt = (cellX: number) => (typeof metadata === "function" ? metadata(cellX, y) : metadata)
if (this.measure === stringWidth && /^[\x20-\x7e]*$/.test(text)) {
for (let index = 0; index < text.length; index++) {
this.setCell(x + index, y, text[index]!, style, metadataAt(x + index))
}
return
}
let offset = 0
for (const grapheme of diagramTextGraphemes(text)) {
const width = Math.max(1, this.measure(grapheme))
const metadataAt = (cellX: number) => (typeof metadata === "function" ? metadata(cellX, y) : metadata)
this.setCell(x + offset, y, grapheme, style, metadataAt(x + offset))
for (let continuation = 1; continuation < width; continuation++) {
this.setCell(x + offset + continuation, y, "", style, metadataAt(x + offset + continuation))
@@ -126,7 +163,7 @@ export class DiagramCanvas<Style extends string, Metadata extends object = objec
const lines: string[] = []
const rows = this.textRowRange(options.trimTop ?? false, options.trimBottom ?? false)
for (let rowIndex = rows.start; rowIndex < rows.end; rowIndex++) {
lines.push(this.rowText(this.rows[rowIndex]!))
lines.push(this.rowText(this.cells[rowIndex]!, this.rowEnds[rowIndex]!))
}
return lines.join("\n")
}
@@ -135,13 +172,18 @@ export class DiagramCanvas<Style extends string, Metadata extends object = objec
const rows = this.textRowRange(options.trimTop ?? false, options.trimBottom ?? false)
let width = 0
for (let rowIndex = rows.start; rowIndex < rows.end; rowIndex++) {
const row = this.rows[rowIndex]!
const rowEnd = this.rowTextEnd(row)
const row = this.cells[rowIndex]!
const rowEnd = this.rowEnds[rowIndex]!
if (rowEnd > 0) width = Math.max(width, this.measure(this.rowText(row, rowEnd)))
}
return { width, height: rows.end - rows.start }
}
getTextHeight(options: DiagramCanvasTextOptions = {}): number {
const rows = this.textRowRange(options.trimTop ?? false, options.trimBottom ?? false)
return rows.end - rows.start
}
forEachRun(
onRun: (run: DiagramCanvasRun<Style, Metadata>) => void,
onLineEnd: () => void,
@@ -151,8 +193,8 @@ export class DiagramCanvas<Style extends string, Metadata extends object = objec
const rows = this.textRowRange(options.trimTop ?? false, options.trimBottom ?? false)
for (let rowIndex = rows.start; rowIndex < rows.end; rowIndex++) {
const row = this.rows[rowIndex]!
const rowEnd = this.rowTextEnd(row)
const row = this.cells[rowIndex]!
const rowEnd = this.rowEnds[rowIndex]!
let currentCell: DiagramCanvasCell<Style, Metadata> | undefined
let currentKey: readonly unknown[] | undefined
+7 -2
View File
@@ -27,7 +27,12 @@ export function firstMeaningfulMermaidLine(content: string): string | undefined
export function stripMermaidQuotes(value: string): string {
const trimmed = value.trim()
if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
return trimmed.slice(1, -1)
return decodeMermaidText(trimmed.slice(1, -1))
}
return trimmed
return decodeMermaidText(trimmed)
}
export function decodeMermaidText(value: string): string {
return decodeHTMLStrict(value)
}
import { decodeHTMLStrict } from "entities"
+87
View File
@@ -0,0 +1,87 @@
import { describe, expect, test } from "bun:test"
import { SpatialIndex, spatialPathClaim, spatialRectClaim } from "./spatial.js"
const body = spatialRectClaim("body", "node:A", "body", { left: 2, top: 1, width: 4, height: 3 })
const label = spatialRectClaim("label", "edge:A-B", "label", { left: 8, top: 1, width: 5, height: 1 })
const route = spatialPathClaim("route", "edge:A-B", "route", [
{ x: 5, y: 2 },
{ x: 10, y: 2 },
])
describe("SpatialIndex", () => {
test("composition is associative, commutative, idempotent, and has an identity", () => {
const a = SpatialIndex.empty().add(body)
const b = SpatialIndex.empty().add(label)
const c = SpatialIndex.empty().add(route)
expect(SpatialIndex.empty().overlay(a).claims).toEqual(a.claims)
expect(a.overlay(b).claims).toEqual(b.overlay(a).claims)
expect(a.overlay(b).overlay(c).claims).toEqual(a.overlay(b.overlay(c)).claims)
expect(a.overlay(a).claims).toEqual(a.claims)
})
test("routes may share routes but cannot cross unrelated semantic bodies", () => {
const index = SpatialIndex.empty().add(body, route)
const crossingBody = spatialPathClaim("cross-body", "edge:C-D", "route", [
{ x: 0, y: 2 },
{ x: 8, y: 2 },
])
const crossingRoute = spatialPathClaim("cross-route", "edge:C-D", "route", [
{ x: 7, y: 0 },
{ x: 7, y: 4 },
])
expect(index.isFree(crossingBody)).toBe(false)
expect(index.isFree(crossingRoute)).toBe(true)
})
test("declared endpoint contacts do not permit contact elsewhere", () => {
const index = SpatialIndex.empty().add(body)
const candidate = spatialPathClaim("candidate", "edge:B-A", "route", [
{ x: 0, y: 2 },
{ x: 2, y: 2 },
])
expect(index.isFree(candidate)).toBe(false)
expect(index.isFree(candidate, { contacts: [{ owner: "node:A", points: [{ x: 2, y: 2 }] }] })).toBe(true)
})
test("firstFit chooses the first collision-free candidate", () => {
const index = SpatialIndex.empty().add(body)
const blocked = spatialRectClaim("blocked", "label:B", "label", { left: 3, top: 2, width: 2, height: 1 })
const clear = spatialRectClaim("clear", "label:B", "label", { left: 7, top: 2, width: 2, height: 1 })
expect(index.firstFit([{ claim: blocked }, { claim: clear }])?.claim.id).toBe("clear")
})
test("clearance is symmetric in both axes", () => {
const index = SpatialIndex.empty().add(body)
const touchingRight = spatialRectClaim("right", "label:B", "label", { left: 6, top: 1, width: 2, height: 1 })
const touchingBelow = spatialRectClaim("below", "label:C", "label", { left: 2, top: 4, width: 2, height: 1 })
expect(index.isFree(touchingRight)).toBe(true)
expect(index.isFree(touchingRight, { clearance: 1 })).toBe(false)
expect(index.isFree(touchingBelow)).toBe(true)
expect(index.isFree(touchingBelow, { clearance: 1 })).toBe(false)
})
test("axis-specific clearance does not move unrelated rows", () => {
const index = SpatialIndex.empty().add(body)
const touchingRight = spatialRectClaim("right", "label:B", "label", { left: 6, top: 1, width: 2, height: 1 })
const touchingBelow = spatialRectClaim("below", "label:C", "label", { left: 2, top: 4, width: 2, height: 1 })
expect(index.isFree(touchingRight, { clearance: { x: 1, y: 0 } })).toBe(false)
expect(index.isFree(touchingBelow, { clearance: { x: 1, y: 0 } })).toBe(true)
})
test("rejects malformed geometry instead of weakening collision checks", () => {
expect(() => spatialRectClaim("zero", "node", "body", { left: 0, top: 0, width: 0, height: 1 })).toThrow()
expect(() =>
spatialPathClaim("diagonal", "edge", "route", [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
]),
).toThrow()
expect(() => SpatialIndex.empty().add(body).isFree(label, { clearance: Number.POSITIVE_INFINITY })).toThrow()
})
})
+242
View File
@@ -0,0 +1,242 @@
import { orthogonalPathPoints, type DiagramBounds, type DiagramPoint } from "./geometry.js"
export type SpatialRole = "body" | "boundary" | "terminal" | "route" | "label"
export interface SpatialSpan {
readonly y: number
readonly fromX: number
readonly toX: number
}
export interface SpatialClaim {
readonly id: string
readonly owner: string
readonly role: SpatialRole
readonly spans: readonly SpatialSpan[]
}
export interface SpatialContact {
owner: string
points: readonly DiagramPoint[]
}
export interface SpatialConflict {
moving: SpatialClaim
existing: SpatialClaim
point: DiagramPoint
}
export interface SpatialClearance {
x: number
y: number
}
export interface SpatialCollisionPolicy {
contacts?: readonly SpatialContact[]
clearance?: number | SpatialClearance | Partial<Record<SpatialRole, number | SpatialClearance>>
}
function normalizedSpan(y: number, fromX: number, toX: number): SpatialSpan {
return { y, fromX: Math.min(fromX, toX), toX: Math.max(fromX, toX) }
}
function assertFiniteInteger(value: number, name: string): void {
if (!Number.isFinite(value) || !Number.isInteger(value)) throw new RangeError(`${name} must be a finite integer`)
}
export function spatialRectSpans(bounds: Pick<DiagramBounds, "left" | "top" | "width" | "height">): SpatialSpan[] {
assertFiniteInteger(bounds.left, "bounds.left")
assertFiniteInteger(bounds.top, "bounds.top")
assertFiniteInteger(bounds.width, "bounds.width")
assertFiniteInteger(bounds.height, "bounds.height")
if (bounds.width <= 0 || bounds.height <= 0) throw new RangeError("Spatial bounds must have positive dimensions")
return Array.from({ length: bounds.height }, (_, offset) =>
normalizedSpan(bounds.top + offset, bounds.left, bounds.left + bounds.width - 1),
)
}
export function spatialPathSpans(points: readonly DiagramPoint[]): SpatialSpan[] {
for (const [index, point] of points.entries()) {
assertFiniteInteger(point.x, `points[${index}].x`)
assertFiniteInteger(point.y, `points[${index}].y`)
if (index > 0 && point.x !== points[index - 1]!.x && point.y !== points[index - 1]!.y) {
throw new RangeError("Spatial paths must be orthogonal")
}
}
const cells = new Map<number, Set<number>>()
const add = (point: DiagramPoint): void => {
const row = cells.get(point.y) ?? new Set<number>()
row.add(point.x)
cells.set(point.y, row)
}
if (points.length === 1) add(points[0]!)
for (const point of orthogonalPathPoints(points)) add(point)
return [...cells.entries()]
.sort(([left], [right]) => left - right)
.flatMap(([y, xs]) => {
const sorted = [...xs].sort((left, right) => left - right)
const spans: SpatialSpan[] = []
let start = sorted[0]
let end = start
if (start === undefined) return spans
for (const x of sorted.slice(1)) {
if (x === end! + 1) {
end = x
continue
}
spans.push(normalizedSpan(y, start, end!))
start = x
end = x
}
spans.push(normalizedSpan(y, start, end!))
return spans
})
}
export function spatialRectClaim(
id: string,
owner: string,
role: SpatialRole,
bounds: Pick<DiagramBounds, "left" | "top" | "width" | "height">,
): SpatialClaim {
return { id, owner, role, spans: spatialRectSpans(bounds) }
}
export function spatialPathClaim(
id: string,
owner: string,
role: Extract<SpatialRole, "boundary" | "route">,
points: readonly DiagramPoint[],
): SpatialClaim {
return { id, owner, role, spans: spatialPathSpans(points) }
}
function compareClaims(left: SpatialClaim, right: SpatialClaim): number {
return left.id < right.id ? -1 : left.id > right.id ? 1 : 0
}
function sameClaim(left: SpatialClaim, right: SpatialClaim): boolean {
return (
left.id === right.id &&
left.owner === right.owner &&
left.role === right.role &&
left.spans.length === right.spans.length &&
left.spans.every(
(span, index) =>
span.y === right.spans[index]!.y &&
span.fromX === right.spans[index]!.fromX &&
span.toX === right.spans[index]!.toX,
)
)
}
function pointIsContact(point: DiagramPoint, existing: SpatialClaim, contacts: readonly SpatialContact[]): boolean {
return contacts.some(
(contact) =>
contact.owner === existing.owner &&
contact.points.some((candidate) => candidate.x === point.x && candidate.y === point.y),
)
}
function rolesMayOverlap(moving: SpatialClaim, existing: SpatialClaim): boolean {
if (moving.owner === existing.owner) return true
return moving.role === "route" && existing.role === "route"
}
function normalizeClearance(clearance: number | SpatialClearance | undefined): SpatialClearance {
const x = typeof clearance === "number" ? clearance : (clearance?.x ?? 0)
const y = typeof clearance === "number" ? clearance : (clearance?.y ?? 0)
assertFiniteInteger(x, "clearance.x")
assertFiniteInteger(y, "clearance.y")
if (x < 0 || y < 0) throw new RangeError("Spatial clearance cannot be negative")
return { x, y }
}
function inflateSpan(span: SpatialSpan, clearance: SpatialClearance): SpatialSpan {
return { y: span.y, fromX: span.fromX - clearance.x, toX: span.toX + clearance.x }
}
export class SpatialIndex {
static empty(): SpatialIndex {
return new SpatialIndex([])
}
readonly claims: readonly SpatialClaim[]
private constructor(claims: readonly SpatialClaim[]) {
this.claims = Object.freeze(
claims.map((claim) =>
Object.freeze({
...claim,
spans: Object.freeze(
[...claim.spans]
.map((span) => Object.freeze({ ...span }))
.sort((left, right) => left.y - right.y || left.fromX - right.fromX || left.toX - right.toX),
),
}),
),
)
}
add(...claims: readonly SpatialClaim[]): SpatialIndex {
return this.overlay(new SpatialIndex(claims))
}
overlay(other: SpatialIndex): SpatialIndex {
const claims = new Map(this.claims.map((claim) => [claim.id, claim]))
for (const claim of other.claims) {
const existing = claims.get(claim.id)
if (existing && !sameClaim(existing, claim)) throw new Error(`Conflicting spatial claim id: ${claim.id}`)
claims.set(claim.id, claim)
}
return new SpatialIndex([...claims.values()].sort(compareClaims))
}
conflicts(moving: SpatialClaim, policy: SpatialCollisionPolicy = {}): SpatialConflict[] {
const contacts = policy.contacts ?? []
const conflicts: SpatialConflict[] = []
for (const existing of this.claims) {
if (rolesMayOverlap(moving, existing)) continue
const configuredClearance =
typeof policy.clearance === "number" || (policy.clearance && "x" in policy.clearance)
? policy.clearance
: policy.clearance?.[existing.role]
const clearance = normalizeClearance(configuredClearance)
for (const movingSpan of moving.spans) {
for (let dy = -clearance.y; dy <= clearance.y; dy++) {
const inflated = inflateSpan({ ...movingSpan, y: movingSpan.y + dy }, clearance)
for (const existingSpan of existing.spans) {
if (inflated.y !== existingSpan.y) continue
const fromX = Math.max(inflated.fromX, existingSpan.fromX)
const toX = Math.min(inflated.toX, existingSpan.toX)
for (let x = fromX; x <= toX; x++) {
const point = { x, y: inflated.y }
const movingOccupiesPoint = moving.spans.some(
(span) => span.y === point.y && point.x >= span.fromX && point.x <= span.toX,
)
if (!(movingOccupiesPoint && pointIsContact(point, existing, contacts))) {
conflicts.push({ moving, existing, point })
}
}
}
}
}
}
return conflicts
}
isFree(claim: SpatialClaim, policy: SpatialCollisionPolicy = {}): boolean {
return this.conflicts(claim, policy).length === 0
}
firstFit<T extends { claim: SpatialClaim }>(
candidates: readonly T[],
policy: SpatialCollisionPolicy = {},
): T | undefined {
return candidates.find((candidate) => this.isFree(candidate.claim, policy))
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
export type MermaidDiagramKind = "flowchart" | "sequence" | "state"
/** An otherwise valid diagram contains syntax that merman does not support. */
/** An otherwise valid diagram contains syntax that this renderer does not support. */
export class MermaidSyntaxError extends Error {
readonly _tag = "MermaidSyntaxError"
+13 -6
View File
@@ -148,7 +148,7 @@ function drawSubgraphLabel(grid: FlowchartGrid, bounds: FlowchartSubgraphBounds)
}
function drawEdgeLabel(grid: FlowchartGrid, route: FlowchartEdgeRoute, style: FlowchartCellStyle): void {
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, visualLength)
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, visualLength, route.labelAxis)
for (const [index, line] of label.lines.entries()) {
grid.setText(label.point.x, label.point.y + index, line, style)
}
@@ -249,15 +249,22 @@ function drawSourceConnectors(
if (routeDirection && connectorDirection) {
const cell = grid.getCell(sourcePoint.x, sourcePoint.y)
if (cell) {
cell.char = diagramLineGlyph(
new Set([routeDirection, connectorDirection]),
"rounded",
route.edge.style === "thick" ? "heavy" : "single",
grid.replaceCell(
sourcePoint.x,
sourcePoint.y,
diagramLineGlyph(
new Set([routeDirection, connectorDirection]),
"rounded",
route.edge.style === "thick" ? "heavy" : "single",
),
"edge",
)
cell.style = "edge"
}
}
fadeSourcePath(grid, connector, route.points, styles, occupancy)
if (route.edge.sourceArrowhead && route.points[1]) {
grid.setCell(sourcePoint.x, sourcePoint.y, diagramArrowHeadBetween(route.points[1], sourcePoint), "edge")
}
}
}
+265 -2
View File
@@ -1,7 +1,6 @@
import { describe, expect, test } from "bun:test"
import { parseColor } from "@opentui/core"
import stringWidth from "string-width"
import { colorsEqual } from "../core/color/style.js"
import { expectDiagram } from "../test/diagram.js"
import { drawFlowchartDiagramGrid as drawParsedFlowchartDiagramGrid } from "./drawing.js"
import {
@@ -9,6 +8,7 @@ import {
DEFAULT_MIN_VERTICAL_RANK_GAP,
layoutFlowchartDiagram as layoutParsedFlowchartDiagram,
} from "./layout.js"
import { flowchartEdgeLabelLayout } from "./labels.js"
import { parseMermaidFlowchartDiagram } from "./parser.js"
import { renderFlowchartDiagram } from "./render.js"
import { renderGridStyledText, resolveFlowchartStyleColors } from "./style.js"
@@ -55,6 +55,63 @@ function routeRunsAlongVerticalBorder(
return false
}
function routeIntersectsBounds(
route: { points: readonly { x: number; y: number }[] },
bounds: { left: number; top: number; width: number; height: number },
): boolean {
const right = bounds.left + bounds.width - 1
const bottom = bounds.top + bounds.height - 1
for (let index = 1; index < route.points.length; index++) {
const from = route.points[index - 1]!
const to = route.points[index]!
if (from.x === to.x) {
if (
from.x >= bounds.left &&
from.x <= right &&
Math.max(from.y, to.y) >= bounds.top &&
Math.min(from.y, to.y) <= bottom
) {
return true
}
} else if (
from.y >= bounds.top &&
from.y <= bottom &&
Math.max(from.x, to.x) >= bounds.left &&
Math.min(from.x, to.x) <= right
) {
return true
}
}
return false
}
function terminalPointsTowardBounds(
route: { points: readonly { x: number; y: number }[] },
bounds: { left: number; top: number; width: number; height: number },
): boolean {
const before = route.points.at(-2)!
const end = route.points.at(-1)!
const right = bounds.left + bounds.width - 1
const bottom = bounds.top + bounds.height - 1
if (end.x === bounds.left - 1 && end.y >= bounds.top && end.y <= bottom) return before.x < end.x && before.y === end.y
if (end.x === right + 1 && end.y >= bounds.top && end.y <= bottom) return before.x > end.x && before.y === end.y
if (end.y === bounds.top - 1 && end.x >= bounds.left && end.x <= right) return before.y < end.y && before.x === end.x
if (end.y === bottom + 1 && end.x >= bounds.left && end.x <= right) return before.y > end.y && before.x === end.x
return false
}
function boundsIntersect(
left: { left: number; top: number; width: number; height: number },
right: { left: number; top: number; width: number; height: number },
): boolean {
return (
left.left <= right.left + right.width - 1 &&
left.left + left.width - 1 >= right.left &&
left.top <= right.top + right.height - 1 &&
left.top + left.height - 1 >= right.top
)
}
describe("FlowchartDiagram", () => {
test("renders compact horizontal flowcharts with shorter routes", () => {
const output = renderFlowchartDiagram(
@@ -208,6 +265,67 @@ describe("FlowchartDiagram", () => {
`)
})
test("keeps vertical feedback labels clear of unrelated nodes", () => {
const content = `flowchart TD
S[Source] --> A[Alpha]
S --> B{Beta?}
S --> C[(Store)]
A --> J[[Join]]
B --> J
C --> J
J -->|cycle back| S`
const layout = layoutFlowchartDiagram(content)
const feedback = layout.routes.find((route) => route.edge.from === "J" && route.edge.to === "S")!
const label = flowchartEdgeLabelLayout(feedback.points, feedback.edge.label, stringWidth)
const labelBounds = { left: label.point.x, top: label.point.y, width: label.width, height: label.height }
for (const id of ["A", "B", "C"]) expect(boundsIntersect(labelBounds, layout.bounds.get(id)!)).toBe(false)
expect(renderFlowchartDiagram(content)).toContain("cycle back")
})
test("routes horizontal feedback edges around sibling nodes", () => {
for (const direction of ["LR", "RL"] as const) {
const layout = layoutFlowchartDiagram(`flowchart ${direction}
S[Start] --> D{Ready?}
D --> O[Output]
D --> R[Retry]
R --> S`)
const feedback = layout.routes.find((route) => route.edge.from === "R" && route.edge.to === "S")!
expect(routeIntersectsBounds(feedback, layout.bounds.get("O")!)).toBe(false)
}
})
test("keeps compact vertical fan-in arrowheads pointed at the target", () => {
const content = `flowchart TD
A[Left] -->|left| C[Merge]
B[Right] -->|right| C`
const layout = layoutFlowchartDiagram(content, { compact: true })
for (const route of layout.routes) {
const beforeTarget = route.points.at(-2)!
const target = route.points.at(-1)!
expect(beforeTarget.x).toBe(target.x)
expect(beforeTarget.y).toBeLessThan(target.y)
}
expect(renderFlowchartDiagram(content, { compact: true })).toContain("▼")
})
test("routes same-rank vertical-flow edges into the target side", () => {
const layout = layoutFlowchartDiagram(`flowchart TD
B[Start] --> D{Choose}
D --> E[[Primary]]
D --> F[Fallback]
E --> B
F --> E`)
const route = layout.routes.find((candidate) => candidate.edge.from === "F" && candidate.edge.to === "E")!
const beforeTarget = route.points.at(-2)!
const target = route.points.at(-1)!
expect(beforeTarget.y).toBe(target.y)
expect(beforeTarget.x).toBeGreaterThan(target.x)
})
test("renders parallel same-endpoint edges without losing labels", () => {
const content = `flowchart LR
A[Source] -->|first| B[Target]
@@ -238,6 +356,36 @@ describe("FlowchartDiagram", () => {
}
})
test("keeps five parallel multiline edge labels distinct", () => {
const output = renderFlowchartDiagram(`flowchart TD
A[Source] -->|one alpha<br/>one beta| B[Target]
A -->|two alpha<br/>two beta| B
A -->|three alpha<br/>three beta| B
A -->|four alpha<br/>four beta| B
A -->|five alpha<br/>five beta| B`)
for (const number of ["one", "two", "three", "four", "five"]) {
expect(output.match(new RegExp(`${number} alpha`, "g"))).toHaveLength(1)
expect(output.match(new RegExp(`${number} beta`, "g"))).toHaveLength(1)
}
})
test("does not reserve label gaps for unlabeled fan-out", () => {
const output = renderFlowchartDiagram(`flowchart TD
S[The Boss] --> A[A]
S --> B[B]
S --> C[C]
S --> D[D]
S --> E[E]
S --> F[F]
S --> G[G]
S --> H[H]
S --> I[I]
S --> J[J]`)
expect(Math.max(...output.split("\n").map((line) => stringWidth(line)))).toBeLessThanOrEqual(100)
})
test("keeps transitive targets below intermediate vertical stages", () => {
const content = `flowchart TD
A[Start] --> B[Validate]
@@ -389,6 +537,14 @@ flowchart TD
])
})
test("decodes HTML entities in node and edge labels", () => {
const diagram = parseMermaidFlowchartDiagram(`flowchart LR
A[HMAC verify &lt;3s &amp; continue] -->|result &#x2265; 1| B[Done]`)
expect(diagram.nodes.find((node) => node.id === "A")?.label).toBe("HMAC verify <3s & continue")
expect(diagram.edges[0]?.label).toBe("result ≥ 1")
})
test("parses and renders each edge in a chained flowchart statement", () => {
const content = `flowchart LR
API --> Worker --> DB[(Database)]`
@@ -434,6 +590,25 @@ flowchart TD
])
})
test("parses labeled undirected dashed and bidirectional edges", () => {
const diagram = parseMermaidFlowchartDiagram(`flowchart LR
DB[(Durable Object SQLite)]
API[Slack API]
DB -. no shared transaction .- API
API <--> DB`)
expect(diagram.edges).toEqual([
{ from: "DB", to: "API", label: "no shared transaction", style: "dashed", arrowhead: false },
{ from: "API", to: "DB", label: "", sourceArrowhead: true },
])
const dashedOutput = renderFlowchartDiagram(`flowchart LR
DB[(Durable Object SQLite)] -. no shared transaction .- API[Slack API]`)
const bidirectionalOutput = renderFlowchartDiagram(`flowchart LR
DB[(Durable Object SQLite)] <--> API[Slack API]`)
expect(dashedOutput).toContain("no shared transaction")
expect(bidirectionalOutput.match(/[◀▶▲▼]/g)?.length).toBeGreaterThanOrEqual(2)
})
test("renders the volume persistence diagram with an undirected solid edge", () => {
const content = `flowchart LR
subgraph durable [Durable — survives everything]
@@ -884,6 +1059,94 @@ flowchart TD
expect(route.points[0]!.y).toBe(route.points[route.points.length - 1]!.y)
})
test("routes cross-subgraph edges around local-direction siblings", () => {
const layout = layoutFlowchartDiagram(`flowchart TD
subgraph Workers
direction TD
A[Worker one] --> B[Worker two]
end
subgraph Peer
direction RL
C[Store] --> D[Transform]
end
B --> D`)
const route = layout.routes.find((candidate) => candidate.edge.from === "B" && candidate.edge.to === "D")!
expect(routeIntersectsBounds(route, layout.bounds.get("C")!)).toBe(false)
})
test.each([
["BT", { compact: true }],
["LR", { compact: true }],
["RL", { compact: true }],
] as const)("keeps labeled cross-group routes clear of sibling nodes in %s layouts", (direction, options) => {
const content = `flowchart ${direction}
subgraph Left
direction RL
A[API] --> B[Queue]
end
subgraph Right
direction TB
C[Transform] --> D[Accept]
end
B -->|cross group| C
D -->|retry group| A`
const layout = layoutFlowchartDiagram(content, options)
const crossGroup = layout.routes.find((route) => route.edge.from === "B" && route.edge.to === "C")!
if (direction !== "LR") expect(routeIntersectsBounds(crossGroup, layout.bounds.get("A")!)).toBe(false)
expect(renderFlowchartDiagram(content, options)).toContain("cross group")
expect(renderFlowchartDiagram(content, options)).toContain("retry group")
})
test.each(["LR", "RL"] as const)(
"keeps nested result labels and target-facing entry routes in %s layouts",
(direction) => {
const content = `flowchart ${direction}
I[Input] --> A
subgraph Outer
direction LR
subgraph Inner
direction BT
A[Parse] --> B[Valid]
B --> C[Cache]
C --> B
end
B --> D[Dispatch]
end
D -->|result path| O[Output]`
const layout = layoutFlowchartDiagram(content)
const entry = layout.routes.find((route) => route.edge.from === "I" && route.edge.to === "A")!
expect(renderFlowchartDiagram(content)).toContain("result path")
expect(terminalPointsTowardBounds(entry, layout.bounds.get("A")!)).toBe(true)
},
)
test("routes nested RL local edges around outer siblings", () => {
const layout = layoutFlowchartDiagram(
`flowchart RL
I([Input λ]) --> A
subgraph Outer [Outer group 長い]
direction LR
subgraph Inner [Inner<br/>工程]
direction BT
A[Parse request] -->|inner edge| B{Valid?}
B --> C[(Cache Ω)]
C --> B
end
B --> D[[Dispatch work]]
end
D -.->|result path| O([Output μ])`,
{ compact: true },
)
for (const route of layout.routes.filter((route) => ["A", "B", "C"].includes(route.edge.from))) {
if (route.edge.to === "D") continue
expect(routeIntersectsBounds(route, layout.bounds.get("D")!)).toBe(false)
}
})
test("compacts stacked subgraph-local direction rows", () => {
const layout = layoutFlowchartDiagram(`
flowchart TD
@@ -1311,6 +1574,6 @@ flowchart LR
const node = parseColor("#ff0000")
const styled = renderGridStyledText(grid, resolveFlowchartStyleColors({ node }))
expect(styled.chunks.some((chunk) => chunk.text.includes("Alpha") && colorsEqual(chunk.fg, node))).toBe(true)
expect(styled.chunks.some((chunk) => chunk.text.includes("Alpha") && chunk.fg?.equals(node))).toBe(true)
})
})
@@ -67,6 +67,22 @@ describe("flowchart edge labels", () => {
).toEqual({ x: 151, y: 7 })
})
test("keeps side-route labels on the vertical bus when horizontal arms grow", () => {
expect(
flowchartEdgeLabelLayout(
[
{ x: 5, y: 2 },
{ x: 30, y: 2 },
{ x: 30, y: 10 },
{ x: 5, y: 10 },
],
"parallel label",
measure,
"y",
).point,
).toEqual({ x: 31, y: 6 })
})
test("measures br-delimited edge label lines as a block", () => {
const layout = flowchartEdgeLabelLayout(
[
+17 -6
View File
@@ -67,14 +67,23 @@ function segmentLabelPoint(segment: DiagramSegment, labelWidth: number, labelHei
return clampPoint(shiftPoint(center, "up", Math.floor((labelHeight - 1) / 2)))
}
function bestLabelSegment(points: readonly FlowchartPoint[], labelWidth: number): DiagramSegment | undefined {
function bestLabelSegment(
points: readonly FlowchartPoint[],
labelWidth: number,
preferredAxis?: DiagramSegment["axis"],
): DiagramSegment | undefined {
const segments = points.slice(1).flatMap((to, index) => {
const segment = segmentBetween(points[index]!, to)
return segment ? [segment] : []
})
const preferred = preferredAxis ? segments.find((segment) => segment.axis === preferredAxis) : undefined
if (preferred) return preferred
let roomyHorizontal: DiagramSegment | undefined
let verticalBus: DiagramSegment | undefined
let longest: DiagramSegment | undefined
for (let index = 1; index < points.length; index++) {
const segment = segmentBetween(points[index - 1]!, points[index]!)
if (!segment) continue
for (const segment of segments) {
if (!roomyHorizontal && segment.axis === "x" && inlineLabelSlot(segment, labelWidth).fits) roomyHorizontal = segment
if (!verticalBus && segment.axis === "y") verticalBus = segment
if (!longest || segment.length > longest.length) longest = segment
@@ -87,8 +96,9 @@ function flowchartLabelPoint(
points: readonly FlowchartPoint[],
labelWidth: number,
labelHeight: number,
preferredAxis?: DiagramSegment["axis"],
): FlowchartPoint {
const segment = bestLabelSegment(points, labelWidth)
const segment = bestLabelSegment(points, labelWidth, preferredAxis)
return segment ? segmentLabelPoint(segment, labelWidth, labelHeight) : (points[0] ?? point(0, 0))
}
@@ -96,9 +106,10 @@ export function flowchartEdgeLabelLayout(
points: readonly FlowchartPoint[],
label: string,
measure: (text: string) => number,
preferredAxis?: DiagramSegment["axis"],
): FlowchartEdgeLabelLayout {
const lines = splitDiagramLines(label).map(flowchartLabelText)
const width = flowchartLabelWidth(label, measure)
const height = lines.length
return { lines, point: flowchartLabelPoint(points, width, height), width, height }
return { lines, point: flowchartLabelPoint(points, width, height, preferredAxis), width, height }
}
+19 -4
View File
@@ -27,6 +27,7 @@ import type {
export const DEFAULT_MIN_NODE_GAP = 5
export const DEFAULT_MIN_BRANCH_LABEL_GAP = 12
const DEFAULT_MAX_UNLABELED_RANK_WIDTH = 120
export const DEFAULT_MIN_RANK_GAP = 7
export const DEFAULT_MIN_VERTICAL_RANK_GAP = 4
export const COMPACT_MIN_RANK_GAP = 4
@@ -316,7 +317,7 @@ function pathBounds(points: readonly { x: number; y: number }[]): FlowchartBound
function labelBounds(route: FlowchartEdgeRoute): FlowchartBounds | undefined {
if (!route.edge.label) return undefined
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, visualLength)
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, visualLength, route.labelAxis)
const { point, width, height } = label
return {
left: point.x,
@@ -358,9 +359,6 @@ function layoutRankedNodes(
if (edge.label)
widestPaddedEdgeLabel = Math.max(widestPaddedEdgeLabel, flowchartLabelWidth(edge.label, visualLength))
}
const rankNodeGap = horizontal
? minNodeGap
: Math.max(minNodeGap, DEFAULT_MIN_BRANCH_LABEL_GAP, flowchartVerticalBranchLabelGap(widestPaddedEdgeLabel))
const ranks = rankNodes(diagram)
const maxRank = Math.max(0, ...ranks.values())
const ranksByIndex = new Map<number, FlowchartNode[]>()
@@ -375,6 +373,23 @@ function layoutRankedNodes(
ranksByIndex.set(normalizedRank, nodes)
}
const spaciousNodeGap = Math.max(minNodeGap, DEFAULT_MIN_BRANCH_LABEL_GAP)
const widestUnlabeledRank = Math.max(
0,
...[...ranksByIndex.values()].map(
(nodes) =>
nodes.reduce((total, node) => total + sizes.get(node.id)!.width, 0) +
Math.max(0, nodes.length - 1) * spaciousNodeGap,
),
)
const rankNodeGap = horizontal
? minNodeGap
: widestPaddedEdgeLabel > 0
? Math.max(spaciousNodeGap, flowchartVerticalBranchLabelGap(widestPaddedEdgeLabel))
: widestUnlabeledRank > DEFAULT_MAX_UNLABELED_RANK_WIDTH
? minNodeGap
: spaciousNodeGap
const rankKeys = [...ranksByIndex.keys()].sort((a, b) => a - b)
const horizontalGaps = horizontal ? horizontalRankGaps(diagram, normalizedRanks, rankKeys, requestedMinRankGap) : []
const verticalGaps = horizontal ? [] : verticalRankGaps(diagram, normalizedRanks, rankKeys, requestedMinRankGap)
+100 -5
View File
@@ -8,6 +8,7 @@ import type {
} from "./types.js"
import { MermaidSyntaxError } from "../diagnostics.js"
import {
decodeMermaidText,
firstMeaningfulMermaidLine,
meaningfulNumberedMermaidLines,
stripMermaidQuotes as stripQuotes,
@@ -28,8 +29,9 @@ const DECISION_NODE_RE = new RegExp(`^(${ID_RE})\\{(.+)\\}$`)
const BOX_NODE_RE = new RegExp(`^(${ID_RE})\\[(.+)\\]$`)
const ID_ONLY_RE = new RegExp(`^${ID_RE}$`)
const EXPLICIT_NODE_SHAPE_RE = new RegExp(`^${ID_RE}(?:\\[|\\(|\\{)`)
const CIRCLE_NODE_RE = new RegExp(`^${ID_RE}\\(\\(.+\\)\\)$`)
const EDGE_OPERATOR_RE =
/(-\.(?!->)(.+?)\.->)|(--|==|-\.)\s+(.+?)\s+(-->|==>|\.->|-\.->)|(-->|==>|-\.->|---|~~~)\s*(?:\|([^|]*)\|\s*)?/g
/(-\.(?!->)(.+?)\.(?:->|-))|(--|==|-\.)\s+(.+?)\s+(-->|==>|\.->|-\.->|\.-)|(<-->|-->|==>|-\.->|---|~~~)\s*(?:\|([^|]*)\|\s*)?/g
function normalizeDirection(value?: string): FlowchartDirection {
const upper = value?.toUpperCase()
@@ -79,6 +81,20 @@ function parseNodeToken(token: string): FlowchartNode {
return { id: trimmed, label: trimmed, shape: "box" }
}
function isSupportedNodeToken(token: string): boolean {
const trimmed = stripNodeToken(token)
if (CIRCLE_NODE_RE.test(trimmed)) return false
return (
ID_ONLY_RE.test(trimmed) ||
DATABASE_NODE_RE.test(trimmed) ||
SUBROUTINE_NODE_RE.test(trimmed) ||
ROUNDED_BRACKET_NODE_RE.test(trimmed) ||
ROUNDED_NODE_RE.test(trimmed) ||
DECISION_NODE_RE.test(trimmed) ||
BOX_NODE_RE.test(trimmed)
)
}
function hasExplicitNodeShape(token: string): boolean {
return EXPLICIT_NODE_SHAPE_RE.test(token.trim())
}
@@ -122,9 +138,11 @@ function createEdge(
label: string,
style: FlowchartEdgeStyle | undefined,
arrowhead: boolean,
sourceArrowhead: boolean,
): FlowchartEdge {
const edge: FlowchartEdge = style ? { from, to, label, style } : { from, to, label }
if (!arrowhead) edge.arrowhead = false
if (sourceArrowhead) edge.sourceArrowhead = true
return edge
}
@@ -134,25 +152,91 @@ interface ParsedEdgeOperator {
label: string
style: FlowchartEdgeStyle | undefined
arrowhead: boolean
sourceArrowhead: boolean
orderOnly: boolean
}
function parseEdgeOperators(line: string): ParsedEdgeOperator[] {
return [...line.matchAll(EDGE_OPERATOR_RE)].map((match) => {
return [...maskNodeLabelOperators(line).matchAll(EDGE_OPERATOR_RE)].map((match) => {
const inlineDashedArrow = match[1]
const startArrow = inlineDashedArrow ?? match[3] ?? match[6]!
const endArrow = inlineDashedArrow ?? match[5] ?? match[6]!
return {
index: match.index,
end: match.index + match[0].length,
label: (match[2] ?? match[4] ?? match[7] ?? "").trim(),
label: decodeMermaidText((match[2] ?? match[4] ?? match[7] ?? "").trim()),
style: edgeStyleFromArrow(startArrow, endArrow),
arrowhead: endArrow !== "---",
arrowhead: endArrow === "~~~" || endArrow.endsWith(">"),
sourceArrowhead: startArrow.startsWith("<"),
orderOnly: endArrow === "~~~",
}
})
}
function maskNodeLabelOperators(line: string): string {
const characters = line.split("")
const stack: string[] = []
let quote: '"' | "'" | undefined
const closes: Record<string, string> = { "[": "]", "(": ")", "{": "}" }
for (let index = 0; index < characters.length; index++) {
const character = characters[index]!
if (quote) {
if (character === quote && characters[index - 1] !== "\\") quote = undefined
else if (/[<>=.-]/.test(character)) characters[index] = " "
continue
}
if (character === '"' || character === "'") {
quote = character
continue
}
if (character in closes) {
stack.push(character)
continue
}
if (stack.length > 0 && character === closes[stack.at(-1)!]) {
stack.pop()
continue
}
if (stack.length > 0 && /[<>=.-]/.test(character)) characters[index] = " "
}
return characters.join("")
}
function hasInternalStatementSeparator(line: string): boolean {
const stack: string[] = []
let quote: '"' | "'" | undefined
let edgeLabel = false
const closes: Record<string, string> = { "[": "]", "(": ")", "{": "}" }
const finalIndex = line.trimEnd().length - 1
for (let index = 0; index < line.length; index++) {
const character = line[index]!
if (quote) {
if (character === quote && line[index - 1] !== "\\") quote = undefined
continue
}
if (character === '"' || character === "'") {
quote = character
continue
}
if (character in closes) {
stack.push(character)
continue
}
if (stack.length > 0 && character === closes[stack.at(-1)!]) {
stack.pop()
continue
}
if (stack.length === 0 && character === "|") {
edgeLabel = !edgeLabel
continue
}
if (character === ";" && index < finalIndex && stack.length === 0 && !edgeLabel) return true
}
return false
}
export function isMermaidFlowchartDiagram(content: string): boolean {
return FLOWCHART_HEADER_RE.test(firstMeaningfulMermaidLine(content) ?? "")
}
@@ -166,6 +250,7 @@ export function parseMermaidFlowchartDiagram(content: string): FlowchartDiagram
for (const source of meaningfulNumberedMermaidLines(content)) {
const line = source.text
if (hasInternalStatementSeparator(line)) throw new MermaidSyntaxError("flowchart", source.lineNumber, line)
const header = line.match(FLOWCHART_HEADER_RE)
if (header) {
direction = normalizeDirection(header[2])
@@ -222,6 +307,15 @@ export function parseMermaidFlowchartDiagram(content: string): FlowchartDiagram
]
if (nodeTokens.every((token) => stripNodeToken(token).length > 0)) {
const unsupportedEndpoint = nodeTokens.find((token, index) => {
const stripped = stripNodeToken(token)
const orderOnlyEndpoint = edgeOperators[index - 1]?.orderOnly || edgeOperators[index]?.orderOnly
return (
!(orderOnlyEndpoint && subgraphs.some((subgraph) => subgraph.id === stripped)) &&
!isSupportedNodeToken(stripped)
)
})
if (unsupportedEndpoint) throw new MermaidSyntaxError("flowchart", source.lineNumber, line)
const chainNodeIds = nodeTokens.map((token, index) => {
const stripped = stripNodeToken(token)
const orderOnlyEndpoint = edgeOperators[index - 1]?.orderOnly || edgeOperators[index]?.orderOnly
@@ -239,6 +333,7 @@ export function parseMermaidFlowchartDiagram(content: string): FlowchartDiagram
operator.label,
operator.style,
operator.arrowhead,
operator.sourceArrowhead,
)
edges.push(operator.orderOnly ? { ...edge, orderOnly: true } : edge)
}
@@ -246,7 +341,7 @@ export function parseMermaidFlowchartDiagram(content: string): FlowchartDiagram
}
}
if (hasExplicitNodeShape(line) || ID_ONLY_RE.test(stripNodeToken(line))) {
if (isSupportedNodeToken(line)) {
const node = ensureNode(nodes, line)
addNodeToSubgraph(currentSubgraph, node.id)
continue
@@ -1,4 +1,6 @@
import { describe, expect, test } from "bun:test"
import { diagramTextWidth } from "../core/text.js"
import { flowchartEdgeLabelLayout } from "./labels.js"
import type { FlowchartDiagram, FlowchartNodeBounds } from "./types.js"
import { routeFlowchartEdges } from "./routing.js"
@@ -21,6 +23,31 @@ function diagram(direction: FlowchartDiagram["direction"], edges: FlowchartDiagr
return { direction, nodes: [], edges, subgraphs: [] }
}
function routeIntersectsBounds(
points: readonly { x: number; y: number }[],
nodeBounds: { left: number; top: number; width: number; height: number },
): boolean {
const right = nodeBounds.left + nodeBounds.width - 1
const bottom = nodeBounds.top + nodeBounds.height - 1
return points.slice(1).some((to, index) => {
const from = points[index]!
if (from.x === to.x) {
return (
from.x >= nodeBounds.left &&
from.x <= right &&
Math.max(from.y, to.y) >= nodeBounds.top &&
Math.min(from.y, to.y) <= bottom
)
}
return (
from.y >= nodeBounds.top &&
from.y <= bottom &&
Math.max(from.x, to.x) >= nodeBounds.left &&
Math.min(from.x, to.x) <= right
)
})
}
describe("flowchart routing", () => {
test("routes a simple horizontal edge from source port to target port", () => {
const edge = { from: "A", to: "B", label: "" }
@@ -269,4 +296,79 @@ describe("flowchart routing", () => {
},
])
})
test("does not route a fallback through its own source node", () => {
const labeled = { from: "A", to: "B", label: "route" }
const crossing = { from: "C", to: "D", label: "" }
const nodeBounds = new Map([
["A", bounds("A", 0, 0)],
["B", bounds("B", 100, 0)],
["C", bounds("C", 48, -12)],
["D", bounds("D", 48, 12)],
])
const routes = routeFlowchartEdges(diagram("LR", [labeled, crossing]), nodeBounds, undefined, new Map())
const route = routes.find((candidate) => candidate.edge === labeled)!
expect(routeIntersectsBounds(route.points, nodeBounds.get("A")!)).toBe(false)
expect(routeIntersectsBounds(route.points, nodeBounds.get("B")!)).toBe(false)
})
test("ignores zero-width blank label interiors as route obstacles", () => {
const blankLabel = { from: "A", to: "B", label: "<br/>" }
const crossing = { from: "C", to: "D", label: "" }
const routes = routeFlowchartEdges(
diagram("TD", [blankLabel, crossing]),
new Map([
["A", bounds("A", 0, 0)],
["B", bounds("B", 0, 100)],
["C", bounds("C", -20, 50)],
["D", bounds("D", 20, 50)],
]),
(edge) => (edge === blankLabel ? "TD" : "LR"),
new Map(),
)
expect(routes.find((route) => route.edge === blankLabel)!.points).toEqual([
{ x: 2, y: 3 },
{ x: 2, y: 99 },
])
})
test("checks earlier labels against finalized later fallback routes", () => {
const edges = [
{ from: "C", to: "B", label: "alpha" },
{ from: "A", to: "F", label: "beta long" },
{ from: "C", to: "D", label: "gamma" },
{ from: "A", to: "B", label: "" },
]
const directions = ["TD", "RL", "LR", "BT"] as const
const routes = routeFlowchartEdges(
diagram("LR", edges),
new Map([
["A", bounds("A", -24, 6)],
["B", bounds("B", 48, 24)],
["C", bounds("C", -24, 24)],
["D", bounds("D", -24, -18)],
["F", bounds("F", -16, -6)],
]),
(edge) => directions[edges.indexOf(edge)]!,
new Map(),
)
const labeled = routes.find((route) => route.edge === edges[0])!
const laterFallback = routes.find((route) => route.edge === edges[3])!
const label = flowchartEdgeLabelLayout(labeled.points, labeled.edge.label, diagramTextWidth)
expect(labeled.points).toEqual([
{ x: -19, y: 25 },
{ x: 47, y: 25 },
])
expect(
routeIntersectsBounds(laterFallback.points, {
left: label.point.x + 1,
top: label.point.y,
width: label.width - 2,
height: label.height,
}),
).toBe(false)
})
})
+234 -37
View File
@@ -15,6 +15,7 @@ import {
pathViaLane,
sideForDirection,
snapCoordinate,
shiftPoint,
withCoordinate,
type DiagramAxis,
type DiagramDirection,
@@ -22,7 +23,7 @@ import {
type DiagramSide,
} from "../core/geometry.js"
import { diagramTextWidth, splitDiagramLines } from "../core/text.js"
import { flowchartEdgeLabelLayout } from "./labels.js"
import { flowchartEdgeLabelLayout, type FlowchartEdgeLabelLayout } from "./labels.js"
import type {
FlowchartDiagram,
FlowchartDirection,
@@ -130,7 +131,9 @@ function horizontalEdgePath(
const travel = horizontalTravel(from, to, direction)
const startSide = sideForDirection(travel)
return orthogonalPath(boundsSidePoint(from, startSide), boundsSidePoint(to, oppositeSide(startSide)))
return orthogonalPath(boundsSidePoint(from, startSide), boundsSidePoint(to, oppositeSide(startSide)), {
preferredAxis: "x",
})
}
function selfEdgePath(bounds: FlowchartNodeBounds): FlowchartPoint[] {
@@ -165,7 +168,7 @@ function labelHeight(edge: FlowchartEdge): number {
function rightRenderExtent(route: FlowchartEdgeRoute): number {
let right = Math.max(...route.points.map((point) => point.x))
if (route.edge.label) {
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, diagramTextWidth)
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, diagramTextWidth, route.labelAxis)
right = Math.max(right, label.point.x + label.width - 1)
}
return right
@@ -179,6 +182,14 @@ function edgePath(
): FlowchartPoint[] {
if (from.id === to.id) return selfEdgePath(from)
if (!isVerticalDirection(direction)) return horizontalEdgePath(from, to, direction)
const overlapsVertically = from.top < to.top + to.height && to.top < from.top + from.height
if (overlapsVertically) {
const travel: HorizontalTravel = centerCoordinate(to, "x") >= centerCoordinate(from, "x") ? "right" : "left"
return orthogonalPath(
boundsSidePoint(from, sideForDirection(travel)),
boundsSidePoint(to, oppositeSide(sideForDirection(travel))),
)
}
return isVerticalBackEdge(from, to, direction)
? verticalBackEdgePath(from, to, leftBoundary)
: verticalForwardEdgePath(from, to)
@@ -211,7 +222,7 @@ function targetFanInLane(
afterFarthestCoordinate(sourcePorts, axis, travel, NODE_CLEARANCE),
travel,
)
return keepBefore(unclamped, targetCoordinate, travel)
return keepBefore(unclamped, advanceCoordinate(targetCoordinate, travel, -1), travel)
}
function portForTravel(bounds: FlowchartNodeBounds, travel: DiagramDirection, role: PortRole): FlowchartPoint {
@@ -468,7 +479,11 @@ function routeParallelEdges(
Math.max(boundsSidePoint(from, "bottom").y, boundsSidePoint(to, "bottom").y) + BUS_CLEARANCE,
Math.max(...previousRoute.points.map((point) => point.y)) + Math.max(2, labelHeight(edge) + 1),
)
const route = { edge, points: parallelEdgePath(from, to, direction, laneCoordinate) }
const route: FlowchartEdgeRoute = {
edge,
points: parallelEdgePath(from, to, direction, laneCoordinate),
labelAxis: isVerticalDirection(direction) ? "y" : "x",
}
routes.push(route)
handled.add(edge)
previousRoute = route
@@ -571,59 +586,238 @@ function routeHorizontalSubgraphEntries(
}
}
function pathIntersectsBounds(points: readonly FlowchartPoint[], bounds: FlowchartNodeBounds): boolean {
function pathIntersectsBounds(
points: readonly FlowchartPoint[],
bounds: { left: number; top: number; width: number; height: number },
allowedContact: "source" | "target" | "both" | undefined = undefined,
): boolean {
const right = bounds.left + bounds.width - 1
const bottom = bounds.top + bounds.height - 1
for (let index = 1; index < points.length; index++) {
const from = points[index - 1]!
const to = points[index]!
if (from.x === to.x) {
if (
from.x >= bounds.left &&
from.x <= right &&
Math.max(from.y, to.y) >= bounds.top &&
Math.min(from.y, to.y) <= bottom
) {
return true
}
if (from.x < bounds.left || from.x > right) continue
const overlapTop = Math.max(Math.min(from.y, to.y), bounds.top)
const overlapBottom = Math.min(Math.max(from.y, to.y), bottom)
if (overlapTop > overlapBottom) continue
const sourceContact =
(allowedContact === "source" || allowedContact === "both") &&
index === 1 &&
overlapTop === overlapBottom &&
from.x === points[0]!.x &&
overlapTop === points[0]!.y
const targetContact =
(allowedContact === "target" || allowedContact === "both") &&
index === points.length - 1 &&
overlapTop === overlapBottom &&
to.x === points.at(-1)!.x &&
overlapTop === points.at(-1)!.y
if (!sourceContact && !targetContact) return true
continue
}
if (
from.y >= bounds.top &&
from.y <= bottom &&
Math.max(from.x, to.x) >= bounds.left &&
Math.min(from.x, to.x) <= right
) {
return true
}
if (from.y < bounds.top || from.y > bottom) continue
const overlapLeft = Math.max(Math.min(from.x, to.x), bounds.left)
const overlapRight = Math.min(Math.max(from.x, to.x), right)
if (overlapLeft > overlapRight) continue
const sourceContact =
(allowedContact === "source" || allowedContact === "both") &&
index === 1 &&
overlapLeft === overlapRight &&
overlapLeft === points[0]!.x &&
from.y === points[0]!.y
const targetContact =
(allowedContact === "target" || allowedContact === "both") &&
index === points.length - 1 &&
overlapLeft === overlapRight &&
overlapLeft === points.at(-1)!.x &&
to.y === points.at(-1)!.y
if (!sourceContact && !targetContact) return true
}
return false
}
function labelIntersectsBounds(label: FlowchartEdgeLabelLayout | undefined, bounds: FlowchartNodeBounds): boolean {
if (!label) return false
return (
label.point.x <= bounds.left + bounds.width - 1 &&
label.point.x + label.width - 1 >= bounds.left &&
label.point.y <= bounds.top + bounds.height - 1 &&
label.point.y + label.height - 1 >= bounds.top
)
}
function labelIntersectsSubgraphFrame(
label: FlowchartEdgeLabelLayout | undefined,
bounds: FlowchartSubgraphBounds,
): boolean {
if (!label) return false
const labelRight = label.point.x + label.width - 1
const labelBottom = label.point.y + label.height - 1
const right = bounds.left + bounds.width - 1
const bottom = bounds.top + bounds.height - 1
return (
(label.point.x <= right &&
labelRight >= bounds.left &&
((label.point.y <= bounds.top && labelBottom >= bounds.top) ||
(label.point.y <= bottom && labelBottom >= bottom))) ||
(label.point.y <= bottom &&
labelBottom >= bounds.top &&
((label.point.x <= bounds.left && labelRight >= bounds.left) || (label.point.x <= right && labelRight >= right)))
)
}
function routeLength(route: FlowchartEdgeRoute): number {
let length = 0
for (let index = 1; index < route.points.length; index++) {
const from = route.points[index - 1]!
const to = route.points[index]!
length += Math.abs(to.x - from.x) + Math.abs(to.y - from.y)
}
return length
}
function labelIntersectsLabels(
label: FlowchartEdgeLabelLayout | undefined,
otherLabels: readonly FlowchartEdgeLabelLayout[],
): boolean {
if (!label) return false
return otherLabels.some((otherLabel) => {
return label.lines.some((line, lineIndex) => {
const textLeft = label.point.x + 1
const textRight = label.point.x + diagramTextWidth(line) - 2
const y = label.point.y + lineIndex
return otherLabel.lines.some((otherLine, otherLineIndex) => {
const otherLeft = otherLabel.point.x
const otherRight = otherLeft + diagramTextWidth(otherLine) - 1
return y === otherLabel.point.y + otherLineIndex && textLeft <= otherRight && textRight >= otherLeft
})
})
})
}
function labelIntersectsLaterRoutePaths(
label: FlowchartEdgeLabelLayout | undefined,
laterRoutes: readonly FlowchartEdgeRoute[],
): boolean {
if (!label) return false
return label.lines.some((line, lineIndex) => {
const width = diagramTextWidth(line) - 2
if (width <= 0) return false
return laterRoutes.some((other) =>
pathIntersectsBounds(other.points, {
left: label.point.x + 1,
top: label.point.y + lineIndex,
width,
height: 1,
}),
)
})
}
function avoidNodeObstacles(
route: FlowchartEdgeRoute,
routes: readonly FlowchartEdgeRoute[],
bounds: Map<string, FlowchartNodeBounds>,
direction: FlowchartDirection,
subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds> | undefined,
routeIndex: number,
): FlowchartEdgeRoute {
const obstacle = [...bounds.values()].some(
(bound) => bound.id !== route.edge.from && bound.id !== route.edge.to && pathIntersectsBounds(route.points, bound),
const allNodeBounds = [...bounds.values()]
const allSubgraphBounds = [...(subgraphBounds?.values() ?? [])]
const laterRoutes = routes.slice(routeIndex + 1)
const laterLabels = laterRoutes.flatMap((laterRoute) =>
laterRoute.edge.label
? [flowchartEdgeLabelLayout(laterRoute.points, laterRoute.edge.label, diagramTextWidth, laterRoute.labelAxis)]
: [],
)
if (!obstacle) return route
const intersectsObstacle = (candidate: FlowchartEdgeRoute): boolean => {
const label = candidate.edge.label
? flowchartEdgeLabelLayout(candidate.points, candidate.edge.label, diagramTextWidth, candidate.labelAxis)
: undefined
return (
allNodeBounds.some((bound) => {
const isSource = bound.id === route.edge.from
const isTarget = bound.id === route.edge.to
const allowedContact = isSource && isTarget ? "both" : isSource ? "source" : isTarget ? "target" : undefined
return pathIntersectsBounds(candidate.points, bound, allowedContact)
}) ||
allNodeBounds.some((bound) => labelIntersectsBounds(label, bound)) ||
allSubgraphBounds.some((bound) => labelIntersectsSubgraphFrame(label, bound)) ||
(subgraphBounds !== undefined &&
(labelIntersectsLabels(label, laterLabels) || labelIntersectsLaterRoutePaths(label, laterRoutes)))
)
}
if (!intersectsObstacle(route)) return route
const from = bounds.get(route.edge.from)
const to = bounds.get(route.edge.to)
if (!from || !to) return route
if (isVerticalDirection(direction)) {
const start = boundsSidePoint(from, "right")
const end = boundsSidePoint(to, "right")
const busX = Math.max(...[...bounds.values()].map((bound) => bound.left + bound.width - 1)) + BUS_CLEARANCE
return { edge: route.edge, points: pathViaLane(start, lane("x", busX), end) }
const routingBounds = [...allNodeBounds, ...allSubgraphBounds]
const rightBusX = Math.max(...routingBounds.map((bound) => bound.left + bound.width - 1)) + BUS_CLEARANCE
const leftBusX = Math.min(...routingBounds.map((bound) => bound.left)) - BUS_CLEARANCE
const topBusY = Math.min(...routingBounds.map((bound) => bound.top)) - BUS_CLEARANCE
const bottomBusY = Math.max(...routingBounds.map((bound) => bound.top + bound.height - 1)) + BUS_CLEARANCE
const start = route.points[0]!
const end = route.points.at(-1)!
const targetSide = sideForOutsidePoint(to, end)
const approach = shiftPoint(
end,
targetSide === "left" ? "left" : targetSide === "right" ? "right" : targetSide === "top" ? "up" : "down",
)
const preservedTargetCandidates: FlowchartEdgeRoute[] = [
{
...route,
labelAxis: route.labelAxis === undefined ? undefined : "y",
points: pathThrough([start, { x: leftBusX, y: start.y }, { x: leftBusX, y: approach.y }, approach, end]),
},
{
...route,
labelAxis: route.labelAxis === undefined ? undefined : "y",
points: pathThrough([start, { x: rightBusX, y: start.y }, { x: rightBusX, y: approach.y }, approach, end]),
},
{
...route,
labelAxis: route.labelAxis === undefined ? undefined : "x",
points: pathThrough([start, { x: start.x, y: topBusY }, { x: approach.x, y: topBusY }, approach, end]),
},
{
...route,
labelAxis: route.labelAxis === undefined ? undefined : "x",
points: pathThrough([start, { x: start.x, y: bottomBusY }, { x: approach.x, y: bottomBusY }, approach, end]),
},
]
const candidates: FlowchartEdgeRoute[] = [
{
...route,
labelAxis: route.labelAxis === undefined ? undefined : "y",
points: pathViaLane(boundsSidePoint(from, "right"), lane("x", rightBusX), boundsSidePoint(to, "right")),
},
{
...route,
labelAxis: route.labelAxis === undefined ? undefined : "y",
points: pathViaLane(boundsSidePoint(from, "left"), lane("x", leftBusX), boundsSidePoint(to, "left")),
},
{
...route,
labelAxis: route.labelAxis === undefined ? undefined : "x",
points: pathViaLane(boundsSidePoint(from, "top"), lane("y", topBusY), boundsSidePoint(to, "top")),
},
{
...route,
labelAxis: route.labelAxis === undefined ? undefined : "x",
points: pathViaLane(boundsSidePoint(from, "bottom"), lane("y", bottomBusY), boundsSidePoint(to, "bottom")),
},
]
const shortestValid = (candidateRoutes: FlowchartEdgeRoute[]): FlowchartEdgeRoute | undefined =>
candidateRoutes
.filter((candidate) => !intersectsObstacle(candidate))
.sort((left, right) => routeLength(left) - routeLength(right))[0]
if (subgraphBounds) {
return shortestValid(preservedTargetCandidates) ?? shortestValid(candidates) ?? route
}
const start = boundsSidePoint(from, "top")
const end = boundsSidePoint(to, "top")
const busY = Math.min(...[...bounds.values()].map((bound) => bound.top)) - BUS_CLEARANCE
return { edge: route.edge, points: pathViaLane(start, lane("y", busY), end) }
return (
candidates.find((candidate) => !intersectsObstacle(candidate)) ?? shortestValid(preservedTargetCandidates) ?? route
)
}
export function routeFlowchartEdges(
@@ -671,7 +865,10 @@ export function routeFlowchartEdges(
if (!from || !to) continue
routes.push({ edge, points: edgePath(from, to, directionForEdge(edge), leftBoundary) })
}
return routes.map((route) => avoidNodeObstacles(route, bounds, directionForEdge(route.edge)))
for (let index = routes.length - 1; index >= 0; index--) {
routes[index] = avoidNodeObstacles(routes[index]!, routes, bounds, subgraphBounds, index)
}
return routes
}
function sideForOutsidePoint(bounds: FlowchartNodeBounds, sourcePoint: FlowchartPoint): DiagramSide {
+3 -1
View File
@@ -1,4 +1,4 @@
import type { DiagramBounds, DiagramDirection, DiagramPoint } from "../core/geometry.js"
import type { DiagramAxis, DiagramBounds, DiagramDirection, DiagramPoint } from "../core/geometry.js"
export type FlowchartDirection = "TB" | "TD" | "BT" | "LR" | "RL"
export type FlowchartNodeShape = "box" | "rounded" | "database" | "decision" | "subroutine"
@@ -16,6 +16,7 @@ export interface FlowchartEdge {
label: string
style?: FlowchartEdgeStyle
arrowhead?: false
sourceArrowhead?: true
orderOnly?: boolean
}
@@ -55,6 +56,7 @@ export type FlowchartPoint = DiagramPoint
export interface FlowchartEdgeRoute {
edge: FlowchartEdge
points: FlowchartPoint[]
labelAxis?: DiagramAxis
}
export type FlowchartEdgeDirection = DiagramDirection
+105 -30
View File
@@ -1,4 +1,5 @@
import { describe, expect, test } from "bun:test"
import { diagramTextWidth } from "../core/text.js"
import { expectDiagram } from "../test/diagram.js"
import { renderSequenceDiagram } from "./diagram.js"
import { drawSequenceDiagramGrid } from "./drawing.js"
@@ -28,6 +29,18 @@ sequenceDiagram
])
})
test("decodes HTML entities in participant, message, and note labels", () => {
const diagram = parseMermaidSequenceDiagram(`sequenceDiagram
participant A as Worker &amp; signer
participant B
A->>B: ack &lt;3s
Note over A,B: result &#8805; 1`)
expect(diagram.participants[0]?.label).toBe("Worker & signer")
expect(diagram.messages[0]?.label).toBe("ack <3s")
expect(diagram.steps.find((step) => step.type === "note")?.note.label).toBe("result ≥ 1")
})
test("renders a terminal sequence diagram", () => {
const output = renderSequenceDiagram(`
sequenceDiagram
@@ -42,11 +55,11 @@ sequenceDiagram
Browser Server
GET /
GET /
401 WWW-Auth
401 WWW-Auth
`)
})
@@ -70,15 +83,15 @@ sequenceDiagram
expectDiagram(output).toEqualDiagram(`
leaf tool LocationMutation FileMutation
resolve(path)
resolve(path)
Plan(target, authority anchor)
Plan(target, authority anchor)
commit(plan)
commit(plan)
revalidate(plan)
revalidate(plan)
same target or reject
same target or reject
`)
})
@@ -109,7 +122,7 @@ sequenceDiagram
const lines = output.split("\n")
expect(lines.findIndex((line) => line.includes("deliberately"))).toBeLessThan(
lines.findIndex((line) => line.includes("")),
lines.findIndex((line) => line.includes("")),
)
})
@@ -245,18 +258,29 @@ sequenceDiagram
])
})
test("parses activation syntax without rendering activation bars", () => {
test("renders activation syntax as visible intervals", () => {
const output = renderSequenceDiagram(`
sequenceDiagram
Browser->>+Server: request
Server-->>-Browser: response
`)
expect(output).not.toContain("┃")
expect(output).toContain("┃")
expect(output).toContain("request")
expect(output).toContain("response")
})
test("renders br-delimited participant aliases on separate lines", () => {
const output = renderSequenceDiagram(`sequenceDiagram
participant A as First line<br/>Second line
participant B as Normal
A->>B: hello`)
expect(output).not.toContain("<br")
expect(output).toContain("│ First line │")
expect(output).toContain("│ Second line │")
})
test("parses Mermaid arrow head variants", () => {
const diagram = parseMermaidSequenceDiagram(`
sequenceDiagram
@@ -294,22 +318,22 @@ sequenceDiagram
A B
open solid
open solid
>
open dashed
open dashed
<
failed solid
failed solid
failed dashed
failed dashed
async solid
async solid
)
async dashed
async dashed
(
"
`)
@@ -533,7 +557,7 @@ sequenceDiagram
const fragmentMessageRow = fragment.split("\n").find((line) => line.includes("this non adjacent message"))!
expect(groupMessageRow.trimEnd().endsWith("│")).toBe(true)
expect(fragmentMessageRow).toContain("this non adjacent message is deliberately much wider than the frame")
expect(fragmentMessageRow.match(/│/g)?.length).toBe(3)
expect(fragmentMessageRow.match(/│/g)?.length).toBe(2)
})
test("keeps long notes inside groups and nested fragment frames intact", () => {
@@ -581,6 +605,42 @@ sequenceDiagram
expect(externalHeaderLeft).toBeGreaterThan(groupBorderRight)
})
test("keeps adjacent wide participant group frames separate", () => {
const output = renderSequenceDiagram(
`sequenceDiagram
box First very wide group heading
participant A
end
box Second very wide group heading
participant B
end
A->>B: hi`,
{ compact: true },
)
const topRow = output.split("\n")[0]!
expect(topRow).toContain("First very wide group heading")
expect(topRow).toContain("Second very wide group heading")
expect(topRow.indexOf("╮")).toBeLessThan(topRow.lastIndexOf("╭"))
})
test("renders many adjacent wide participant groups without excessive canvas growth", () => {
const groupCount = 16
const output = renderSequenceDiagram(
`sequenceDiagram
${Array.from(
{ length: groupCount },
(_, index) => ` box Group ${index} has a deliberately wide heading
participant P${index}
end`,
).join("\n")}
P0->>P15: hi`,
{ compact: true },
)
expect(Math.max(...output.split("\n").map(diagramTextWidth))).toBeLessThan(groupCount * 60)
})
test("renders full-height participant group boxes", () => {
const output = renderSequenceDiagram(`
sequenceDiagram
@@ -600,11 +660,11 @@ sequenceDiagram
Browser API Cache DB
GET /users/42
GET /users/42
get user:42
get user:42
"
`)
@@ -619,12 +679,25 @@ sequenceDiagram
end
Browser->>API: GET /users/42
`)
const arrowLine = output.split("\n").find((line) => line.includes(""))!
const arrowLine = output.split("\n").find((line) => line.includes(""))!
expect(arrowLine).toContain("───────────────")
expect(arrowLine).toContain("───────────────")
expect(arrowLine).not.toContain("┼")
})
test("keeps filled arrowheads to one terminal column", () => {
const output = renderSequenceDiagram(`sequenceDiagram
box Backend
participant A
participant B
A->>B: request
end`)
const lines = output.split("\n")
const frameWidth = diagramTextWidth(lines.at(-1)!)
expect(Math.max(...lines.map(diagramTextWidth))).toBe(frameWidth)
})
test("renders self messages as loopback arrows", () => {
const output = renderSequenceDiagram(`
sequenceDiagram
@@ -639,12 +712,12 @@ sequenceDiagram
Check Permissions
"
`)
})
test("places two spacer rows above note badges and one below", () => {
test("frames notes in their reserved rows", () => {
const output = renderSequenceDiagram(`
sequenceDiagram
Browser->>Server: one
@@ -656,9 +729,11 @@ sequenceDiagram
const nextMessageRow = lines.findIndex((line) => line.includes("two"))
expect(noteRow).toBeGreaterThan(0)
expect(lines[noteRow - 1]?.trim()).toBe("│ │")
expect(lines[noteRow - 2]?.trim()).toBe("│ │")
expect(lines[noteRow + 1]?.trim()).toBe("│ │")
expect(lines[noteRow - 1]).toContain("")
expect(lines[noteRow - 1]).toContain("")
expect(lines[noteRow]).toContain("│ phase │")
expect(lines[noteRow + 1]).toContain("╰")
expect(lines[noteRow + 1]).toContain("╯")
expect(nextMessageRow).toBe(noteRow + 2)
})
+52 -9
View File
@@ -1,5 +1,6 @@
import { BorderChars, type BorderStyle } from "@opentui/core"
import { DiagramCanvas } from "../core/canvas.js"
import { diagramTextWidth } from "../core/text.js"
import { DEFAULT_FRAGMENT_BORDER_STYLE } from "./options.js"
import {
createSequencePlacementPlan,
@@ -19,6 +20,10 @@ import type {
const SEQUENCE_BORDER = BorderChars.rounded
function centeredStart(center: number, text: string): number {
return center - Math.floor(diagramTextWidth(text) / 2)
}
function arrowHeadChar(head: SequenceArrowHead | undefined, direction: 1 | -1): string {
switch (head) {
case "open":
@@ -28,7 +33,7 @@ function arrowHeadChar(head: SequenceArrowHead | undefined, direction: 1 | -1):
case "async":
return direction === 1 ? ")" : "("
default:
return direction === 1 ? "" : ""
return direction === 1 ? "" : ""
}
}
@@ -185,6 +190,32 @@ function renderSelfMessage(
setCell(grid, rightX, bottomRow, SEQUENCE_BORDER.bottomRight, style)
}
function renderNote(grid: SequenceGrid, placement: Extract<SequenceStepPlacement, { type: "note" }>): void {
const width = Math.max(...placement.textLines.map(diagramTextWidth))
const left = placement.textX
const right = left + width - 1
const top = placement.textY - 1
const bottom = placement.textY + placement.textLines.length
for (let x = left + 1; x < right; x++) {
setCell(grid, x, top, SEQUENCE_BORDER.horizontal, "note")
setCell(grid, x, bottom, SEQUENCE_BORDER.horizontal, "note")
}
for (let y = top + 1; y < bottom; y++) {
setCell(grid, left, y, SEQUENCE_BORDER.vertical, "note")
setCell(grid, right, y, SEQUENCE_BORDER.vertical, "note")
}
setCell(grid, left, top, SEQUENCE_BORDER.topLeft, "note")
setCell(grid, right, top, SEQUENCE_BORDER.topRight, "note")
setCell(grid, left, bottom, SEQUENCE_BORDER.bottomLeft, "note")
setCell(grid, right, bottom, SEQUENCE_BORDER.bottomRight, "note")
placement.textLines.forEach((line, index) => setText(grid, left, placement.textY + index, line, "noteBadge"))
for (let y = placement.textY; y < bottom; y++) {
setCell(grid, left, y, SEQUENCE_BORDER.vertical, "note")
setCell(grid, right, y, SEQUENCE_BORDER.vertical, "note")
}
}
export function drawSequenceDiagramGrid(
diagram: SequenceDiagram,
options: SequenceDiagramRenderOptions = {},
@@ -197,11 +228,13 @@ export function drawSequenceDiagramGrid(
if (plan.groups.length > 0) renderParticipantGroups(grid, plan.groups, plan.height - 1)
for (const placement of plan.participants) {
const { participant, centerX: center, headerLeftX, headerRightX, labelX } = placement
const { centerX: center, headerLeftX, headerRightX, labelLines } = placement
const { participantHeaderTopY, participantHeaderY, participantRuleY, lifelineStartY, lifelineEndY } = plan.rows
if (options.compact) {
setText(grid, labelX, participantHeaderY, participant.label, "participant")
labelLines.forEach((line, index) =>
setText(grid, centeredStart(center, line), participantHeaderY + index, line, "participant"),
)
} else {
for (let x = headerLeftX; x <= headerRightX; x++) {
setCell(grid, x, participantHeaderTopY, SEQUENCE_BORDER.horizontal, "participant")
@@ -210,11 +243,15 @@ export function drawSequenceDiagramGrid(
setCell(grid, headerLeftX, participantHeaderTopY, SEQUENCE_BORDER.topLeft, "participant")
setCell(grid, headerRightX, participantHeaderTopY, SEQUENCE_BORDER.topRight, "participant")
setCell(grid, headerLeftX, participantHeaderY, SEQUENCE_BORDER.vertical, "participant")
setCell(grid, headerRightX, participantHeaderY, SEQUENCE_BORDER.vertical, "participant")
for (let y = participantHeaderY; y < participantRuleY; y++) {
setCell(grid, headerLeftX, y, SEQUENCE_BORDER.vertical, "participant")
setCell(grid, headerRightX, y, SEQUENCE_BORDER.vertical, "participant")
}
setCell(grid, headerLeftX, participantRuleY, SEQUENCE_BORDER.bottomLeft, "participant")
setCell(grid, headerRightX, participantRuleY, SEQUENCE_BORDER.bottomRight, "participant")
setText(grid, labelX, participantHeaderY, participant.label, "participant")
labelLines.forEach((line, index) =>
setText(grid, centeredStart(center, line), participantHeaderY + index, line, "participant"),
)
setCell(grid, center, participantRuleY, SEQUENCE_BORDER.topT, "participant")
}
@@ -227,9 +264,7 @@ export function drawSequenceDiagramGrid(
for (const placement of plan.steps) {
if (placement.type === "note") {
for (let lineIndex = 0; lineIndex < placement.textLines.length; lineIndex++) {
setText(grid, placement.textX, placement.textY + lineIndex, placement.textLines[lineIndex]!, "noteBadge")
}
renderNote(grid, placement)
continue
}
@@ -270,5 +305,13 @@ export function drawSequenceDiagramGrid(
if (placement.inlineLabel) setText(grid, placement.labelX, placement.labelY, placement.inlineLabel, messageStyle)
}
for (const activation of plan.activations) {
for (let y = activation.startY; y <= activation.endY; y++) {
if (grid.getCell(activation.centerX, y)?.char === SEQUENCE_BORDER.vertical) {
setCell(grid, activation.centerX, y, "┃", "lifeline")
}
}
}
return grid
}
+4
View File
@@ -22,6 +22,7 @@ const ALT_RE = /^alt\s+(.+)$/i
const ELSE_RE = /^else(?:\s+(.+))?$/i
const LOOP_RE = /^loop\s+(.+)$/i
const AUTONUMBER_RE = /^autonumber(?:\s+(\d+)(?:\s+(\d+))?)?$/i
const UNSUPPORTED_BIDIRECTIONAL_MESSAGE_RE = /<<-{1,2}>>/
const CSS_COLOR_NAMES = new Set([
"black",
"white",
@@ -132,6 +133,9 @@ export function parseMermaidSequenceDiagram(content: string): SequenceDiagram {
for (const source of meaningfulNumberedMermaidLines(content)) {
const line = source.text
if (line.toLowerCase() === "sequencediagram") continue
if (UNSUPPORTED_BIDIRECTIONAL_MESSAGE_RE.test(line)) {
throw new MermaidSyntaxError("sequence", source.lineNumber, line)
}
const autonumberMatch = line.match(AUTONUMBER_RE)
if (autonumberMatch) {
@@ -90,6 +90,25 @@ describe("createSequencePlacementPlan", () => {
expect(external.headerLeftX).toBeGreaterThan(group.rightX)
})
test("keeps many adjacent wide groups at a linear width", () => {
const groupCount = 16
const source = `sequenceDiagram
${Array.from(
{ length: groupCount },
(_, index) => ` box Group ${index} has a deliberately wide heading
participant P${index}
end`,
).join("\n")}
P0->>P15: hi`
const plan = createSequencePlacementPlan(parseMermaidSequenceDiagram(source), { compact: true })
expect(plan.groups).toHaveLength(groupCount)
for (let index = 1; index < plan.groups.length; index++) {
expect(plan.groups[index]!.leftX).toBeGreaterThan(plan.groups[index - 1]!.rightX)
}
expect(plan.width).toBeLessThan(groupCount * 60)
})
test("expands group and fragment frames around contained long content", () => {
const groupPlan = createSequencePlacementPlan(
parseMermaidSequenceDiagram(`sequenceDiagram
@@ -169,4 +188,34 @@ describe("createSequencePlacementPlan", () => {
expect(starts[0]!.bounds.rightX).toBeGreaterThan(starts[1]!.bounds.rightX)
})
test("aligns explicit and shorthand activation intervals to message events", () => {
const shorthand = createSequencePlacementPlan(
parseMermaidSequenceDiagram(`sequenceDiagram
A->>+B: request
B-->>-A: response`),
)
const explicit = createSequencePlacementPlan(
parseMermaidSequenceDiagram(`sequenceDiagram
A->>B: request
activate B
B-->>A: response
deactivate B`),
)
expect(explicit.activations).toEqual(shorthand.activations)
})
test("centers message label blocks over their arrow span", () => {
const plan = createSequencePlacementPlan(
parseMermaidSequenceDiagram(`sequenceDiagram
participant A
participant B
A->>B: short<br/>a much longer line`),
)
const message = plan.steps.find((step) => step.type === "message")!
const labelWidth = Math.max(...message.labelLines.map(diagramTextWidth))
expect(message.labelX * 2 + labelWidth).toBe(message.leftX + message.rightX)
})
})
+92 -37
View File
@@ -11,7 +11,7 @@ import type {
SequenceStep,
} from "./types.js"
const NOTE_HORIZONTAL_PADDING = 1
const NOTE_HORIZONTAL_PADDING = 2
const GROUP_HORIZONTAL_PADDING = 2
const FRAGMENT_HORIZONTAL_OVERHANG = 3
@@ -25,7 +25,7 @@ export interface SequenceParticipantPlacement {
centerX: number
headerLeftX: number
headerRightX: number
labelX: number
labelLines: string[]
}
export interface SequenceGroupPlacement {
@@ -41,6 +41,14 @@ export interface SequenceWallPlacement {
endY: number
}
export interface SequenceActivationPlacement {
participant: string
centerX: number
startY: number
endY: number
depth: number
}
export type SequenceStepPlacement =
| { type: "note"; note: SequenceNote; textLines: string[]; textX: number; textY: number }
| {
@@ -88,6 +96,7 @@ export interface SequencePlacementPlan {
}
participants: SequenceParticipantPlacement[]
groups: SequenceGroupPlacement[]
activations: SequenceActivationPlacement[]
steps: SequenceStepPlacement[]
}
@@ -132,7 +141,8 @@ function messageLabelText(message: SequenceMessage): string {
}
function participantHeaderWidth(label: string, compact: boolean): number {
return compact ? visualLength(label) : Math.max(5, visualLength(label) + 4)
const width = labelLinesWidth(mermaidLabelLines(label))
return compact ? width : Math.max(5, width + 4)
}
function fragmentLabelText(fragment: SequenceFragment): string {
@@ -236,7 +246,9 @@ function getStepContentBounds(
if (fromIndex === toIndex) return { leftX: fromX, rightX: fromX + selfMessageLoopWidth(step.message) }
const leftX = Math.min(fromX, toX)
const rightX = Math.max(fromX, toX)
return { leftX, rightX: Math.max(rightX, leftX + 2 + messageWidth(step.message) - 1) }
const labelWidth = messageWidth(step.message)
const labelLeftX = Math.floor((leftX + rightX - labelWidth) / 2)
return { leftX: Math.min(leftX, labelLeftX), rightX: Math.max(rightX, labelLeftX + labelWidth - 1) }
}
if (step.type !== "note") return undefined
const indexes = getParticipantIndexes(participantIndexes, step.note.over)
@@ -387,7 +399,9 @@ function resolveParticipantCenters(
if (fromIndex === toIndex && fromIndex >= 0 && fromIndex < diagram.participants.length - 1) {
gaps[fromIndex] = Math.max(
gaps[fromIndex]!,
selfMessageLoopWidth(message) + Math.ceil(visualLength(diagram.participants[fromIndex + 1]!.label) / 2) + 2,
selfMessageLoopWidth(message) +
Math.ceil(labelLinesWidth(mermaidLabelLines(diagram.participants[fromIndex + 1]!.label)) / 2) +
2,
)
continue
}
@@ -423,37 +437,31 @@ function separateExpandedGroupsFromExternalParticipants(
compact: boolean,
): number[] {
const adjusted = [...centers]
for (let pass = 0; pass < Math.max(1, ranges.length * 2); pass++) {
let changed = false
for (let boundary = 0; boundary < adjusted.length - 1; boundary++) {
const groups = resolveGroupBounds(diagram, adjusted, participantIndexes, ranges, compact)
const leftWidth = participantHeaderWidth(diagram.participants[boundary]!.label, compact)
const rightWidth = participantHeaderWidth(diagram.participants[boundary + 1]!.label, compact)
let leftRight = adjusted[boundary]! - Math.floor(leftWidth / 2) + leftWidth - 1
let rightLeft = adjusted[boundary + 1]! - Math.floor(rightWidth / 2)
let bordersGroup = false
for (const [index, range] of ranges.entries()) {
const group = groups[index]!
if (range.startIndex > 0) {
const previousIndex = range.startIndex - 1
const previousWidth = participantHeaderWidth(diagram.participants[previousIndex]!.label, compact)
const previousRight = adjusted[previousIndex]! - Math.floor(previousWidth / 2) + previousWidth - 1
const shift = previousRight + GROUP_HORIZONTAL_PADDING + 1 - group.leftX
if (shift > 0) {
for (let participantIndex = range.startIndex; participantIndex < adjusted.length; participantIndex++) {
adjusted[participantIndex]! += shift
}
changed = true
}
if (range.endIndex === boundary) {
leftRight = Math.max(leftRight, groups[index]!.rightX)
bordersGroup = true
}
if (range.endIndex < diagram.participants.length - 1) {
const nextIndex = range.endIndex + 1
const nextWidth = participantHeaderWidth(diagram.participants[nextIndex]!.label, compact)
const nextLeft = adjusted[nextIndex]! - Math.floor(nextWidth / 2)
const shift = group.rightX + GROUP_HORIZONTAL_PADDING + 1 - nextLeft
if (shift > 0) {
for (let participantIndex = nextIndex; participantIndex < adjusted.length; participantIndex++) {
adjusted[participantIndex]! += shift
}
changed = true
}
if (range.startIndex === boundary + 1) {
rightLeft = Math.min(rightLeft, groups[index]!.leftX)
bordersGroup = true
}
}
if (!changed) return adjusted
if (!bordersGroup) continue
const shift = leftRight + GROUP_HORIZONTAL_PADDING + 1 - rightLeft
if (shift <= 0) continue
for (let participantIndex = boundary + 1; participantIndex < adjusted.length; participantIndex++) {
adjusted[participantIndex]! += shift
}
}
return adjusted
}
@@ -475,6 +483,7 @@ export function createSequencePlacementPlan(
},
participants: [],
groups: [],
activations: [],
steps: [],
}
}
@@ -511,9 +520,13 @@ export function createSequencePlacementPlan(
fragments = fragmentBounds()
}
const hasGroups = groups.length > 0
const participantLabelHeight = Math.max(
1,
...diagram.participants.map((participant) => mermaidLabelLines(participant.label).length),
)
const participantHeaderTopY = hasGroups ? 1 : 0
const participantHeaderY = participantHeaderTopY + (compact ? 0 : 1)
const participantRuleY = participantHeaderTopY + (compact ? 0 : 2)
const participantRuleY = participantHeaderTopY + (compact ? participantLabelHeight - 1 : participantLabelHeight + 1)
const lifelineStartY = participantRuleY + 1
const stepStartY = lifelineStartY + 1
const width = Math.max(contentBounds.rightX + 1, ...groups.map((group) => group.rightX + 1), fragments.rightX + 1)
@@ -525,19 +538,46 @@ export function createSequencePlacementPlan(
const centerX = centers[index]!
const width = participantHeaderWidth(participant.label, compact)
const headerLeftX = centerX - Math.floor(width / 2)
const labelLines = mermaidLabelLines(participant.label)
return {
participant,
centerX,
headerLeftX,
headerRightX: headerLeftX + width - 1,
labelX: centeredStart(centerX, participant.label),
labelLines,
}
})
const steps: SequenceStepPlacement[] = []
const activations: SequenceActivationPlacement[] = []
const activeByParticipant = new Map<string, Array<{ startY: number; depth: number }>>()
const lastEventYByParticipant = new Map<string, number>()
const openActivation = (participant: string, y: number): void => {
const active = activeByParticipant.get(participant) ?? []
active.push({ startY: y, depth: active.length })
activeByParticipant.set(participant, active)
}
const closeActivation = (participant: string, y: number): void => {
const active = activeByParticipant.get(participant)
const opened = active?.pop()
const participantIndex = indexes.get(participant)
if (!opened || participantIndex === undefined) return
activations.push({
participant,
centerX: centers[participantIndex]!,
startY: opened.startY,
endY: y,
depth: opened.depth,
})
}
let stepY = stepStartY
const activeFrames: ActiveFragmentFrame[] = []
for (const [stepIndex, step] of diagram.steps.entries()) {
if (step.type === "activation") continue
if (step.type === "activation") {
const eventY = Math.min(lastEventYByParticipant.get(step.activation.participant) ?? stepY, lifelineEndY)
if (step.activation.active) openActivation(step.activation.participant, eventY)
else closeActivation(step.activation.participant, eventY)
continue
}
const stepHeight = getStepHeight(step, centers, indexes, compact)
if (step.type === "note") {
const noteIndexes = getParticipantIndexes(indexes, step.note.over)
@@ -588,6 +628,7 @@ export function createSequencePlacementPlan(
const labelLines = messageLabelLines(messageLabelText(step.message))
if (fromIndex === toIndex) {
const centerX = centers[fromIndex]!
const bottomY = stepY + labelLines.length + 1
steps.push({
type: "selfMessage",
message: step.message,
@@ -595,8 +636,11 @@ export function createSequencePlacementPlan(
centerX,
rightX: centerX + selfMessageLoopWidthForLines(labelLines),
topY: stepY,
bottomY: stepY + labelLines.length + 1,
bottomY,
})
if (step.message.activate) openActivation(step.message.activate, bottomY)
if (step.message.deactivate) closeActivation(step.message.deactivate, bottomY)
lastEventYByParticipant.set(step.message.from, bottomY)
} else {
const fromX = centers[fromIndex]!
const toX = centers[toIndex]!
@@ -604,13 +648,16 @@ export function createSequencePlacementPlan(
const leftX = Math.min(fromX, toX)
const rightX = Math.max(fromX, toX)
const inlineLabel = inlineMessageLabel(step.message, labelLines, fromX, toX, compact)
const arrowY = inlineLabel ? stepY : stepY + labelLines.length
const renderedLabelWidth = inlineLabel ? visualLength(inlineLabel) : labelLinesWidth(labelLines)
const labelX = Math.floor((leftX + rightX - renderedLabelWidth) / 2)
steps.push({
type: "message",
message: step.message,
labelLines,
labelX: leftX + 2,
labelX,
labelY: stepY,
arrowY: inlineLabel ? stepY : stepY + labelLines.length,
arrowY,
fromX,
toX,
leftX,
@@ -619,15 +666,23 @@ export function createSequencePlacementPlan(
headX: arrowHeadX(toX, direction, step.message.head),
inlineLabel,
})
if (step.message.activate) openActivation(step.message.activate, arrowY)
if (step.message.deactivate) closeActivation(step.message.deactivate, arrowY)
lastEventYByParticipant.set(step.message.from, arrowY)
lastEventYByParticipant.set(step.message.to, arrowY)
}
stepY += stepHeight
}
for (const [participant, active] of activeByParticipant) {
while (active.length > 0) closeActivation(participant, lifelineEndY)
}
return {
width,
height,
rows: { participantHeaderTopY, participantHeaderY, participantRuleY, lifelineStartY, lifelineEndY },
participants,
groups,
activations,
steps,
}
}
+194 -8
View File
@@ -47,6 +47,17 @@ stateDiagram-v2
})
})
test("decodes HTML entities in state, transition, and note labels", () => {
const diagram = parseMermaidStateDiagram(`stateDiagram-v2
state "Ready &amp; waiting" as Ready
Ready --> Done: elapsed &lt;3s
note right of Done: result &#x2265; 1`)
expect(diagram.states.find((state) => state.id === "Ready")?.label).toBe("Ready & waiting")
expect(diagram.transitions[0]?.label).toBe("elapsed <3s")
expect(diagram.notes[0]?.lines).toEqual(["result ≥ 1"])
})
test("parses choice pseudo-states", () => {
const diagram = parseMermaidStateDiagram(`
stateDiagram-v2
@@ -55,7 +66,7 @@ stateDiagram-v2
Decision --> Accepted: yes
`)
expect(diagram.states).toContainEqual({ id: "Decision", label: "", kind: "choice" })
expect(diagram.states).toContainEqual({ id: "Decision", label: "", kind: "choice" })
})
test("parses composite states and notes", () => {
@@ -188,7 +199,7 @@ stateDiagram-v2
Running
💥 sandbox dies BEFORE hook fires
(crash, our bug, race)
Dormant Lost
@@ -384,7 +395,7 @@ stateDiagram-v2
expect(output).toMatchInlineSnapshot(`
" submit ok
Editing Saved
Editing Saved
type fail
@@ -411,7 +422,7 @@ stateDiagram-v2
Decision --> Done
Done --> [*]`)
expect(output).toContain("Upper ├─────────────┬────────────▶│ Done")
expect(output).toContain("Upper ├────────────▶◆────────────▶│ Done")
})
test("renders self transitions as loops in vertical diagrams", () => {
@@ -444,6 +455,65 @@ stateDiagram-v2
expect(vertical).toContain("second")
})
test("separates labels on four parallel vertical transitions", () => {
const output = renderStateDiagram(`stateDiagram-v2
direction TB
A --> B: one
A --> B: two
A --> B: three
A --> B: four`)
expect(output).not.toContain("twothree")
for (const label of ["one", "two", "three", "four"]) {
expect(output.match(new RegExp(label, "g"))).toHaveLength(1)
}
})
test("keeps explicit choices visible in choice-only cycles", () => {
const output = renderStateDiagram(`stateDiagram-v2
direction TB
state One <<choice>>
state Two <<choice>>
state Three <<choice>>
One --> Two: clockwise
Two --> Three: clockwise
Three --> One: clockwise`)
expect(output.match(/◆/g)).toHaveLength(3)
})
test("routes dense horizontal transitions around unrelated states", () => {
const output = renderStateDiagram(`stateDiagram-v2
direction LR
A --> B: ab
A --> C: ac
A --> D: ad
B --> A: ba
B --> C: bc
B --> D: bd
C --> A: ca
C --> B: cb
C --> D: cd
D --> A: da
D --> B: db
D --> C: dc`)
for (const state of ["A", "B", "C", "D"]) expect(output.match(new RegExp(state, "g"))).toHaveLength(1)
})
test("routes parallel transitions around vertically offset states", () => {
const output = renderStateDiagram(`stateDiagram-v2
A --> B: first<br/>line two
A --> B: second<br/>another line
B --> A: return<br/>with details`)
expect(output).toContain(" A ")
expect(output).toContain("│ B │")
expect(output).toContain("first")
expect(output).toContain("second")
expect(output).toContain("return")
})
test("keeps independent overlapping feedback labels and paths distinct", () => {
const content = (direction: "LR" | "RL") => `stateDiagram-v2
direction ${direction}
@@ -561,15 +631,46 @@ stateDiagram-v2
})
expect(output).toMatchInlineSnapshot(`
" Authenticated
login open save
Idle Editing
save
login open logout
Idle Editing
"
`)
})
test("keeps nested composite entry and exit routes within the outer frame height", () => {
const output = renderStateDiagram(`stateDiagram-v2
state Session {
[*] --> Open
state Open {
[*] --> Clean
Clean --> Dirty: edit
Dirty --> Clean: save
}
note right of Open: document lifecycle
Open --> [*]: close
}
[*] --> Session
Session --> [*]`)
const lines = output.split("\n")
const outerFrameTop = lines.find((line) => line.includes("Session"))!
const frameLeft = outerFrameTop.indexOf("╭")
const frameRight = outerFrameTop.lastIndexOf("╮")
const outerFrameBottom = lines.findIndex((line) => line[frameLeft] === "╰" && line[frameRight] === "╯")
const startColumn = lines.find((line) => line.includes("●"))!.indexOf("●")
const endColumn = lines.find((line) => line.includes("◎"))!.indexOf("◎")
expect(outerFrameBottom).toBeGreaterThan(0)
expect(startColumn).toBeLessThan(frameLeft)
expect(endColumn).toBeGreaterThan(frameRight)
expect(lines.slice(outerFrameBottom + 1).every((line) => line.trim() === "")).toBe(true)
expect(output).toContain("Open")
expect(output).toContain("document lifecycle")
expect(output).toContain("close")
})
test("renders notes attached to states", () => {
const output = renderStateDiagram(`
stateDiagram-v2
@@ -600,6 +701,91 @@ stateDiagram-v2
state Decision <<choice>>
Decision --> [*]`)
expect(output).toContain("╰─────────────┬\n")
expect(output).toContain("╰─────────────")
expect(output).toContain("◆────────────▶◎")
})
test("keeps vertical branch labels from overwriting state labels", () => {
const output = renderStateDiagram(`stateDiagram-v2
direction TB
state "Branch root" as Root
state "Upper branch" as Upper
state "Lower branch" as Lower
state "Merged branch" as Merge
Root --> Upper: branch-up
Root --> Lower: branch-down
Upper --> Merge: merge-up
Lower --> Merge: merge-down
Merge --> Root: branch-feedback`)
for (const text of [
"Branch root",
"Upper branch",
"Lower branch",
"Merged branch",
"branch-up",
"branch-down",
"merge-up",
"merge-down",
"branch-feedback",
]) {
expect(output).toContain(text)
}
})
test("keeps lifecycle states intact around branches and feedback", () => {
const output = renderStateDiagram(`stateDiagram-v2
[*] --> Idle
Idle --> MailboxPending: enqueue + setAlarm
MailboxPending --> PromptSubmitted: drain mailbox
PromptSubmitted --> Polling: prompt admitted
Polling --> Polling: execution still active
Polling --> Completed: terminal log event
Polling --> Polling: retry after transient failure
Completed --> Idle: final Slack projection
Idle --> Expired: 30 days inactive
Expired --> [*]: delete SQLite state`)
for (const state of ["Idle", "MailboxPending", "PromptSubmitted", "Polling", "Completed", "Expired"]) {
expect(output.match(new RegExp(state, "g"))).toHaveLength(1)
}
})
test("keeps composite titles intact under reciprocal composite routes", () => {
const source = `stateDiagram-v2
direction LR
state FirstGroup {
[*] --> FirstInner
FirstInner --> [*]: first-out
}
state SecondGroup {
[*] --> SecondInner
SecondInner --> [*]: second-out
}
FirstGroup --> SecondGroup: group-next
SecondGroup --> FirstGroup: group-back`
for (const direction of ["LR", "TB"] as const) {
const lines = renderStateDiagram(source, { direction }).split("\n")
for (const title of ["FirstGroup", "SecondGroup"]) {
const top = lines.findIndex((line) => line.includes(title))
const left = lines[top]!.lastIndexOf("╭", lines[top]!.indexOf(title))
const right = lines[top]!.indexOf("╮", left)
const bottom = lines.findIndex((line, index) => index > top && line[left] === "╰" && line[right] === "╯")
expect(top).toBeGreaterThanOrEqual(0)
expect(left).toBeGreaterThanOrEqual(0)
expect(right).toBeGreaterThan(left)
expect(bottom).toBeGreaterThan(top)
expect(
lines.slice(top + 1, bottom).every((line) => "│├┤┼".includes(line[left]!) && "│├┤┼".includes(line[right]!)),
).toBe(true)
expect(
lines[bottom]!.slice(left + 1, right)
.split("")
.every((char) => "─┬┴┼".includes(char)),
).toBe(true)
}
}
})
})
+5 -2
View File
@@ -49,7 +49,9 @@ function translateTransitionPlans(
function makeGrid(width: number, height: number): StateGrid {
return new DiagramCanvas(width, height, {
mergeCell: (existing, incoming): StateCell => {
const shouldMerge = existing.style === "transition" && incoming.style === "transition"
const existingIsTransition = existing.style === "transition" || existing.style?.startsWith("stateDepartureRamp")
const incomingIsTransition = incoming.style === "transition" || incoming.style?.startsWith("stateDepartureRamp")
const shouldMerge = incomingIsTransition && (existingIsTransition || existing.style === "composite")
return {
...incoming,
char: shouldMerge
@@ -198,7 +200,8 @@ function drawTransitionJunctionPlans(
): void {
for (const plan of createStateTransitionJunctionPlans(diagram, bounds, renderPlans)) {
const style = plan.kind === "choice" ? "choice" : "transition"
setCell(grid, plan.bounds.left, plan.bounds.top, diagramLineGlyph(plan.connections, "rounded"), style)
const char = plan.kind === "choice" ? "◆" : diagramLineGlyph(plan.connections, "rounded")
setCell(grid, plan.bounds.left, plan.bounds.top, char, style)
}
}
+39 -21
View File
@@ -40,14 +40,6 @@ export interface StateDiagramLayoutOptions {
minStateGap: number
}
function visualLength(value: string): number {
return diagramTextWidth(value)
}
function splitStateDiagramLines(value: string): string[] {
return splitDiagramLines(value)
}
function computeRanks(diagram: StateDiagram): Map<string, number> {
const ranks = new Map<string, number>()
const outgoing = new Map<string, string[]>()
@@ -88,8 +80,11 @@ function outgoingTransitions(diagram: StateDiagram): Map<string, StateDiagramTra
return outgoing
}
function reaches(diagram: StateDiagram, from: string, target: string): boolean {
const outgoing = outgoingTransitions(diagram)
function reaches(
outgoing: ReadonlyMap<string, readonly StateDiagramTransition[]>,
from: string,
target: string,
): boolean {
const visited = new Set<string>()
const stack = [from]
while (stack.length > 0) {
@@ -104,6 +99,7 @@ function reaches(diagram: StateDiagram, from: string, target: string): boolean {
function computeMainPath(diagram: StateDiagram): string[] {
const outgoing = outgoingTransitions(diagram)
const statesById = new Map(diagram.states.map((state) => [state.id, state]))
const start = diagram.states.find((state) => state.kind === "start")?.id ?? diagram.states[0]?.id
if (!start) return []
@@ -114,9 +110,14 @@ function computeMainPath(diagram: StateDiagram): string[] {
const candidates = (outgoing.get(current) ?? []).filter((transition) => !visited.has(transition.to))
if (candidates.length === 0) break
const next =
candidates.find((transition) => diagram.states.find((state) => state.id === transition.to)?.kind === "end") ??
candidates.find((transition) => !reaches(diagram, transition.to, current)) ??
candidates.find((transition) => !hasReverseTransition(diagram, transition))
candidates.find((transition) => statesById.get(transition.to)?.kind === "end") ??
candidates.find((transition) => !reaches(outgoing, transition.to, current)) ??
candidates.find((transition) => !hasReverseTransition(diagram, transition)) ??
candidates.find((transition) => {
const fromParent = statesById.get(current)?.parentId
const toParent = statesById.get(transition.to)?.parentId
return Boolean(fromParent && toParent && fromParent !== toParent)
})
if (!next) break
path.push(next.to)
visited.add(next.to)
@@ -132,7 +133,7 @@ function stateSize(state: StateDiagramState): { width: number; height: number; l
}
function noteLines(note: StateDiagramNote): string[] {
const lines = note.lines.flatMap(splitStateDiagramLines).map((line) => line.trim())
const lines = note.lines.flatMap(splitDiagramLines).map((line) => line.trim())
return lines.length > 0 ? lines : [""]
}
@@ -202,7 +203,7 @@ function addCompositeBounds(diagram: StateDiagram, layout: StateDiagramLayout):
const top = Math.min(...childBounds.map((bound) => bound.top)) - 2
const right = Math.max(...childBounds.map((bound) => bound.left + bound.width)) + 2
const bottom = Math.max(...childBounds.map((bound) => bound.top + bound.height)) + 2
const width = Math.max(right - left, visualLength(composite.label) + 5)
const width = Math.max(right - left, diagramTextWidth(composite.label) + 5)
const bound = {
id: composite.id,
left,
@@ -349,7 +350,7 @@ function expandCompositeBoundsForNotes(diagram: StateDiagram, layout: StateDiagr
bound.left = left
bound.top = top
bound.width = Math.max(right - left, visualLength(composite.label) + 5)
bound.width = Math.max(right - left, diagramTextWidth(composite.label) + 5)
bound.height = bottom - top
bound.centerX = bound.left + Math.floor(bound.width / 2)
bound.centerY = bound.top + Math.floor(bound.height / 2)
@@ -461,7 +462,8 @@ export function createStateDiagramLayout(
x += size.width + options.minStateGap + 8
}
const labelRows = states.reduce((rows, state) => Math.max(rows, outgoingLabelRows.get(state.id) ?? 0), 0)
y += rowHeight + Math.max(4, labelRows + 3)
const pseudoStateApproachClearance = states.some((state) => state.kind === "choice") ? 2 : 0
y += rowHeight + Math.max(4, labelRows + 3) + pseudoStateApproachClearance
}
return finalizeLayout(diagram, emptyLayout(bounds, sizes))
@@ -499,7 +501,10 @@ function createHorizontalLayout(diagram: StateDiagram, options: StateDiagramLayo
const adjacentLabelWidth = diagram.transitions
.filter((transition) => transition.from === id && transition.to === nextId)
.reduce((width, transition) => Math.max(width, measureStateTransitionLabel(transition.label).width), 0)
x += size.width + Math.max(defaultGap, adjacentLabelWidth + 2)
const crossesCompositeBoundary = Boolean(
nextId && statesById.get(id)?.parentId !== statesById.get(nextId)?.parentId,
)
x += size.width + Math.max(defaultGap, adjacentLabelWidth + (crossesCompositeBoundary ? 6 : 2))
}
const branchesByParent = new Map<string, string[]>()
@@ -550,12 +555,25 @@ function createHorizontalLayout(diagram: StateDiagram, options: StateDiagramLayo
}
const ranks = computeRanks(diagram)
const fallbackStates = diagram.states.filter((state) => !bounds.has(state.id))
const fallbackStates = diagram.states
.filter((state) => !bounds.has(state.id))
.sort((left, right) => (ranks.get(left.id) ?? 0) - (ranks.get(right.id) ?? 0))
for (const state of fallbackStates) {
const size = sizes.get(state.id)!
const rank = ranks.get(state.id) ?? bounds.size
const top = baselineY + 5
const left = rank * (size.width + defaultGap)
const rank = ranks.get(state.id) ?? bounds.size
let left = rank * (size.width + defaultGap)
while (true) {
const collision = [...bounds.values()].find(
(bound) =>
left < bound.left + bound.width + defaultGap &&
left + size.width + defaultGap > bound.left &&
top < bound.top + bound.height &&
top + size.height > bound.top,
)
if (!collision) break
left = collision.left + collision.width + defaultGap
}
bounds.set(state.id, {
id: state.id,
left,
+10 -7
View File
@@ -1,4 +1,4 @@
import { firstMeaningfulMermaidLine, numberedMermaidLines } from "../core/mermaid.js"
import { decodeMermaidText, firstMeaningfulMermaidLine, numberedMermaidLines } from "../core/mermaid.js"
import { splitDiagramLines } from "../core/text-lines.js"
import { MermaidSyntaxError } from "../diagnostics.js"
import { normalizeStateDiagramEndpoint, stateDiagramEndMarkerId, stateDiagramStartMarkerId } from "./endpoint.js"
@@ -96,7 +96,7 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
notes.push({
target: pendingNote.target,
position: pendingNote.position,
lines: pendingNote.lines,
lines: pendingNote.lines.map(decodeMermaidText),
})
pendingNote = undefined
} else if (line || pendingNote.lines.length > 0) {
@@ -119,6 +119,9 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
const directionMatch = line.match(DIRECTION_RE)
if (directionMatch) {
if (parentStack.length > 0) {
throw new MermaidSyntaxError("state", source.lineNumber, line, "Composite-local direction is not supported")
}
direction = normalizeDirection(directionMatch[1])
continue
}
@@ -128,7 +131,7 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
notes.push({
position: inlineNoteMatch[1]!.toLowerCase() as "left" | "right",
target: inlineNoteMatch[2]!,
lines: splitDiagramLines(inlineNoteMatch[3]!.trim()),
lines: splitDiagramLines(decodeMermaidText(inlineNoteMatch[3]!.trim())),
})
continue
}
@@ -150,7 +153,7 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
const id = compositeMatch[2]!
composites.push({
id,
label: compositeMatch[1] ?? id,
label: decodeMermaidText(compositeMatch[1] ?? id),
...(parentId ? { parentId } : {}),
})
parentStack.push({ id, lineNumber: source.lineNumber, sourceLine: line })
@@ -159,13 +162,13 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
const stateMatch = line.match(STATE_RE)
if (stateMatch) {
ensureState(states, stateMatch[2]!, stateMatch[1]!, "state", parentId)
ensureState(states, stateMatch[2]!, decodeMermaidText(stateMatch[1]!), "state", parentId)
continue
}
const choiceMatch = line.match(CHOICE_STATE_RE)
if (choiceMatch) {
ensureState(states, choiceMatch[1]!, "", "choice", parentId)
ensureState(states, choiceMatch[1]!, "", "choice", parentId)
continue
}
@@ -177,7 +180,7 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
const to = normalizeStateDiagramEndpoint(rawTo, "to", parentId)
ensureState(states, from, rawFrom === "[*]" ? "●" : from, rawFrom === "[*]" ? "start" : "state", parentId)
ensureState(states, to, rawTo === "[*]" ? "◎" : to, rawTo === "[*]" ? "end" : "state", parentId)
transitions.push({ from, to, label: transitionMatch[3]?.trim() ?? "" })
transitions.push({ from, to, label: decodeMermaidText(transitionMatch[3]?.trim() ?? "") })
continue
}
+37 -1
View File
@@ -1,11 +1,14 @@
import { describe, expect, test } from "bun:test"
import type { StateDiagramBoxBounds } from "./layout.js"
import { createStateDiagramLayout } from "./layout.js"
import { parseMermaidStateDiagram } from "./parser.js"
import {
createStateTransitionJunctionPlans,
createStateTransitionRenderPlans,
createStateTransitionRoutePlans,
} from "./routing.js"
import { prepareVisibleStateDiagram, type StateVisibleDiagram } from "./visible-model.js"
import type { StateVisibleDiagram } from "./visible-model.js"
import { prepareVisibleStateDiagram } from "./visible-model.js"
function bounds(id: string, centerX: number, centerY: number): StateDiagramBoxBounds {
return { id, left: centerX - 2, top: centerY - 1, width: 5, height: 3, centerX, centerY }
@@ -207,6 +210,39 @@ describe("createStateTransitionRenderPlans", () => {
[11, 4],
])
})
test("keeps vertical branch routes out of unrelated state bounds", () => {
const diagram = prepareVisibleStateDiagram(
parseMermaidStateDiagram(`stateDiagram-v2
direction TB
state "Branch root" as Root
state "Upper branch" as Upper
state "Lower branch" as Lower
state "Merged branch" as Merge
Root --> Upper: branch-up
Root --> Lower: branch-down
Upper --> Merge: merge-up
Lower --> Merge: merge-down
Merge --> Root: branch-feedback`),
)
const layout = createStateDiagramLayout(diagram, { minStateGap: 4 })
const plans = createStateTransitionRenderPlans(diagram, layout.bounds, 30)
for (const plan of plans) {
const unrelated = diagram.states
.filter((state) => state.id !== plan.route.transition.from && state.id !== plan.route.transition.to)
.map((state) => layout.bounds.get(state.id)!)
expect(
plan.path.some(([x, y]) =>
unrelated.some(
(bound) =>
x >= bound.left && x < bound.left + bound.width && y >= bound.top && y < bound.top + bound.height,
),
),
`${plan.route.transition.from} -> ${plan.route.transition.to}`,
).toBe(false)
}
})
})
describe("createStateTransitionJunctionPlans", () => {
+270 -95
View File
@@ -1,5 +1,6 @@
import { BorderChars } from "@opentui/core"
import type { DiagramDirection } from "../core/geometry.js"
import { SpatialIndex, spatialPathClaim, spatialRectClaim } from "../core/spatial.js"
import { diagramTextWidth, splitDiagramLines } from "../core/text.js"
import type { StateDiagramBoxBounds as BoxBounds } from "./layout.js"
import type { StateDiagram, StateDiagramState, StateDiagramTransition } from "./types.js"
@@ -10,14 +11,15 @@ interface StateTransitionRoutePlanBase {
from: BoxBounds
to: BoxBounds
targetIsChoice: boolean
targetIsHiddenMarker: boolean
}
export type StateTransitionRoutePlan =
| (StateTransitionRoutePlanBase & { kind: "self" })
| (StateTransitionRoutePlanBase & { kind: "horizontal-forward"; leftToRight: boolean })
| (StateTransitionRoutePlanBase & { kind: "bottom-feedback"; railY: number })
| (StateTransitionRoutePlanBase & { kind: "bottom-feedback"; railY: number; approachX: number })
| (StateTransitionRoutePlanBase & { kind: "top-feedback"; railY: number })
| (StateTransitionRoutePlanBase & { kind: "bottom-parallel"; railY: number })
| (StateTransitionRoutePlanBase & { kind: "bottom-parallel"; railY: number; approachX: number })
| (StateTransitionRoutePlanBase & { kind: "vertical-elbow"; hasReverse: boolean; offsetConnector: boolean })
| (StateTransitionRoutePlanBase & { kind: "side-parallel"; railX: number })
| (StateTransitionRoutePlanBase & { kind: "vertical" })
@@ -192,6 +194,93 @@ function hasOpposingTopConnector(
})
}
function verticalCorridorCrossesUnrelatedState(
diagram: StateVisibleDiagram,
transition: StateVisibleTransition,
from: BoxBounds,
to: BoxBounds,
bounds: ReadonlyMap<string, BoxBounds>,
): boolean {
const top = Math.min(from.top + from.height, to.top + to.height)
const bottom = Math.max(from.top - 1, to.top - 1)
return diagram.states.some((state) => {
if (state.id === transition.from || state.id === transition.to || isHiddenCompositeMarker(state)) return false
const bound = bounds.get(state.id)
return Boolean(
bound &&
from.centerX >= bound.left &&
from.centerX < bound.left + bound.width &&
top < bound.top + bound.height &&
bottom >= bound.top,
)
})
}
function horizontalCorridorCrossesUnrelatedState(
diagram: StateVisibleDiagram,
transition: StateVisibleTransition,
from: BoxBounds,
to: BoxBounds,
bounds: ReadonlyMap<string, BoxBounds>,
): boolean {
const leftToRight = from.centerX <= to.centerX
const startX = leftToRight ? from.left + from.width : from.left - 1
const endX = leftToRight ? to.left - 1 : to.left + to.width
const space = SpatialIndex.empty().add(
...diagram.states.flatMap((state) => {
if (state.id === transition.from || state.id === transition.to || isHiddenCompositeMarker(state)) return []
const bound = bounds.get(state.id)
return bound ? [spatialRectClaim(`state:${state.id}`, `state:${state.id}`, "body", bound)] : []
}),
)
const corridor = spatialPathClaim(
`corridor:${transition.from}:${transition.to}`,
`transition:${transition.from}:${transition.to}`,
"route",
[
{ x: startX, y: from.centerY },
{ x: endX, y: from.centerY },
],
)
return !space.isFree(corridor)
}
function bottomApproachX(
diagram: StateVisibleDiagram,
transition: StateVisibleTransition,
from: BoxBounds,
to: BoxBounds,
bounds: ReadonlyMap<string, BoxBounds>,
railY: number,
): number {
const targetX = to.width > 1 ? (from.centerX > to.centerX ? to.left + 1 : to.left + to.width - 2) : to.centerX
const targetBottomY = to.top + to.height
const top = Math.min(targetBottomY, railY)
const bottom = Math.max(targetBottomY, railY)
const isClear = (x: number): boolean =>
!diagram.states.some((state) => {
if (state.id === transition.from || state.id === transition.to || isHiddenCompositeMarker(state)) return false
const bound = bounds.get(state.id)
return Boolean(
bound &&
x >= bound.left &&
x < bound.left + bound.width &&
top < bound.top + bound.height &&
bottom >= bound.top,
)
})
if (isClear(targetX)) return targetX
const maxX = Math.max(targetX, ...[...bounds.values()].map((bound) => bound.left + bound.width)) + 1
for (let distance = 1; distance <= maxX; distance++) {
const right = targetX + distance
if (isClear(right)) return right
const left = targetX - distance
if (left >= 0 && isClear(left)) return left
}
return targetX
}
export function createStateTransitionRoutePlans(
diagram: StateVisibleDiagram,
bounds: ReadonlyMap<string, BoxBounds>,
@@ -200,16 +289,29 @@ export function createStateTransitionRoutePlans(
): StateTransitionRoutePlan[] {
const statesById = new Map(diagram.states.map((state) => [state.id, state]))
const endpointOccurrences = new Map<string, number>()
const maxLabelWidth = Math.max(
0,
...diagram.transitions.map((transition) => measureStateTransitionLabel(transition.label).width),
)
const parallelLaneGap = Math.max(
3,
...diagram.transitions.map((transition) => measureStateTransitionLabel(transition.label).height + 2),
)
const sideLaneX = Math.max(0, ...[...bounds.values()].map((bound) => bound.left + bound.width)) + maxLabelWidth + 3
let nextSideRailX = Math.max(0, ...[...bounds.values()].map((bound) => bound.left + bound.width)) + 3
const feedbackAllocations = createFeedbackAllocations(diagram, bounds, feedbackLaneY, parallelLaneGap, feedbackTopY)
let nextBottomRailY =
Math.max(
feedbackLaneY - parallelLaneGap,
...[...feedbackAllocations.values()]
.filter((allocation) => allocation.side === "bottom")
.map((allocation) => allocation.railY),
) + parallelLaneGap
const allocateSideRail = (label: string): number => {
const railX = nextSideRailX
nextSideRailX += Math.max(3, measureStateTransitionLabel(label).width + 2)
return railX
}
const allocateBottomRail = (): number => {
const railY = nextBottomRailY
nextBottomRailY += parallelLaneGap
return railY
}
return diagram.transitions.flatMap((transition): StateTransitionRoutePlan[] => {
const from = bounds.get(transition.from)
@@ -217,8 +319,9 @@ export function createStateTransitionRoutePlans(
if (!from || !to) return []
const targetState = statesById.get(transition.to)
const targetIsChoice = targetState?.kind === "choice" || isHiddenCompositeMarker(targetState)
const base = { transition, from, to, targetIsChoice }
const targetIsChoice = targetState?.kind === "choice"
const targetIsHiddenMarker = isHiddenCompositeMarker(targetState)
const base = { transition, from, to, targetIsChoice, targetIsHiddenMarker }
if (transition.from === transition.to) return [{ ...base, kind: "self" }]
const endpointKey = `${transition.from}\u0000${transition.to}`
const parallelIndex = endpointOccurrences.get(endpointKey) ?? 0
@@ -227,30 +330,80 @@ export function createStateTransitionRoutePlans(
(diagram.direction === "LR" || diagram.direction === "RL") && isStateHorizontalFeedback(diagram, from, to)
const feedbackAllocation = feedbackAllocations.get(transition)
if (feedbackAllocation) {
if (feedbackAllocation.side === "bottom") {
return [
{
...base,
kind: "bottom-feedback",
railY: feedbackAllocation.railY,
approachX: bottomApproachX(diagram, transition, from, to, bounds, feedbackAllocation.railY),
},
]
}
return [
{
...base,
kind: feedbackAllocation.side === "bottom" ? "bottom-feedback" : "top-feedback",
kind: "top-feedback",
railY: feedbackAllocation.railY,
},
]
}
if (parallelIndex > 0) {
if (diagram.direction === "LR" || diagram.direction === "RL") {
if ((diagram.direction === "LR" || diagram.direction === "RL") && from.centerY === to.centerY) {
const railY = allocateBottomRail()
return [
{
...base,
kind: "bottom-parallel",
railY: feedbackLaneY + (parallelIndex - 1) * parallelLaneGap,
railY,
approachX: bottomApproachX(diagram, transition, from, to, bounds, railY),
},
]
}
return [{ ...base, kind: "side-parallel", railX: sideLaneX + (parallelIndex - 1) * parallelLaneGap }]
return [{ ...base, kind: "side-parallel", railX: allocateSideRail(transition.label) }]
}
if (diagram.direction !== "LR" && diagram.direction !== "RL") {
const fromParent = statesById.get(transition.from)?.parentId
const toParent = statesById.get(transition.to)?.parentId
if (fromParent && toParent && fromParent !== toParent) {
return [{ ...base, kind: "side-parallel", railX: allocateSideRail(transition.label) }]
}
if (verticalCorridorCrossesUnrelatedState(diagram, transition, from, to, bounds)) {
return [{ ...base, kind: "side-parallel", railX: allocateSideRail(transition.label) }]
}
if (from.centerY > to.centerY) {
return [{ ...base, kind: "side-parallel", railX: allocateSideRail(transition.label) }]
}
if (from.centerY === to.centerY) {
if (hasReverseTransition(diagram, transition) && from.centerX > to.centerX) {
const railY = allocateBottomRail()
return [
{
...base,
kind: "bottom-parallel",
railY,
approachX: bottomApproachX(diagram, transition, from, to, bounds, railY),
},
]
}
return [{ ...base, kind: "horizontal-forward", leftToRight: from.centerX <= to.centerX }]
}
if (from.centerX !== to.centerX) {
return [{ ...base, kind: "vertical-elbow", hasReverse: false, offsetConnector: false }]
}
return [{ ...base, kind: "vertical" }]
}
if (diagram.direction !== "LR" && diagram.direction !== "RL") return [{ ...base, kind: "vertical" }]
if (from.centerY !== to.centerY) {
if (from.centerY > to.centerY && feedback) return [{ ...base, kind: "bottom-feedback", railY: feedbackLaneY }]
if (from.centerY > to.centerY && feedback)
return [
{
...base,
kind: "bottom-feedback",
railY: feedbackLaneY,
approachX: bottomApproachX(diagram, transition, from, to, bounds, feedbackLaneY),
},
]
const hasReverse = hasReverseTransition(diagram, transition)
return [
{
@@ -261,7 +414,26 @@ export function createStateTransitionRoutePlans(
},
]
}
if (feedback) return [{ ...base, kind: "bottom-feedback", railY: feedbackLaneY }]
if (feedback)
return [
{
...base,
kind: "bottom-feedback",
railY: feedbackLaneY,
approachX: bottomApproachX(diagram, transition, from, to, bounds, feedbackLaneY),
},
]
if (horizontalCorridorCrossesUnrelatedState(diagram, transition, from, to, bounds)) {
const railY = allocateBottomRail()
return [
{
...base,
kind: "bottom-parallel",
railY,
approachX: bottomApproachX(diagram, transition, from, to, bounds, railY),
},
]
}
return [{ ...base, kind: "horizontal-forward", leftToRight: from.centerX <= to.centerX }]
})
}
@@ -333,7 +505,7 @@ function addTopDeparture(builder: StateTransitionRenderBuilder, bounds: BoxBound
}
function addHorizontalForward(builder: StateTransitionRenderBuilder): void {
const { from, to, targetIsChoice, leftToRight, transition } = builder.route as Extract<
const { from, to, targetIsChoice, targetIsHiddenMarker, leftToRight, transition } = builder.route as Extract<
StateTransitionRoutePlan,
{ kind: "horizontal-forward" }
>
@@ -343,9 +515,12 @@ function addHorizontalForward(builder: StateTransitionRenderBuilder): void {
const step = leftToRight ? 1 : -1
const startX = leftToRight ? from.left + from.width : from.left - 1
const endX = leftToRight ? to.left - 1 : to.left + to.width
addHorizontalLine(builder, startX, targetIsChoice ? endX : endX - step, y, step)
if (targetIsChoice) addPathPoint(builder, to.left, y)
else addCell(builder, { x: endX, y, arrowDirection: leftToRight ? "right" : "left" })
addHorizontalLine(builder, startX, endX - step, y, step)
addCell(
builder,
targetIsHiddenMarker ? { x: endX, y, char: "─" } : { x: endX, y, arrowDirection: leftToRight ? "right" : "left" },
)
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, y)
if (!transition.label) return
const metrics = measureStateTransitionLabel(transition.label)
const labelX = Math.min(startX, endX) + Math.max(1, Math.floor((Math.abs(endX - startX) - metrics.width) / 2))
@@ -378,14 +553,14 @@ function outsideTopY(bounds: BoxBounds): number {
}
function addBottomLaneTransition(builder: StateTransitionRenderBuilder): void {
const { from, to, targetIsChoice, transition, railY } = builder.route as Extract<
const { from, to, targetIsChoice, targetIsHiddenMarker, transition, railY, approachX } = builder.route as Extract<
StateTransitionRoutePlan,
{ kind: "bottom-feedback" | "bottom-parallel" }
>
const sourceX = from.centerX
const targetX = to.width > 1 ? (sourceX > to.centerX ? to.left + 1 : to.left + to.width - 2) : to.centerX
const targetRailCutsSource = targetX >= from.left && targetX <= from.left + from.width - 1
const railTargetX = targetRailCutsSource ? Math.max(from.left + from.width, to.left + to.width) + 2 : targetX
const railTargetX = targetRailCutsSource ? Math.max(from.left + from.width, to.left + to.width) + 2 : approachX
const sourceBottomY = outsideBottomY(from)
const targetBottomY = outsideBottomY(to)
addBottomDeparture(builder, from, sourceX)
@@ -406,8 +581,13 @@ function addBottomLaneTransition(builder: StateTransitionRenderBuilder): void {
addCell(builder, { x, y: targetBottomY, char: "─" })
}
}
addCell(builder, { x: targetX, y: targetBottomY, ...(targetIsChoice ? { char: "│" } : { arrowDirection: "up" }) })
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
addCell(
builder,
targetIsHiddenMarker
? { x: targetX, y: targetBottomY, char: "│" }
: { x: targetX, y: targetBottomY, arrowDirection: "up" },
)
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
if (!transition.label) return
const metrics = measureStateTransitionLabel(transition.label)
const horizontalRoom = Math.abs(sourceX - railTargetX) - 2
@@ -419,7 +599,7 @@ function addBottomLaneTransition(builder: StateTransitionRenderBuilder): void {
}
function addTopFeedbackTransition(builder: StateTransitionRenderBuilder): void {
const { from, to, targetIsChoice, transition, railY } = builder.route as Extract<
const { from, to, targetIsChoice, targetIsHiddenMarker, transition, railY } = builder.route as Extract<
StateTransitionRoutePlan,
{ kind: "top-feedback" }
>
@@ -437,8 +617,13 @@ function addTopFeedbackTransition(builder: StateTransitionRenderBuilder): void {
}
addCell(builder, { x: targetX, y: railY, char: sourceX > targetX ? "╭" : "╮" })
for (let y = railY + 1; y < targetTopY; y++) addCell(builder, { x: targetX, y, char: "│" })
addCell(builder, { x: targetX, y: targetTopY, ...(targetIsChoice ? { char: "│" } : { arrowDirection: "down" }) })
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
addCell(
builder,
targetIsHiddenMarker
? { x: targetX, y: targetTopY, char: "│" }
: { x: targetX, y: targetTopY, arrowDirection: "down" },
)
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
if (!transition.label) return
const metrics = measureStateTransitionLabel(transition.label)
const horizontalRoom = Math.abs(sourceX - targetX) - 2
@@ -450,7 +635,7 @@ function addTopFeedbackTransition(builder: StateTransitionRenderBuilder): void {
}
function addSideParallelTransition(builder: StateTransitionRenderBuilder): void {
const { from, to, targetIsChoice, transition, railX } = builder.route as Extract<
const { from, to, targetIsChoice, targetIsHiddenMarker, transition, railX } = builder.route as Extract<
StateTransitionRoutePlan,
{ kind: "side-parallel" }
>
@@ -465,9 +650,16 @@ function addSideParallelTransition(builder: StateTransitionRenderBuilder): void
for (let y = startY + verticalStep; y !== endY; y += verticalStep) addCell(builder, { x: railX, y, char: "│" })
addCell(builder, { x: railX, y: endY, char: verticalStep === 1 ? "╯" : "╮" })
for (let x = railX - 1; x > endX; x--) addCell(builder, { x, y: endY, char: "─" })
addCell(builder, { x: endX, y: endY, ...(targetIsChoice ? { char: "─" } : { arrowDirection: "left" }) })
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
if (transition.label) addLabel(builder, railX + 2, Math.min(startY, endY) + 1, transition.label)
addCell(
builder,
targetIsHiddenMarker ? { x: endX, y: endY, char: "─" } : { x: endX, y: endY, arrowDirection: "left" },
)
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
if (transition.label) {
const metrics = measureStateTransitionLabel(transition.label)
const labelY = Math.max(0, Math.floor((startY + endY - metrics.height + 1) / 2))
addLabel(builder, railX + 2, labelY, transition.label)
}
}
function innerConnectorX(bounds: BoxBounds, preferredX: number): number {
@@ -476,10 +668,8 @@ function innerConnectorX(bounds: BoxBounds, preferredX: number): number {
}
function addVerticalElbowTransition(builder: StateTransitionRenderBuilder): void {
const { from, to, transition, targetIsChoice, hasReverse, offsetConnector } = builder.route as Extract<
StateTransitionRoutePlan,
{ kind: "vertical-elbow" }
>
const { from, to, transition, targetIsChoice, targetIsHiddenMarker, hasReverse, offsetConnector } =
builder.route as Extract<StateTransitionRoutePlan, { kind: "vertical-elbow" }>
const topToBottom = from.centerY < to.centerY
const offset = offsetConnector ? (topToBottom ? -2 : 2) : 0
const startX = innerConnectorX(from, from.centerX + offset)
@@ -513,13 +703,19 @@ function addVerticalElbowTransition(builder: StateTransitionRenderBuilder): void
}
}
}
const targetChar = targetIsChoice ? (hasTargetApproach || startX === endX ? "│" : topToBottom ? "┬" : "┴") : undefined
const targetChar = targetIsHiddenMarker
? hasTargetApproach || startX === endX
? "│"
: topToBottom
? "┬"
: "┴"
: undefined
addCell(builder, {
x: endX,
y: endY,
...(targetChar ? { char: targetChar } : { arrowDirection: topToBottom ? "down" : "up" }),
})
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
if (!transition.label) return
const metrics = measureStateTransitionLabel(transition.label)
if (topToBottom) {
@@ -543,7 +739,7 @@ function addVerticalElbowTransition(builder: StateTransitionRenderBuilder): void
}
function addVerticalTransition(builder: StateTransitionRenderBuilder): void {
const { from, to, transition, targetIsChoice } = builder.route
const { from, to, transition, targetIsChoice, targetIsHiddenMarker } = builder.route
const topToBottom = from.centerY <= to.centerY
const x = from.centerX
const startY = topToBottom ? from.top + from.height : from.top - 1
@@ -555,9 +751,9 @@ function addVerticalTransition(builder: StateTransitionRenderBuilder): void {
addCell(builder, {
x,
y: endY,
...(targetIsChoice ? { char: "│" } : { arrowDirection: topToBottom ? "down" : "up" }),
...(targetIsHiddenMarker ? { char: "│" } : { arrowDirection: topToBottom ? "down" : "up" }),
})
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
if (transition.label) addLabel(builder, x + 2, Math.min(startY, endY) + 1, transition.label)
}
@@ -590,69 +786,47 @@ function createStateTransitionRenderPlan(route: StateTransitionRoutePlan): State
return builder
}
interface StateTransitionLabelRect {
left: number
top: number
width: number
height: number
}
function labelRect(label: StateTransitionRenderLabel, width: number): StateTransitionLabelRect {
return { left: label.x, top: label.y, width, height: label.lines.length }
}
function rectsOverlap(left: StateTransitionLabelRect, right: StateTransitionLabelRect): boolean {
return (
left.left < right.left + right.width &&
left.left + left.width > right.left &&
left.top < right.top + right.height &&
left.top + left.height > right.top
)
}
function placeStateTransitionLabels(
plans: readonly StateTransitionRenderPlan[],
diagram: StateVisibleDiagram,
bounds: ReadonlyMap<string, BoxBounds>,
): StateTransitionRenderPlan[] {
const routeCells = new Set(plans.flatMap((plan) => plan.cells.map((cell) => `${cell.x}:${cell.y}`)))
const placedLabels: StateTransitionLabelRect[] = []
const stateRects = diagram.states.flatMap((state) => {
const bound = bounds.get(state.id)
return bound && !isHiddenCompositeMarker(state)
? [{ left: bound.left, top: bound.top, width: bound.width, height: bound.height }]
: []
})
let space = SpatialIndex.empty().add(
...diagram.states.flatMap((state) => {
const bound = bounds.get(state.id)
return bound && !isHiddenCompositeMarker(state)
? [spatialRectClaim(`state:${state.id}`, `state:${state.id}`, "body", bound)]
: []
}),
...plans.map((plan, index) =>
spatialPathClaim(
`route:${index}`,
`route:${index}`,
"route",
plan.path.map(([x, y]) => ({ x, y })),
),
),
)
return plans.map((plan) => {
return plans.map((plan, planIndex) => {
if (!plan.label) return plan
const width = Math.max(...plan.label.lines.map(diagramTextWidth))
if (plan.label.lines.length === 1) {
placedLabels.push(labelRect(plan.label, width))
return plan
}
const statePadding = 1
const statePadding = plan.label.lines.length === 1 ? 0 : 1
const labelClaim = (x: number, y: number) =>
spatialRectClaim(`label:${planIndex}`, `label:${planIndex}`, "label", {
left: x,
top: y,
width,
height: plan.label!.lines.length,
})
const isClear = (x: number, y: number): boolean => {
if (x < 0 || y < 0) return false
const rect = labelRect({ ...plan.label!, x, y }, width)
if (
stateRects.some((state) =>
rectsOverlap(rect, {
left: state.left - statePadding,
top: state.top - statePadding,
width: state.width + statePadding * 2,
height: state.height + statePadding * 2,
}),
)
)
return false
if (placedLabels.some((label) => rectsOverlap(rect, label))) return false
for (let row = rect.top; row < rect.top + rect.height; row++) {
for (let column = rect.left; column < rect.left + rect.width; column++) {
if (routeCells.has(`${column}:${row}`)) return false
}
}
return true
return space.isFree(labelClaim(x, y), {
clearance: {
body: statePadding,
label: { x: 1, y: 0 },
},
})
}
let x = plan.label.x
@@ -672,7 +846,7 @@ function placeStateTransitionLabels(
}
}
placedLabels.push(labelRect({ ...plan.label, x, y }, width))
space = space.add(labelClaim(x, y))
return { ...plan, label: { ...plan.label, x, y } }
})
}
@@ -703,6 +877,7 @@ export function createStateTransitionJunctionPlans(
bounds: ReadonlyMap<string, BoxBounds>,
renderPlans: readonly StateTransitionRenderPlan[],
): StateTransitionJunctionPlan[] {
const renderPlanByTransition = new Map(renderPlans.map((plan) => [plan.route.transition, plan]))
return diagram.states.flatMap((state): StateTransitionJunctionPlan[] => {
const kind =
state.kind === "choice" ? "choice" : isHiddenCompositeMarker(state) ? "hidden-composite-marker" : undefined
@@ -713,7 +888,7 @@ export function createStateTransitionJunctionPlans(
const connections = new Set<DiagramDirection>()
const transitions: StateVisibleTransition[] = []
for (const transition of diagram.transitions) {
const renderPlan = renderPlans.find((plan) => plan.route.transition === transition)
const renderPlan = renderPlanByTransition.get(transition)
let connected = false
if (transition.to === state.id) {
const junction = renderPlan?.path.at(-1)
@@ -20,6 +20,43 @@ describe("prepareVisibleStateDiagram", () => {
expect(visible.states.some((state) => state.id === "Authenticated.__start")).toBe(false)
expect(visible.states.some((state) => state.id === "Authenticated.__end")).toBe(false)
expect(entry).toMatchObject({ from: "__start", to: "Idle", label: "login" })
expect(exit).toMatchObject({ from: "Editing", to: "__end", label: "save" })
expect(exit).toMatchObject({ from: "Editing", to: "__end", label: "save<br/>logout" })
})
test("collapses nested composite entry chains without retaining scoped markers", () => {
const visible = prepareVisibleStateDiagram(
parseMermaidStateDiagram(`stateDiagram-v2
state Session {
[*] --> Open
state Open {
[*] --> Clean
Clean --> Dirty: edit
Dirty --> Clean: save
}
Open --> [*]: close
}
[*] --> Session
Session --> [*]`),
)
expect(visible.states.map((state) => state.id)).toEqual(["Clean", "Dirty", "__start", "__end"])
expect(visible.transitions).toContainEqual({ from: "__start", to: "Clean", label: "" })
expect(visible.transitions.some((transition) => transition.from.includes(".__start"))).toBe(false)
expect(visible.transitions.some((transition) => transition.to.includes(".__start"))).toBe(false)
})
test("preserves labels on both sides of collapsed composite markers", () => {
const visible = prepareVisibleStateDiagram(
parseMermaidStateDiagram(`stateDiagram-v2
[*] --> Session: open session
state Session {
[*] --> Ready: initialize
Ready --> [*]: finalize
}
Session --> [*]: close session`),
)
expect(visible.transitions).toContainEqual({ from: "__start", to: "Ready", label: "open session<br/>initialize" })
expect(visible.transitions).toContainEqual({ from: "Ready", to: "__end", label: "finalize<br/>close session" })
})
})
+15 -20
View File
@@ -11,7 +11,7 @@ export function isHiddenCompositeMarker(state: StateDiagramState | undefined): b
}
function composeTransitionLabel(incoming: StateDiagramTransition, outgoing: StateDiagramTransition): string {
return incoming.label || outgoing.label
return [incoming.label, outgoing.label].filter(Boolean).join("<br/>")
}
function collapseHiddenCompositeMarkerTransitionsOnce(
@@ -23,33 +23,28 @@ function collapseHiddenCompositeMarkerTransitionsOnce(
)
if (hiddenMarkers.size === 0) return { transitions: [...transitions], changed: false }
const skipped = new Set<StateVisibleTransition>()
const collapsed: StateVisibleTransition[] = []
let changed = false
for (const markerId of hiddenMarkers) {
const incoming = transitions.filter((transition) => transition.to === markerId && transition.from !== markerId)
const outgoing = transitions.filter((transition) => transition.from === markerId && transition.to !== markerId)
if (incoming.length === 0 || outgoing.length === 0) continue
changed = true
for (const incomingTransition of incoming) {
skipped.add(incomingTransition)
for (const outgoingTransition of outgoing) {
skipped.add(outgoingTransition)
collapsed.push({
from: incomingTransition.from,
to: outgoingTransition.to,
label: composeTransitionLabel(incomingTransition, outgoingTransition),
})
}
const skipped = new Set([...incoming, ...outgoing])
return {
transitions: [
...transitions.filter((transition) => !skipped.has(transition)),
...incoming.flatMap((incomingTransition) =>
outgoing.map((outgoingTransition) => ({
from: incomingTransition.from,
to: outgoingTransition.to,
label: composeTransitionLabel(incomingTransition, outgoingTransition),
})),
),
],
changed: true,
}
}
return {
transitions: [...transitions.filter((transition) => !skipped.has(transition)), ...collapsed],
changed,
}
return { transitions: [...transitions], changed: false }
}
function collapseHiddenCompositeMarkerTransitions(diagram: StateDiagram): StateVisibleTransition[] {
@@ -26,6 +26,21 @@ describe("parser diagnostics", () => {
).toThrow('Unsupported syntax in flowchart diagram at line 3: "A --o B"')
})
test("does not partially parse unsupported flowchart syntax", () => {
for (const statement of ["A & B --> C", "A((Start)) --> B", "A-->B; B-->C"]) {
expect(() => parseMermaidFlowchartDiagram(`flowchart LR\n ${statement}`)).toThrow(MermaidSyntaxError)
}
})
test("does not treat arrows inside flowchart node labels as edges", () => {
const diagram = parseMermaidFlowchartDiagram(`flowchart LR
A["send --> receive"] --> B`)
expect(diagram.nodes.map((node) => node.id)).toEqual(["A", "B"])
expect(diagram.nodes[0]?.label).toBe("send --> receive")
expect(diagram.edges).toHaveLength(1)
})
test("exposes structured syntax errors through top-level rendering", () => {
try {
renderSequenceDiagram(`sequenceDiagram
@@ -41,6 +56,12 @@ describe("parser diagnostics", () => {
}
})
test("rejects unsupported bidirectional sequence arrows without phantom participants", () => {
for (const message of ["A<<->>B: hello", "A<<-->>B: hello"]) {
expect(() => parseMermaidSequenceDiagram(`sequenceDiagram\n ${message}`)).toThrow(MermaidSyntaxError)
}
})
test("reports unclosed state constructs at their opening line", () => {
expect(() =>
parseMermaidStateDiagram(`stateDiagram-v2
@@ -55,6 +76,17 @@ describe("parser diagnostics", () => {
)
})
test("rejects unsupported composite-local state directions", () => {
expect(() =>
parseMermaidStateDiagram(`stateDiagram-v2
direction LR
state Parent {
direction TB
A --> B
}`),
).toThrow("Composite-local direction is not supported")
})
test("reports malformed sequence block endings", () => {
expect(() =>
parseMermaidSequenceDiagram(`sequenceDiagram
+10 -34
View File
@@ -1,43 +1,19 @@
import type { ConnectionInfo } from "@opencode-ai/client"
import type {
ConnectionInfo,
IntegrationCommandMethod,
IntegrationEnvMethod,
IntegrationKeyMethod,
IntegrationMethod,
IntegrationOAuthMethod,
} from "@opencode-ai/client"
import type { IntegrationApi } from "@opencode-ai/client/effect/api"
import { Credential } from "@opencode-ai/schema/credential"
import { Form } from "@opencode-ai/schema/form"
import type { Effect, Scope } from "effect"
import type { Transform } from "./registration.js"
type IntegrationInputs = Record<string, string>
type IntegrationRef = { id: string; name: string }
export interface IntegrationOAuthMethod {
readonly id: string
readonly type: "oauth"
readonly label: string
readonly form?: Form.Fields
}
export interface IntegrationCommandMethod {
readonly id: string
readonly type: "command"
readonly label: string
readonly command: ReadonlyArray<string>
}
export interface IntegrationKeyMethod {
readonly type: "key"
readonly label?: string
readonly form?: Form.Fields
}
export interface IntegrationEnvMethod {
readonly type: "env"
readonly names: ReadonlyArray<string>
}
export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationEnvMethod
export type IntegrationOAuthAuthorization = {
readonly url: string
readonly instructions: string
@@ -55,7 +31,7 @@ export type IntegrationOAuthAuthorization = {
export type IntegrationOAuthMethodRegistration = {
readonly integrationID: string
readonly method: IntegrationOAuthMethod
readonly authorize: (answer: Form.Answer) => Effect.Effect<IntegrationOAuthAuthorization, unknown, Scope.Scope>
readonly authorize: (inputs: IntegrationInputs) => Effect.Effect<IntegrationOAuthAuthorization, unknown, Scope.Scope>
readonly refresh?: (credential: Credential.OAuth) => Effect.Effect<Credential.OAuth, unknown>
readonly label?: (credential: Credential.OAuth) => string | undefined
}
+11 -38
View File
@@ -1,42 +1,18 @@
import type { ConnectionInfo } from "@opencode-ai/client"
import type {
ConnectionInfo,
IntegrationCommandMethod,
IntegrationEnvMethod,
IntegrationKeyMethod,
IntegrationMethod,
IntegrationOAuthMethod,
} from "@opencode-ai/client"
import type { IntegrationApi } from "@opencode-ai/client/promise/api"
import { Credential } from "@opencode-ai/schema/credential"
import { Form } from "@opencode-ai/schema/form"
import type { Transform } from "./registration.js"
type IntegrationInputs = Record<string, string>
type IntegrationRef = { id: string; name: string }
export interface IntegrationOAuthMethod {
readonly id: string
readonly type: "oauth"
readonly label: string
readonly form?: Form.Fields
}
export interface IntegrationCommandMethod {
readonly id: string
readonly type: "command"
readonly label: string
readonly command: ReadonlyArray<string>
}
export interface IntegrationKeyMethod {
readonly type: "key"
readonly label?: string
readonly form?: Form.Fields
}
export interface IntegrationEnvMethod {
readonly type: "env"
readonly names: ReadonlyArray<string>
}
export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationEnvMethod
export type IntegrationOAuthAuthorization = {
readonly url: string
readonly instructions: string
@@ -55,7 +31,7 @@ export type IntegrationOAuthAuthorization = {
export type IntegrationOAuthMethodRegistration = {
readonly integrationID: string
readonly method: IntegrationOAuthMethod
readonly authorize: (answer: Form.Answer) => Promise<IntegrationOAuthAuthorization>
readonly authorize: (inputs: IntegrationInputs) => Promise<IntegrationOAuthAuthorization>
readonly refresh?: (credential: Credential.OAuth) => Promise<Credential.OAuth>
readonly label?: (credential: Credential.OAuth) => string | undefined
}
@@ -63,10 +39,7 @@ export type IntegrationOAuthMethodRegistration = {
export type IntegrationMethodRegistration =
| IntegrationOAuthMethodRegistration
| { readonly integrationID: string; readonly method: IntegrationCommandMethod }
| {
readonly integrationID: string
readonly method: IntegrationKeyMethod
}
| { readonly integrationID: string; readonly method: IntegrationKeyMethod }
| { readonly integrationID: string; readonly method: IntegrationEnvMethod }
export interface IntegrationDraft {
+3 -3
View File
@@ -1,11 +1,12 @@
import { Integration } from "@opencode-ai/schema/integration"
import { Location } from "@opencode-ai/schema/location"
import { Form } from "@opencode-ai/schema/form"
import { Schema } from "effect"
import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
import { InvalidRequestError } from "../errors.js"
import { LocationQuery, locationQueryOpenApi } from "./location.js"
const Inputs = Schema.Record(Schema.String, Schema.String)
export const IntegrationGroup = HttpApiGroup.make("server.integration")
.add(
HttpApiEndpoint.get("integration.list", "/api/integration", {
@@ -58,7 +59,6 @@ export const IntegrationGroup = HttpApiGroup.make("server.integration")
query: LocationQuery,
payload: Schema.Struct({
key: Schema.String,
answer: Schema.optional(Form.Answer),
label: Schema.optional(Schema.String),
}),
success: HttpApiSchema.NoContent,
@@ -79,7 +79,7 @@ export const IntegrationGroup = HttpApiGroup.make("server.integration")
query: LocationQuery,
payload: Schema.Struct({
methodID: Integration.MethodID,
answer: Schema.optional(Form.Answer),
inputs: Inputs,
label: Schema.optional(Schema.String),
}),
success: Location.response(Integration.Attempt),
-2
View File
@@ -5,7 +5,6 @@ import { optional } from "./schema.js"
import { IntegrationMethodID } from "./integration-id.js"
import { ascending } from "./identifier.js"
import { NonNegativeInt, statics } from "./schema.js"
import { Form } from "./form.js"
export const ID = Schema.String.pipe(
Schema.brand("Credential.ID"),
@@ -28,7 +27,6 @@ export const Key = Schema.Struct({
type: Schema.Literal("key"),
key: Schema.String,
metadata: optional(Schema.Record(Schema.String, Schema.Unknown)),
configuration: optional(Form.Answer),
}).annotate({ identifier: "Credential.Key" })
export const Value = Schema.Union([OAuth, Key])
+38 -3
View File
@@ -7,7 +7,6 @@ import { Connection } from "./connection.js"
import { ascending } from "./identifier.js"
import { statics } from "./schema.js"
import { IntegrationID, IntegrationMethodID } from "./integration-id.js"
import { Form } from "./form.js"
export const ID = IntegrationID
export type ID = typeof ID.Type
@@ -15,12 +14,46 @@ export type ID = typeof ID.Type
export const MethodID = IntegrationMethodID
export type MethodID = typeof MethodID.Type
export interface When extends Schema.Schema.Type<typeof When> {}
export const When = Schema.Struct({
key: Schema.String,
op: Schema.Literals(["eq", "neq"]),
value: Schema.String,
}).annotate({ identifier: "Integration.When" })
export interface TextPrompt extends Schema.Schema.Type<typeof TextPrompt> {}
export const TextPrompt = Schema.Struct({
type: Schema.Literal("text"),
key: Schema.String,
message: Schema.String,
placeholder: optional(Schema.String),
when: optional(When),
}).annotate({ identifier: "Integration.TextPrompt" })
export interface SelectPrompt extends Schema.Schema.Type<typeof SelectPrompt> {}
export const SelectPrompt = Schema.Struct({
type: Schema.Literal("select"),
key: Schema.String,
message: Schema.String,
options: Schema.Array(
Schema.Struct({
label: Schema.String,
value: Schema.String,
hint: optional(Schema.String),
}),
),
when: optional(When),
}).annotate({ identifier: "Integration.SelectPrompt" })
export const Prompt = Schema.Union([TextPrompt, SelectPrompt]).pipe(Schema.toTaggedUnion("type"))
export type Prompt = typeof Prompt.Type
export interface OAuthMethod extends Schema.Schema.Type<typeof OAuthMethod> {}
export const OAuthMethod = Schema.Struct({
id: MethodID,
type: Schema.Literal("oauth"),
label: Schema.String,
form: optional(Form.Fields),
prompts: optional(Schema.Array(Prompt)),
}).annotate({ identifier: "Integration.OAuthMethod" })
export interface CommandMethod extends Schema.Schema.Type<typeof CommandMethod> {}
@@ -35,7 +68,6 @@ export interface KeyMethod extends Schema.Schema.Type<typeof KeyMethod> {}
export const KeyMethod = Schema.Struct({
type: Schema.Literal("key"),
label: optional(Schema.String),
form: optional(Form.Fields),
}).annotate({ identifier: "Integration.KeyMethod" })
export interface EnvMethod extends Schema.Schema.Type<typeof EnvMethod> {}
@@ -49,6 +81,9 @@ export const Method = Schema.Union([OAuthMethod, CommandMethod, KeyMethod, EnvMe
.annotate({ identifier: "Integration.Method" })
export type Method = typeof Method.Type
export const Inputs = Schema.Record(Schema.String, Schema.String).annotate({ identifier: "Integration.Inputs" })
export type Inputs = typeof Inputs.Type
const Updated = ephemeral({
type: "integration.updated",
schema: {},
+1 -2
View File
@@ -58,7 +58,6 @@ export const IntegrationHandler = HttpApiBuilder.group(Api, "server.integration"
service.connection.key({
integrationID: ctx.params.integrationID,
key: ctx.payload.key,
answer: ctx.payload.answer,
label: ctx.payload.label,
}),
)
@@ -74,7 +73,7 @@ export const IntegrationHandler = HttpApiBuilder.group(Api, "server.integration"
service.oauth.connect({
integrationID: ctx.params.integrationID,
methodID: ctx.payload.methodID,
answer: ctx.payload.answer,
inputs: ctx.payload.inputs,
label: ctx.payload.label,
}),
),
+41 -252
View File
@@ -5,10 +5,6 @@ import type {
IntegrationInfo,
IntegrationOauthConnectOutput,
IntegrationOAuthMethod,
FormAnswer,
FormField,
FormFields,
FormValue,
} from "@opencode-ai/client"
import open from "open"
import { createMemo, createSignal, onCleanup, onMount, Show } from "solid-js"
@@ -22,7 +18,6 @@ import { DialogPrompt } from "../ui/dialog-prompt"
import { DialogSelect } from "../ui/dialog-select"
import { Link } from "../ui/link"
import { useToast } from "../ui/toast"
import { formLabel, formToggleMultiselect, formValidateValue, type FormAnswerField } from "../util/form"
const INTEGRATION_PRIORITY: Record<string, number> = {
opencode: 0,
@@ -37,10 +32,6 @@ type ConnectMethod = Exclude<IntegrationInfo["methods"][number], { type: "env" }
type IntegrationAttempt = IntegrationOauthConnectOutput["data"]
type CommandAttempt = IntegrationCommandConnectOutput["data"]
type OnIntegrationConnected = (providerID?: string) => void
const CANCELLED = Symbol("cancelled")
const CUSTOM = Symbol("custom")
const OPEN = Symbol("open")
const SUBMIT = Symbol("submit")
export function integrationOptions(list: IntegrationInfo[]) {
return list.toSorted(
@@ -190,7 +181,7 @@ function openMethod(
onConnected?: OnIntegrationConnected,
) {
if (method.type === "key") {
void beginKey(integration, method, dialog, onConnected)
dialog.replace(() => <KeyMethod integration={integration} method={method} onConnected={onConnected} />)
return
}
if (method.type === "command") {
@@ -200,21 +191,6 @@ function openMethod(
void beginOAuth(integration, method, dialog, onConnected)
}
async function beginKey(
integration: IntegrationInfo,
method: Extract<ConnectMethod, { type: "key" }>,
dialog: ReturnType<typeof useDialog>,
onConnected?: OnIntegrationConnected,
) {
const answer = method.form
? await formAnswer(dialog, method.label ?? `Connect ${integration.name}`, method.form)
: undefined
if (answer === null) return
dialog.replace(() => (
<KeyMethod integration={integration} method={method} answer={answer} onConnected={onConnected} />
))
}
function CommandStarting(props: {
integration: IntegrationInfo
method: Extract<ConnectMethod, { type: "command" }>
@@ -360,7 +336,6 @@ function CommandView(props: { title: string; output: string; message: string })
function KeyMethod(props: {
integration: IntegrationInfo
method: Extract<ConnectMethod, { type: "key" }>
answer?: FormAnswer
onConnected?: OnIntegrationConnected
}) {
const data = useData()
@@ -381,7 +356,6 @@ function KeyMethod(props: {
integrationID: props.integration.id,
location: location(data),
key,
...(props.answer ? { answer: props.answer } : {}),
})
.then(() => connected(props.integration, data, dialog, toast, props.onConnected))
.catch((cause) => setError(message(cause)))
@@ -399,17 +373,17 @@ async function beginOAuth(
dialog: ReturnType<typeof useDialog>,
onConnected?: OnIntegrationConnected,
) {
const answer = method.form ? await formAnswer(dialog, method.label, method.form) : undefined
if (answer === null) return
const inputs = method.prompts?.length ? await promptInputs(dialog, method.prompts) : {}
if (inputs === null) return
dialog.replace(() => (
<OAuthStarting integration={integration} method={method} answer={answer} onConnected={onConnected} />
<OAuthStarting integration={integration} method={method} inputs={inputs} onConnected={onConnected} />
))
}
function OAuthStarting(props: {
integration: IntegrationInfo
method: IntegrationOAuthMethod
answer?: FormAnswer
inputs: Record<string, string>
onConnected?: OnIntegrationConnected
}) {
const data = useData()
@@ -423,7 +397,7 @@ function OAuthStarting(props: {
integrationID: props.integration.id,
location: location(data),
methodID: props.method.id,
...(props.answer ? { answer: props.answer } : {}),
inputs: props.inputs,
})
.then((result) => {
if (result.data.mode === "code") {
@@ -647,234 +621,49 @@ function OAuthView(props: {
)
}
async function formAnswer(dialog: ReturnType<typeof useDialog>, title: string, fields: FormFields) {
const answer: FormAnswer = {}
for (const field of fields) {
if (!active(field, answer)) continue
const value = await fieldAnswer(dialog, title, field)
if (value === CANCELLED) return null
if (value !== undefined) answer[field.key] = value
}
return answer
}
function active(field: FormField, answer: FormAnswer) {
if (field.type === "external" || !field.when) return true
return field.when.every((when) => {
const value = answer[when.key]
if (value === undefined) return false
const hit = Array.isArray(value) ? value.includes(String(when.value)) : value === when.value
return when.op === "eq" ? hit : !hit
})
}
function fieldAnswer(
async function promptInputs(
dialog: ReturnType<typeof useDialog>,
title: string,
field: FormField,
): Promise<FormValue | undefined | typeof CANCELLED> {
if (field.type === "external") return externalAnswer(dialog, title, field)
if (field.type === "multiselect") return multiselectAnswer(dialog, title, field)
if (field.type === "boolean" || (field.type === "string" && field.options)) {
return selectAnswer(dialog, title, field)
}
return textAnswer(dialog, title, field)
}
async function selectAnswer(
dialog: ReturnType<typeof useDialog>,
title: string,
field: Extract<FormAnswerField, { type: "boolean" | "string" }>,
): Promise<FormValue | undefined | typeof CANCELLED> {
const options =
field.type === "boolean"
? field.default === false
? [
{ title: "No", value: false as FormValue },
{ title: "Yes", value: true as FormValue },
]
: [
{ title: "Yes", value: true as FormValue },
{ title: "No", value: false as FormValue },
]
: (field.options ?? []).map((option) => ({
title: option.label,
value: option.value as FormValue,
description: option.description,
}))
const choice = await new Promise<FormValue | typeof CUSTOM | undefined | typeof CANCELLED>((resolve) => {
dialog.replace(
() => (
<DialogSelect<FormValue | typeof CUSTOM | undefined>
title={formLabel(field) || title}
options={[
...options,
...(field.type === "string" && field.custom
? [{ title: "Type your own answer", value: CUSTOM as typeof CUSTOM }]
: []),
...(!field.required ? [{ title: "Skip", value: undefined }] : []),
]}
current={field.type === "string" ? field.default : undefined}
onSelect={(option) => resolve(option.value)}
/>
),
() => resolve(CANCELLED),
)
})
if (choice === CUSTOM) {
if (field.type !== "string") return CANCELLED
return textAnswer(dialog, title, field, "")
}
return choice
}
function textAnswer(
dialog: ReturnType<typeof useDialog>,
title: string,
field: Extract<FormAnswerField, { type: "string" | "number" | "integer" }>,
initial = field.default === undefined ? undefined : String(field.default),
): Promise<FormValue | undefined | typeof CANCELLED> {
return new Promise<FormValue | undefined | typeof CANCELLED>((resolve) => {
dialog.replace(
() => {
const theme = useTheme("elevated")
const [error, setError] = createSignal<string>()
return (
<DialogPrompt
title={formLabel(field) || title}
placeholder={field.type === "string" ? field.placeholder : undefined}
value={initial}
onConfirm={(input) => {
const text = input.trim()
const value = text === "" && !field.required ? undefined : field.type === "string" ? text : Number(text)
const invalid = formValidateValue(field, value)
if (invalid) {
setError(invalid)
return
}
resolve(value)
}}
description={() => (
<box gap={1}>
<Show when={field.description}>
{(description) => <text fg={theme.text.subdued}>{description()}</text>}
</Show>
<Show when={error()}>{(value) => <text fg={theme.text.feedback.error.default}>{value()}</text>}</Show>
</box>
)}
/>
)
},
() => resolve(CANCELLED),
)
})
}
async function multiselectAnswer(
dialog: ReturnType<typeof useDialog>,
title: string,
field: Extract<FormAnswerField, { type: "multiselect" }>,
): Promise<FormValue | typeof CANCELLED> {
const selected = field.default ? [...field.default] : []
while (true) {
const invalid = formValidateValue(field, selected)
const choice = await new Promise<string | typeof CUSTOM | typeof SUBMIT | typeof CANCELLED>((resolve) => {
dialog.replace(
() => (
<DialogSelect<string | typeof CUSTOM | typeof SUBMIT>
title={formLabel(field) || title}
options={[
...field.options.map((option) => ({
title: `[${selected.includes(option.value) ? "x" : " "}] ${option.label}`,
prompts: NonNullable<IntegrationOAuthMethod["prompts"]>,
) {
const inputs: Record<string, string> = {}
for (const prompt of prompts) {
if (prompt.when) {
const value = inputs[prompt.when.key]
if (value === undefined) continue
const matches = prompt.when.op === "eq" ? value === prompt.when.value : value !== prompt.when.value
if (!matches) continue
}
if (prompt.type === "select") {
const value = await new Promise<string | null>((resolve) => {
dialog.replace(
() => (
<DialogSelect
title={prompt.message}
options={prompt.options.map((option) => ({
title: option.label,
value: option.value,
description: option.description,
disabled:
!selected.includes(option.value) && field.maxItems !== undefined && selected.length >= field.maxItems,
})),
...(field.custom ? [{ title: "Type your own answer", value: CUSTOM as typeof CUSTOM }] : []),
{
title: "Continue",
value: SUBMIT as typeof SUBMIT,
description: invalid,
disabled: invalid !== undefined,
},
]}
onSelect={(option) => resolve(option.value)}
/>
),
() => resolve(CANCELLED),
)
})
if (choice === CANCELLED) return CANCELLED
if (choice === SUBMIT) return selected
if (choice === CUSTOM) {
const value = await customAnswer(dialog, title, field)
if (value === CANCELLED) return CANCELLED
if (value && !selected.includes(value)) selected.push(value)
description: option.hint,
}))}
onSelect={(option) => resolve(option.value)}
/>
),
() => resolve(null),
)
})
if (value === null) return null
inputs[prompt.key] = value
continue
}
selected.splice(0, selected.length, ...formToggleMultiselect(selected, choice))
}
}
function customAnswer(
dialog: ReturnType<typeof useDialog>,
title: string,
field: Extract<FormAnswerField, { type: "multiselect" }>,
): Promise<string | typeof CANCELLED> {
return new Promise<string | typeof CANCELLED>((resolve) => {
dialog.replace(
() => (
<DialogPrompt
title={formLabel(field) || title}
placeholder="Type your own answer"
onConfirm={(value) => {
if (value) resolve(value)
}}
/>
),
() => resolve(CANCELLED),
)
})
}
async function externalAnswer(
dialog: ReturnType<typeof useDialog>,
title: string,
field: Extract<FormField, { type: "external" }>,
): Promise<true | typeof CANCELLED> {
let opened = false
while (true) {
const choice = await new Promise<true | typeof OPEN | typeof CANCELLED>((resolve) => {
const value = await new Promise<string | null>((resolve) => {
dialog.replace(
() => (
<DialogSelect<true | typeof OPEN>
title={formLabel(field) || title}
options={[
{ title: opened ? "Open link again" : "Open link", value: OPEN as typeof OPEN, description: field.url },
{ title: "I finished", value: true as const, description: field.description, disabled: !opened },
]}
onSelect={(option) => resolve(option.value)}
/>
),
() => resolve(CANCELLED),
() => <DialogPrompt title={prompt.message} placeholder={prompt.placeholder} onConfirm={resolve} />,
() => resolve(null),
)
})
if (choice === CANCELLED) return CANCELLED
if (choice === true) return true
const result = await new Promise<boolean | typeof CANCELLED>((resolve) => {
dialog.replace(
() => <OAuthView title={formLabel(field) || title} message="Opening link..." />,
() => resolve(CANCELLED),
)
void open(field.url).then(
() => resolve(true),
() => resolve(false),
)
})
if (result === CANCELLED) return CANCELLED
opened ||= result
if (value === null) return null
inputs[prompt.key] = value
}
return inputs
}
async function connected(