@langchain/core 1.2.20 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/dist/callbacks/manager.cjs +20 -3
- package/dist/callbacks/manager.cjs.map +1 -1
- package/dist/callbacks/manager.d.cts.map +1 -1
- package/dist/callbacks/manager.d.ts.map +1 -1
- package/dist/callbacks/manager.js +20 -3
- package/dist/callbacks/manager.js.map +1 -1
- package/dist/language_models/base.cjs +1 -1
- package/dist/language_models/base.cjs.map +1 -1
- package/dist/language_models/base.js +1 -1
- package/dist/language_models/base.js.map +1 -1
- package/dist/language_models/compat.cjs +11 -14
- package/dist/language_models/compat.cjs.map +1 -1
- package/dist/language_models/compat.d.cts.map +1 -1
- package/dist/language_models/compat.d.ts.map +1 -1
- package/dist/language_models/compat.js +11 -14
- package/dist/language_models/compat.js.map +1 -1
- package/dist/language_models/openai_completions_stream.cjs +11 -14
- package/dist/language_models/openai_completions_stream.cjs.map +1 -1
- package/dist/language_models/openai_completions_stream.js +11 -14
- package/dist/language_models/openai_completions_stream.js.map +1 -1
- package/dist/runnables/graph.cjs +2 -1
- package/dist/runnables/graph.cjs.map +1 -1
- package/dist/runnables/graph.d.cts.map +1 -1
- package/dist/runnables/graph.d.ts.map +1 -1
- package/dist/runnables/graph.js +2 -1
- package/dist/runnables/graph.js.map +1 -1
- package/dist/runnables/graph_mermaid.cjs +28 -1
- package/dist/runnables/graph_mermaid.cjs.map +1 -1
- package/dist/runnables/graph_mermaid.js +28 -1
- package/dist/runnables/graph_mermaid.js.map +1 -1
- package/package.json +1 -1
|
@@ -158,21 +158,18 @@ async function* convertOpenAICompletionsStream(source, options = {}) {
|
|
|
158
158
|
const acc = blockAccumulators.get(index);
|
|
159
159
|
if (rawToolCall.id != null) acc.id = rawToolCall.id;
|
|
160
160
|
if (rawToolCall.function?.name != null) acc.name = rawToolCall.function.name;
|
|
161
|
-
const argDelta = rawToolCall.function?.arguments
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
...acc.id != null ? { id: acc.id } : {},
|
|
171
|
-
...acc.name != null ? { name: acc.name } : {},
|
|
172
|
-
args: acc.args
|
|
161
|
+
const argDelta = rawToolCall.function?.arguments;
|
|
162
|
+
if (argDelta) {
|
|
163
|
+
acc.args = (acc.args ?? "") + argDelta;
|
|
164
|
+
yield {
|
|
165
|
+
event: "content-block-delta",
|
|
166
|
+
index,
|
|
167
|
+
delta: {
|
|
168
|
+
type: "tool-call-delta",
|
|
169
|
+
args: argDelta
|
|
173
170
|
}
|
|
174
|
-
}
|
|
175
|
-
}
|
|
171
|
+
};
|
|
172
|
+
}
|
|
176
173
|
}
|
|
177
174
|
if (delta.audio) {
|
|
178
175
|
const { index, isNew } = getOrCreateBlockIndex("audio", {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai_completions_stream.js","names":[],"sources":["../../src/language_models/openai_completions_stream.ts"],"sourcesContent":["/**\n * Converts OpenAI Chat Completions-shaped stream chunks into\n * {@link ChatModelStreamEvent}s.\n *\n * Used by `@langchain/openai` and OpenAI-compatible providers (Groq, Mistral,\n * OpenRouter, IBM watsonx, etc.) without requiring a dependency on\n * `@langchain/openai`.\n *\n * @module\n */\n\nimport { finalizeContentBlock } from \"./compat.js\";\nimport type { ChatModelStreamEvent, FinishReason } from \"./event.js\";\nimport type { ContentBlock } from \"../messages/content/index.js\";\nimport type { UsageMetadata } from \"../messages/metadata.js\";\n\nexport type OpenAICompletionsFinishReason =\n | \"stop\"\n | \"length\"\n | \"max_tokens\"\n | \"tool_calls\"\n | \"function_call\"\n | \"content_filter\"\n | null;\n\nexport interface OpenAICompletionsUsage {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n prompt_tokens_details?: {\n audio_tokens?: number;\n cached_tokens?: number;\n };\n completion_tokens_details?: {\n audio_tokens?: number;\n reasoning_tokens?: number;\n };\n}\n\nexport interface OpenAICompletionsToolCallDelta {\n index?: number;\n id?: string;\n type?: \"function\";\n function?: {\n name?: string;\n arguments?: string;\n };\n}\n\nexport interface OpenAICompletionsDelta {\n role?: string;\n content?: string | null;\n reasoning_content?: string;\n reasoning?: string;\n tool_calls?: OpenAICompletionsToolCallDelta[];\n function_call?: unknown;\n audio?: {\n id?: string;\n data?: string;\n transcript?: string;\n };\n}\n\nexport interface OpenAICompletionsStreamChoice {\n index?: number;\n finish_reason?: OpenAICompletionsFinishReason;\n logprobs?: unknown;\n delta?: OpenAICompletionsDelta;\n}\n\nexport interface OpenAICompletionsStreamChunk {\n id?: string;\n model?: string;\n service_tier?: string | null;\n system_fingerprint?: string | null;\n usage?: OpenAICompletionsUsage | null;\n x_groq?: {\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n };\n };\n choices?: OpenAICompletionsStreamChoice[];\n}\n\nexport interface ConvertOpenAICompletionsStreamOptions {\n streamUsage?: boolean;\n /** Provider id for passthrough events (default `\"openai\"`). */\n provider?: string;\n /** Optional per-chunk transform before conversion. */\n mapChunk?: (\n chunk: OpenAICompletionsStreamChunk\n ) => OpenAICompletionsStreamChunk;\n}\n\ntype BlockKey = \"text\" | \"reasoning\" | \"audio\" | `tool:${number}`;\n\n/**\n * Convert an async iterable of OpenAI Chat Completions-shaped stream chunks into\n * LangChain `ChatModelStreamEvent`s with typed deltas.\n */\nexport async function* convertOpenAICompletionsStream(\n source: AsyncIterable<OpenAICompletionsStreamChunk>,\n options: ConvertOpenAICompletionsStreamOptions = {}\n): AsyncGenerator<ChatModelStreamEvent> {\n const shouldStreamUsage = options.streamUsage ?? true;\n const provider = options.provider ?? \"openai\";\n const mapChunk = options.mapChunk;\n\n const blockAccumulators = new Map<\n number,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n Record<string, any>\n >();\n const blockKeyToIndex = new Map<BlockKey, number>();\n let nextBlockIndex = 0;\n let messageStarted = false;\n let usageSnapshot: UsageMetadata | undefined;\n let finishReason: FinishReason | undefined;\n let responseMetadata: Record<string, unknown> | undefined;\n let emittedProviderMetadata = false;\n\n const getOrCreateBlockIndex = (\n key: BlockKey,\n initial: Record<string, unknown>\n ): { index: number; isNew: boolean } => {\n const existing = blockKeyToIndex.get(key);\n if (existing !== undefined) {\n return { index: existing, isNew: false };\n }\n const index = nextBlockIndex++;\n blockKeyToIndex.set(key, index);\n blockAccumulators.set(index, { ...initial });\n return { index, isNew: true };\n };\n\n for await (let data of source) {\n if (mapChunk) {\n data = mapChunk(data);\n }\n if (!messageStarted) {\n messageStarted = true;\n yield {\n event: \"message-start\" as const,\n id: data.id,\n };\n }\n\n if (!emittedProviderMetadata && (data.model || data.service_tier)) {\n emittedProviderMetadata = true;\n yield {\n event: \"provider\" as const,\n provider,\n name: \"stream_metadata\",\n payload: {\n model: data.model,\n service_tier: data.service_tier,\n },\n };\n }\n\n if (data.usage && shouldStreamUsage) {\n usageSnapshot = buildUsageSnapshot(data.usage);\n yield { event: \"usage\" as const, usage: usageSnapshot };\n }\n\n const groqUsage = data.x_groq?.usage;\n if (groqUsage && shouldStreamUsage) {\n usageSnapshot = buildGroqUsageSnapshot(groqUsage);\n yield { event: \"usage\" as const, usage: usageSnapshot };\n }\n\n const choice = data.choices?.[0];\n if (!choice) {\n continue;\n }\n\n if (choice.finish_reason != null) {\n finishReason = mapFinishReason(choice.finish_reason);\n responseMetadata = buildResponseMetadata(data, choice);\n }\n\n const { delta } = choice;\n if (!delta) {\n continue;\n }\n\n const reasoningText = getReasoningDeltaText(delta);\n if (reasoningText) {\n const key: BlockKey = \"reasoning\";\n const { index, isNew } = getOrCreateBlockIndex(key, {\n type: \"reasoning\" as const,\n reasoning: \"\",\n });\n if (isNew) {\n yield {\n event: \"content-block-start\" as const,\n index,\n content: { type: \"reasoning\", reasoning: \"\" } as ContentBlock,\n };\n }\n const acc = blockAccumulators.get(index)!;\n acc.reasoning = (acc.reasoning ?? \"\") + reasoningText;\n yield {\n event: \"content-block-delta\" as const,\n index,\n delta: {\n type: \"reasoning-delta\" as const,\n reasoning: reasoningText,\n },\n };\n }\n\n if (delta.content) {\n const key: BlockKey = \"text\";\n const { index, isNew } = getOrCreateBlockIndex(key, {\n type: \"text\" as const,\n text: \"\",\n });\n if (isNew) {\n yield {\n event: \"content-block-start\" as const,\n index,\n content: { type: \"text\", text: \"\" } as ContentBlock,\n };\n }\n const acc = blockAccumulators.get(index)!;\n acc.text = (acc.text ?? \"\") + delta.content;\n yield {\n event: \"content-block-delta\" as const,\n index,\n delta: { type: \"text-delta\" as const, text: delta.content },\n };\n }\n\n if (Array.isArray(delta.tool_calls)) {\n for (const rawToolCall of delta.tool_calls) {\n const toolIndex = rawToolCall.index ?? 0;\n const key: BlockKey = `tool:${toolIndex}`;\n const { index, isNew } = getOrCreateBlockIndex(key, {\n type: \"tool_call_chunk\" as const,\n id: rawToolCall.id,\n name: rawToolCall.function?.name,\n args: \"\",\n index: toolIndex,\n });\n if (isNew) {\n yield {\n event: \"content-block-start\" as const,\n index,\n content: {\n type: \"tool_call_chunk\",\n id: rawToolCall.id,\n name: rawToolCall.function?.name,\n args: \"\",\n index: toolIndex,\n } as ContentBlock,\n };\n }\n\n const acc = blockAccumulators.get(index)!;\n if (rawToolCall.id != null) acc.id = rawToolCall.id;\n if (rawToolCall.function?.name != null) {\n acc.name = rawToolCall.function.name;\n }\n const argDelta = rawToolCall.function?.arguments ?? \"\";\n acc.args = (acc.args ?? \"\") + argDelta;\n yield {\n event: \"content-block-delta\" as const,\n index,\n delta: {\n type: \"block-delta\" as const,\n fields: {\n type: \"tool_call_chunk\",\n ...(acc.id != null ? { id: acc.id } : {}),\n ...(acc.name != null ? { name: acc.name } : {}),\n args: acc.args,\n },\n },\n };\n }\n }\n\n if (delta.audio) {\n const key: BlockKey = \"audio\";\n const { index, isNew } = getOrCreateBlockIndex(key, {\n type: \"audio\" as const,\n id: delta.audio.id,\n data: \"\",\n mimeType: \"audio/pcm\",\n transcript: delta.audio.transcript ?? \"\",\n });\n if (isNew) {\n yield {\n event: \"content-block-start\" as const,\n index,\n content: {\n type: \"audio\",\n id: delta.audio.id,\n data: \"\",\n mimeType: \"audio/pcm\",\n transcript: delta.audio.transcript ?? \"\",\n } as ContentBlock,\n };\n }\n const acc = blockAccumulators.get(index)!;\n if (delta.audio.transcript) {\n acc.transcript = (acc.transcript ?? \"\") + delta.audio.transcript;\n yield {\n event: \"content-block-delta\" as const,\n index,\n delta: {\n type: \"block-delta\" as const,\n fields: {\n type: \"audio\",\n transcript: acc.transcript,\n },\n },\n };\n }\n if (delta.audio.data) {\n acc.data = (acc.data ?? \"\") + delta.audio.data;\n yield {\n event: \"content-block-delta\" as const,\n index,\n delta: {\n type: \"data-delta\" as const,\n data: delta.audio.data,\n encoding: \"base64\" as const,\n },\n };\n }\n }\n\n if (delta.function_call) {\n yield {\n event: \"provider\" as const,\n provider,\n name: \"function_call\",\n payload: delta.function_call,\n };\n }\n\n if (choice.logprobs) {\n yield {\n event: \"provider\" as const,\n provider,\n name: \"logprobs\",\n payload: choice.logprobs,\n };\n }\n }\n\n for (const [index, acc] of blockAccumulators) {\n const finalized = finalizeContentBlock(acc as ContentBlock);\n yield {\n event: \"content-block-finish\" as const,\n index,\n content: finalized,\n };\n }\n\n yield {\n event: \"message-finish\" as const,\n reason: finishReason,\n ...(usageSnapshot ? { usage: usageSnapshot } : {}),\n ...(responseMetadata ? { responseMetadata } : {}),\n };\n}\n\nfunction getReasoningDeltaText(\n delta: OpenAICompletionsDelta\n): string | undefined {\n const reasoning = delta.reasoning_content ?? delta.reasoning;\n return typeof reasoning === \"string\" && reasoning.length > 0\n ? reasoning\n : undefined;\n}\n\nfunction buildGroqUsageSnapshot(usage: {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n}): UsageMetadata {\n return {\n input_tokens: usage.prompt_tokens ?? 0,\n output_tokens: usage.completion_tokens ?? 0,\n total_tokens: usage.total_tokens ?? 0,\n };\n}\n\nfunction mapFinishReason(reason: OpenAICompletionsFinishReason): FinishReason {\n switch (reason) {\n case \"stop\":\n return \"stop\";\n case \"length\":\n case \"max_tokens\":\n return \"length\";\n case \"tool_calls\":\n case \"function_call\":\n return \"tool_use\";\n case \"content_filter\":\n return \"content_filter\";\n default:\n return \"stop\";\n }\n}\n\nfunction buildUsageSnapshot(usage: OpenAICompletionsUsage): UsageMetadata {\n const inputTokenDetails = {\n ...(usage.prompt_tokens_details?.audio_tokens != null && {\n audio: usage.prompt_tokens_details.audio_tokens,\n }),\n ...(usage.prompt_tokens_details?.cached_tokens != null && {\n cache_read: usage.prompt_tokens_details.cached_tokens,\n }),\n };\n const outputTokenDetails = {\n ...(usage.completion_tokens_details?.audio_tokens != null && {\n audio: usage.completion_tokens_details.audio_tokens,\n }),\n ...(usage.completion_tokens_details?.reasoning_tokens != null && {\n reasoning: usage.completion_tokens_details.reasoning_tokens,\n }),\n };\n return {\n input_tokens: usage.prompt_tokens ?? 0,\n output_tokens: usage.completion_tokens ?? 0,\n total_tokens: usage.total_tokens ?? 0,\n ...(Object.keys(inputTokenDetails).length > 0 && {\n input_token_details: inputTokenDetails,\n }),\n ...(Object.keys(outputTokenDetails).length > 0 && {\n output_token_details: outputTokenDetails,\n }),\n };\n}\n\nfunction buildResponseMetadata(\n data: OpenAICompletionsStreamChunk,\n choice: OpenAICompletionsStreamChoice\n): Record<string, unknown> {\n return {\n model_provider: \"openai\",\n model_name: data.model,\n system_fingerprint: data.system_fingerprint,\n service_tier: data.service_tier,\n finish_reason: choice.finish_reason,\n ...(data.usage ? { usage: data.usage } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsGA,gBAAuB,+BACrB,QACA,UAAiD,CAAC,GACZ;CACtC,MAAM,oBAAoB,QAAQ,eAAe;CACjD,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,WAAW,QAAQ;CAEzB,MAAM,oCAAoB,IAAI,IAI5B;CACF,MA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BAAkB,CAAC,CAAC,SAAS,KAAK,EAChD,sBAAsB,mBACxB;CACF;AACF;AAEA,SAAS,sBACP,MACA,QACyB;CACzB,OAAO;EACL,gBAAgB;EAChB,YAAY,KAAK;EACjB,oBAAoB,KAAK;EACzB,cAAc,KAAK;EACnB,eAAe,OAAO;EACtB,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;CAC5C;AACF"}
|
|
1
|
+
{"version":3,"file":"openai_completions_stream.js","names":[],"sources":["../../src/language_models/openai_completions_stream.ts"],"sourcesContent":["/**\n * Converts OpenAI Chat Completions-shaped stream chunks into\n * {@link ChatModelStreamEvent}s.\n *\n * Used by `@langchain/openai` and OpenAI-compatible providers (Groq, Mistral,\n * OpenRouter, IBM watsonx, etc.) without requiring a dependency on\n * `@langchain/openai`.\n *\n * @module\n */\n\nimport { finalizeContentBlock } from \"./compat.js\";\nimport type { ChatModelStreamEvent, FinishReason } from \"./event.js\";\nimport type { ContentBlock } from \"../messages/content/index.js\";\nimport type { UsageMetadata } from \"../messages/metadata.js\";\n\nexport type OpenAICompletionsFinishReason =\n | \"stop\"\n | \"length\"\n | \"max_tokens\"\n | \"tool_calls\"\n | \"function_call\"\n | \"content_filter\"\n | null;\n\nexport interface OpenAICompletionsUsage {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n prompt_tokens_details?: {\n audio_tokens?: number;\n cached_tokens?: number;\n };\n completion_tokens_details?: {\n audio_tokens?: number;\n reasoning_tokens?: number;\n };\n}\n\nexport interface OpenAICompletionsToolCallDelta {\n index?: number;\n id?: string;\n type?: \"function\";\n function?: {\n name?: string;\n arguments?: string;\n };\n}\n\nexport interface OpenAICompletionsDelta {\n role?: string;\n content?: string | null;\n reasoning_content?: string;\n reasoning?: string;\n tool_calls?: OpenAICompletionsToolCallDelta[];\n function_call?: unknown;\n audio?: {\n id?: string;\n data?: string;\n transcript?: string;\n };\n}\n\nexport interface OpenAICompletionsStreamChoice {\n index?: number;\n finish_reason?: OpenAICompletionsFinishReason;\n logprobs?: unknown;\n delta?: OpenAICompletionsDelta;\n}\n\nexport interface OpenAICompletionsStreamChunk {\n id?: string;\n model?: string;\n service_tier?: string | null;\n system_fingerprint?: string | null;\n usage?: OpenAICompletionsUsage | null;\n x_groq?: {\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n };\n };\n choices?: OpenAICompletionsStreamChoice[];\n}\n\nexport interface ConvertOpenAICompletionsStreamOptions {\n streamUsage?: boolean;\n /** Provider id for passthrough events (default `\"openai\"`). */\n provider?: string;\n /** Optional per-chunk transform before conversion. */\n mapChunk?: (\n chunk: OpenAICompletionsStreamChunk\n ) => OpenAICompletionsStreamChunk;\n}\n\ntype BlockKey = \"text\" | \"reasoning\" | \"audio\" | `tool:${number}`;\n\n/**\n * Convert an async iterable of OpenAI Chat Completions-shaped stream chunks into\n * LangChain `ChatModelStreamEvent`s with typed deltas.\n */\nexport async function* convertOpenAICompletionsStream(\n source: AsyncIterable<OpenAICompletionsStreamChunk>,\n options: ConvertOpenAICompletionsStreamOptions = {}\n): AsyncGenerator<ChatModelStreamEvent> {\n const shouldStreamUsage = options.streamUsage ?? true;\n const provider = options.provider ?? \"openai\";\n const mapChunk = options.mapChunk;\n\n const blockAccumulators = new Map<\n number,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n Record<string, any>\n >();\n const blockKeyToIndex = new Map<BlockKey, number>();\n let nextBlockIndex = 0;\n let messageStarted = false;\n let usageSnapshot: UsageMetadata | undefined;\n let finishReason: FinishReason | undefined;\n let responseMetadata: Record<string, unknown> | undefined;\n let emittedProviderMetadata = false;\n\n const getOrCreateBlockIndex = (\n key: BlockKey,\n initial: Record<string, unknown>\n ): { index: number; isNew: boolean } => {\n const existing = blockKeyToIndex.get(key);\n if (existing !== undefined) {\n return { index: existing, isNew: false };\n }\n const index = nextBlockIndex++;\n blockKeyToIndex.set(key, index);\n blockAccumulators.set(index, { ...initial });\n return { index, isNew: true };\n };\n\n for await (let data of source) {\n if (mapChunk) {\n data = mapChunk(data);\n }\n if (!messageStarted) {\n messageStarted = true;\n yield {\n event: \"message-start\" as const,\n id: data.id,\n };\n }\n\n if (!emittedProviderMetadata && (data.model || data.service_tier)) {\n emittedProviderMetadata = true;\n yield {\n event: \"provider\" as const,\n provider,\n name: \"stream_metadata\",\n payload: {\n model: data.model,\n service_tier: data.service_tier,\n },\n };\n }\n\n if (data.usage && shouldStreamUsage) {\n usageSnapshot = buildUsageSnapshot(data.usage);\n yield { event: \"usage\" as const, usage: usageSnapshot };\n }\n\n const groqUsage = data.x_groq?.usage;\n if (groqUsage && shouldStreamUsage) {\n usageSnapshot = buildGroqUsageSnapshot(groqUsage);\n yield { event: \"usage\" as const, usage: usageSnapshot };\n }\n\n const choice = data.choices?.[0];\n if (!choice) {\n continue;\n }\n\n if (choice.finish_reason != null) {\n finishReason = mapFinishReason(choice.finish_reason);\n responseMetadata = buildResponseMetadata(data, choice);\n }\n\n const { delta } = choice;\n if (!delta) {\n continue;\n }\n\n const reasoningText = getReasoningDeltaText(delta);\n if (reasoningText) {\n const key: BlockKey = \"reasoning\";\n const { index, isNew } = getOrCreateBlockIndex(key, {\n type: \"reasoning\" as const,\n reasoning: \"\",\n });\n if (isNew) {\n yield {\n event: \"content-block-start\" as const,\n index,\n content: { type: \"reasoning\", reasoning: \"\" } as ContentBlock,\n };\n }\n const acc = blockAccumulators.get(index)!;\n acc.reasoning = (acc.reasoning ?? \"\") + reasoningText;\n yield {\n event: \"content-block-delta\" as const,\n index,\n delta: {\n type: \"reasoning-delta\" as const,\n reasoning: reasoningText,\n },\n };\n }\n\n if (delta.content) {\n const key: BlockKey = \"text\";\n const { index, isNew } = getOrCreateBlockIndex(key, {\n type: \"text\" as const,\n text: \"\",\n });\n if (isNew) {\n yield {\n event: \"content-block-start\" as const,\n index,\n content: { type: \"text\", text: \"\" } as ContentBlock,\n };\n }\n const acc = blockAccumulators.get(index)!;\n acc.text = (acc.text ?? \"\") + delta.content;\n yield {\n event: \"content-block-delta\" as const,\n index,\n delta: { type: \"text-delta\" as const, text: delta.content },\n };\n }\n\n if (Array.isArray(delta.tool_calls)) {\n for (const rawToolCall of delta.tool_calls) {\n const toolIndex = rawToolCall.index ?? 0;\n const key: BlockKey = `tool:${toolIndex}`;\n const { index, isNew } = getOrCreateBlockIndex(key, {\n type: \"tool_call_chunk\" as const,\n id: rawToolCall.id,\n name: rawToolCall.function?.name,\n args: \"\",\n index: toolIndex,\n });\n if (isNew) {\n yield {\n event: \"content-block-start\" as const,\n index,\n content: {\n type: \"tool_call_chunk\",\n id: rawToolCall.id,\n name: rawToolCall.function?.name,\n args: \"\",\n index: toolIndex,\n } as ContentBlock,\n };\n }\n\n // Accumulate the full call for content-block-finish, and emit only\n // this chunk's args. A late id or name reaches consumers on finish.\n const acc = blockAccumulators.get(index)!;\n if (rawToolCall.id != null) acc.id = rawToolCall.id;\n if (rawToolCall.function?.name != null) {\n acc.name = rawToolCall.function.name;\n }\n const argDelta = rawToolCall.function?.arguments;\n if (argDelta) {\n acc.args = (acc.args ?? \"\") + argDelta;\n yield {\n event: \"content-block-delta\" as const,\n index,\n delta: { type: \"tool-call-delta\" as const, args: argDelta },\n };\n }\n }\n }\n\n if (delta.audio) {\n const key: BlockKey = \"audio\";\n const { index, isNew } = getOrCreateBlockIndex(key, {\n type: \"audio\" as const,\n id: delta.audio.id,\n data: \"\",\n mimeType: \"audio/pcm\",\n transcript: delta.audio.transcript ?? \"\",\n });\n if (isNew) {\n yield {\n event: \"content-block-start\" as const,\n index,\n content: {\n type: \"audio\",\n id: delta.audio.id,\n data: \"\",\n mimeType: \"audio/pcm\",\n transcript: delta.audio.transcript ?? \"\",\n } as ContentBlock,\n };\n }\n const acc = blockAccumulators.get(index)!;\n if (delta.audio.transcript) {\n acc.transcript = (acc.transcript ?? \"\") + delta.audio.transcript;\n yield {\n event: \"content-block-delta\" as const,\n index,\n delta: {\n type: \"block-delta\" as const,\n fields: {\n type: \"audio\",\n transcript: acc.transcript,\n },\n },\n };\n }\n if (delta.audio.data) {\n acc.data = (acc.data ?? \"\") + delta.audio.data;\n yield {\n event: \"content-block-delta\" as const,\n index,\n delta: {\n type: \"data-delta\" as const,\n data: delta.audio.data,\n encoding: \"base64\" as const,\n },\n };\n }\n }\n\n if (delta.function_call) {\n yield {\n event: \"provider\" as const,\n provider,\n name: \"function_call\",\n payload: delta.function_call,\n };\n }\n\n if (choice.logprobs) {\n yield {\n event: \"provider\" as const,\n provider,\n name: \"logprobs\",\n payload: choice.logprobs,\n };\n }\n }\n\n for (const [index, acc] of blockAccumulators) {\n const finalized = finalizeContentBlock(acc as ContentBlock);\n yield {\n event: \"content-block-finish\" as const,\n index,\n content: finalized,\n };\n }\n\n yield {\n event: \"message-finish\" as const,\n reason: finishReason,\n ...(usageSnapshot ? { usage: usageSnapshot } : {}),\n ...(responseMetadata ? { responseMetadata } : {}),\n };\n}\n\nfunction getReasoningDeltaText(\n delta: OpenAICompletionsDelta\n): string | undefined {\n const reasoning = delta.reasoning_content ?? delta.reasoning;\n return typeof reasoning === \"string\" && reasoning.length > 0\n ? reasoning\n : undefined;\n}\n\nfunction buildGroqUsageSnapshot(usage: {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n}): UsageMetadata {\n return {\n input_tokens: usage.prompt_tokens ?? 0,\n output_tokens: usage.completion_tokens ?? 0,\n total_tokens: usage.total_tokens ?? 0,\n };\n}\n\nfunction mapFinishReason(reason: OpenAICompletionsFinishReason): FinishReason {\n switch (reason) {\n case \"stop\":\n return \"stop\";\n case \"length\":\n case \"max_tokens\":\n return \"length\";\n case \"tool_calls\":\n case \"function_call\":\n return \"tool_use\";\n case \"content_filter\":\n return \"content_filter\";\n default:\n return \"stop\";\n }\n}\n\nfunction buildUsageSnapshot(usage: OpenAICompletionsUsage): UsageMetadata {\n const inputTokenDetails = {\n ...(usage.prompt_tokens_details?.audio_tokens != null && {\n audio: usage.prompt_tokens_details.audio_tokens,\n }),\n ...(usage.prompt_tokens_details?.cached_tokens != null && {\n cache_read: usage.prompt_tokens_details.cached_tokens,\n }),\n };\n const outputTokenDetails = {\n ...(usage.completion_tokens_details?.audio_tokens != null && {\n audio: usage.completion_tokens_details.audio_tokens,\n }),\n ...(usage.completion_tokens_details?.reasoning_tokens != null && {\n reasoning: usage.completion_tokens_details.reasoning_tokens,\n }),\n };\n return {\n input_tokens: usage.prompt_tokens ?? 0,\n output_tokens: usage.completion_tokens ?? 0,\n total_tokens: usage.total_tokens ?? 0,\n ...(Object.keys(inputTokenDetails).length > 0 && {\n input_token_details: inputTokenDetails,\n }),\n ...(Object.keys(outputTokenDetails).length > 0 && {\n output_token_details: outputTokenDetails,\n }),\n };\n}\n\nfunction buildResponseMetadata(\n data: OpenAICompletionsStreamChunk,\n choice: OpenAICompletionsStreamChoice\n): Record<string, unknown> {\n return {\n model_provider: \"openai\",\n model_name: data.model,\n system_fingerprint: data.system_fingerprint,\n service_tier: data.service_tier,\n finish_reason: choice.finish_reason,\n ...(data.usage ? { usage: data.usage } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsGA,gBAAuB,+BACrB,QACA,UAAiD,CAAC,GACZ;CACtC,MAAM,oBAAoB,QAAQ,eAAe;CACjD,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,WAAW,QAAQ;CAEzB,MAAM,oCAAoB,IAAI,IAI5B;CACF,MAAM,kCAAkB,IAAI,IAAsB;CAClD,IAAI,iBAAiB;CACrB,IAAI,iBAAiB;CACrB,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,0BAA0B;CAE9B,MAAM,yBACJ,KACA,YACsC;EACtC,MAAM,WAAW,gBAAgB,IAAI,GAAG;EACxC,IAAI,aAAa,KAAA,GACf,OAAO;GAAE,OAAO;GAAU,OAAO;EAAM;EAEzC,MAAM,QAAQ;EACd,gBAAgB,IAAI,KAAK,KAAK;EAC9B,kBAAkB,IAAI,OAAO,EAAE,GAAG,QAAQ,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;CAC5E,QAAQ,QAAR;EACE,KAAK,QACH,OAAO;EACT,KAAK;EACL,KAAK,cACH,OAAO;EACT,KAAK;EACL,KAAK,iBACH,OAAO;EACT,KAAK,kBACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAEA,SAAS,mBAAmB,OAA8C;CACxE,MAAM,oBAAoB;EACxB,GAAI,MAAM,uBAAuB,gBAAgB,QAAQ,EACvD,OAAO,MAAM,sBAAsB,aACrC;EACA,GAAI,MAAM,uBAAuB,iBAAiB,QAAQ,EACxD,YAAY,MAAM,sBAAsB,cAC1C;CACF;CACA,MAAM,qBAAqB;EACzB,GAAI,MAAM,2BAA2B,gBAAgB,QAAQ,EAC3D,OAAO,MAAM,0BAA0B,aACzC;EACA,GAAI,MAAM,2BAA2B,oBAAoB,QAAQ,EAC/D,WAAW,MAAM,0BAA0B,iBAC7C;CACF;CACA,OAAO;EACL,cAAc,MAAM,iBAAiB;EACrC,eAAe,MAAM,qBAAqB;EAC1C,cAAc,MAAM,gBAAgB;EACpC,GAAI,OAAO,KAAK,iBAAiB,CAAC,CAAC,SAAS,KAAK,EAC/C,qBAAqB,kBACvB;EACA,GAAI,OAAO,KAAK,kBAAkB,CAAC,CAAC,SAAS,KAAK,EAChD,sBAAsB,mBACxB;CACF;AACF;AAEA,SAAS,sBACP,MACA,QACyB;CACzB,OAAO;EACL,gBAAgB;EAChB,YAAY,KAAK;EACjB,oBAAoB,KAAK;EACzB,cAAc,KAAK;EACnB,eAAe,OAAO;EACtB,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;CAC5C;AACF"}
|
package/dist/runnables/graph.cjs
CHANGED
|
@@ -48,7 +48,8 @@ var Graph = class Graph {
|
|
|
48
48
|
return {
|
|
49
49
|
nodes: Object.values(this.nodes).map((node) => ({
|
|
50
50
|
id: stableNodeIds[node.id],
|
|
51
|
-
...nodeDataJson(node)
|
|
51
|
+
...nodeDataJson(node),
|
|
52
|
+
...node.metadata != null ? { metadata: node.metadata } : {}
|
|
52
53
|
})),
|
|
53
54
|
edges: this.edges.map((edge) => {
|
|
54
55
|
const item = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.cjs","names":["isUuid","isRunnableInterface","toJsonSchema","uuidv4","drawMermaid","drawMermaidImage"],"sources":["../../src/runnables/graph.ts"],"sourcesContent":["import { v4 as uuidv4, validate as isUuid } from \"../utils/uuid/index.js\";\nimport type {\n RunnableInterface,\n RunnableIOSchema,\n Node,\n Edge,\n} from \"./types.js\";\nimport { isRunnableInterface } from \"./utils.js\";\nimport { drawMermaid, drawMermaidImage } from \"./graph_mermaid.js\";\nimport { toJsonSchema } from \"../utils/json_schema.js\";\n\nexport { Node, Edge };\n\nfunction nodeDataStr(\n id: string | undefined,\n data: RunnableInterface | RunnableIOSchema\n): string {\n if (id !== undefined && !isUuid(id)) {\n return id;\n } else if (isRunnableInterface(data)) {\n try {\n let dataStr = data.getName();\n dataStr = dataStr.startsWith(\"Runnable\")\n ? dataStr.slice(\"Runnable\".length)\n : dataStr;\n return dataStr;\n } catch {\n return data.getName();\n }\n } else {\n return data.name ?? \"UnknownSchema\";\n }\n}\n\nfunction nodeDataJson(node: Node) {\n // if node.data implements Runnable\n if (isRunnableInterface(node.data)) {\n return {\n type: \"runnable\",\n data: {\n id: node.data.lc_id,\n name: node.data.getName(),\n },\n };\n } else {\n return {\n type: \"schema\",\n data: { ...toJsonSchema(node.data.schema), title: node.data.name },\n };\n }\n}\n\nexport class Graph {\n nodes: Record<string, Node> = {};\n\n edges: Edge[] = [];\n\n constructor(params?: { nodes: Record<string, Node>; edges: Edge[] }) {\n this.nodes = params?.nodes ?? this.nodes;\n this.edges = params?.edges ?? this.edges;\n }\n\n // Convert the graph to a JSON-serializable format.\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(): Record<string, any> {\n const stableNodeIds: Record<string, string | number> = {};\n Object.values(this.nodes).forEach((node, i) => {\n stableNodeIds[node.id] = isUuid(node.id) ? i : node.id;\n });\n\n return {\n nodes: Object.values(this.nodes).map((node) => ({\n id: stableNodeIds[node.id],\n ...nodeDataJson(node),\n })),\n edges: this.edges.map((edge) => {\n const item: Record<string, unknown> = {\n source: stableNodeIds[edge.source],\n target: stableNodeIds[edge.target],\n };\n\n if (typeof edge.data !== \"undefined\") {\n item.data = edge.data;\n }\n\n if (typeof edge.conditional !== \"undefined\") {\n item.conditional = edge.conditional;\n }\n return item;\n }),\n };\n }\n\n addNode(\n data: RunnableInterface | RunnableIOSchema,\n id?: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n metadata?: Record<string, any>\n ): Node {\n if (id !== undefined && this.nodes[id] !== undefined) {\n throw new Error(`Node with id ${id} already exists`);\n }\n const nodeId = id ?? uuidv4();\n const node: Node = {\n id: nodeId,\n data,\n name: nodeDataStr(id, data),\n metadata,\n };\n this.nodes[nodeId] = node;\n return node;\n }\n\n removeNode(node: Node): void {\n // Remove the node from the nodes map\n delete this.nodes[node.id];\n\n // Filter out edges connected to the node\n this.edges = this.edges.filter(\n (edge) => edge.source !== node.id && edge.target !== node.id\n );\n }\n\n addEdge(\n source: Node,\n target: Node,\n data?: string,\n conditional?: boolean\n ): Edge {\n if (this.nodes[source.id] === undefined) {\n throw new Error(`Source node ${source.id} not in graph`);\n }\n if (this.nodes[target.id] === undefined) {\n throw new Error(`Target node ${target.id} not in graph`);\n }\n const edge: Edge = {\n source: source.id,\n target: target.id,\n data,\n conditional,\n };\n this.edges.push(edge);\n return edge;\n }\n\n firstNode(): Node | undefined {\n return _firstNode(this);\n }\n\n lastNode(): Node | undefined {\n return _lastNode(this);\n }\n\n /**\n * Add all nodes and edges from another graph.\n * Note this doesn't check for duplicates, nor does it connect the graphs.\n */\n extend(graph: Graph, prefix = \"\") {\n let finalPrefix = prefix;\n const nodeIds = Object.values(graph.nodes).map((node) => node.id);\n if (nodeIds.every(isUuid)) {\n finalPrefix = \"\";\n }\n\n const prefixed = (id: string) => {\n return finalPrefix ? `${finalPrefix}:${id}` : id;\n };\n\n Object.entries(graph.nodes).forEach(([key, value]) => {\n this.nodes[prefixed(key)] = { ...value, id: prefixed(key) };\n });\n\n const newEdges = graph.edges.map((edge) => {\n return {\n ...edge,\n source: prefixed(edge.source),\n target: prefixed(edge.target),\n };\n });\n // Add all edges from the other graph\n this.edges = [...this.edges, ...newEdges];\n const first = graph.firstNode();\n const last = graph.lastNode();\n return [\n first ? { id: prefixed(first.id), data: first.data } : undefined,\n last ? { id: prefixed(last.id), data: last.data } : undefined,\n ];\n }\n\n trimFirstNode(): void {\n const firstNode = this.firstNode();\n if (firstNode && _firstNode(this, [firstNode.id])) {\n this.removeNode(firstNode);\n }\n }\n\n trimLastNode(): void {\n const lastNode = this.lastNode();\n if (lastNode && _lastNode(this, [lastNode.id])) {\n this.removeNode(lastNode);\n }\n }\n\n /**\n * Return a new graph with all nodes re-identified,\n * using their unique, readable names where possible.\n */\n reid(): Graph {\n const nodeLabels: Record<string, string> = Object.fromEntries(\n Object.values(this.nodes).map((node) => [node.id, node.name])\n );\n const nodeLabelCounts = new Map<string, number>();\n Object.values(nodeLabels).forEach((label) => {\n nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1);\n });\n\n const getNodeId = (nodeId: string): string => {\n const label = nodeLabels[nodeId];\n if (isUuid(nodeId) && nodeLabelCounts.get(label) === 1) {\n return label;\n } else {\n return nodeId;\n }\n };\n\n return new Graph({\n nodes: Object.fromEntries(\n Object.entries(this.nodes).map(([id, node]) => [\n getNodeId(id),\n { ...node, id: getNodeId(id) },\n ])\n ),\n edges: this.edges.map((edge) => ({\n ...edge,\n source: getNodeId(edge.source),\n target: getNodeId(edge.target),\n })),\n });\n }\n\n drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }): string {\n const {\n withStyles,\n curveStyle,\n nodeColors = {\n default: \"fill:#f2f0ff,line-height:1.2\",\n first: \"fill-opacity:0\",\n last: \"fill:#bfb6fc\",\n },\n wrapLabelNWords,\n } = params ?? {};\n const graph = this.reid();\n const firstNode = graph.firstNode();\n\n const lastNode = graph.lastNode();\n\n return drawMermaid(graph.nodes, graph.edges, {\n firstNode: firstNode?.id,\n lastNode: lastNode?.id,\n withStyles,\n curveStyle,\n nodeColors,\n wrapLabelNWords,\n });\n }\n\n async drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }): Promise<Blob> {\n const mermaidSyntax = this.drawMermaid(params);\n return drawMermaidImage(mermaidSyntax, {\n backgroundColor: params?.backgroundColor,\n });\n }\n}\n/**\n * Find the single node that is not a target of any edge.\n * Exclude nodes/sources with ids in the exclude list.\n * If there is no such node, or there are multiple, return undefined.\n * When drawing the graph, this node would be the origin.\n */\nfunction _firstNode(graph: Graph, exclude: string[] = []): Node | undefined {\n const targets = new Set(\n graph.edges\n .filter((edge) => !exclude.includes(edge.source))\n .map((edge) => edge.target)\n );\n\n const found: Node[] = [];\n for (const node of Object.values(graph.nodes)) {\n if (!exclude.includes(node.id) && !targets.has(node.id)) {\n found.push(node);\n }\n }\n return found.length === 1 ? found[0] : undefined;\n}\n\n/**\n * Find the single node that is not a source of any edge.\n * Exclude nodes/targets with ids in the exclude list.\n * If there is no such node, or there are multiple, return undefined.\n * When drawing the graph, this node would be the destination.\n */\nfunction _lastNode(graph: Graph, exclude: string[] = []): Node | undefined {\n const sources = new Set(\n graph.edges\n .filter((edge) => !exclude.includes(edge.target))\n .map((edge) => edge.source)\n );\n\n const found: Node[] = [];\n for (const node of Object.values(graph.nodes)) {\n if (!exclude.includes(node.id) && !sources.has(node.id)) {\n found.push(node);\n }\n }\n return found.length === 1 ? found[0] : undefined;\n}\n"],"mappings":";;;;;;;;AAaA,SAAS,YACP,IACA,MACQ;CACR,IAAI,OAAO,KAAA,KAAa,CAACA,yBAAAA,SAAO,EAAE,GAChC,OAAO;MACF,IAAIC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c,UAAoB,CAAC,GAAqB;CACzE,MAAM,UAAU,IAAI,IAClB,MAAM,MACH,QAAQ,SAAS,CAAC,QAAQ,SAAS,KAAK,MAAM,CAAC,CAAC,CAChD,KAAK,SAAS,KAAK,MAAM,CAC9B;CAEA,MAAM,QAAgB,CAAC;CACvB,KAAK,MAAM,QAAQ,OAAO,OAAO,MAAM,KAAK,GAC1C,IAAI,CAAC,QAAQ,SAAS,KAAK,EAAE,KAAK,CAAC,QAAQ,IAAI,KAAK,EAAE,GACpD,MAAM,KAAK,IAAI;CAGnB,OAAO,MAAM,WAAW,IAAI,MAAM,KAAK,KAAA;AACzC"}
|
|
1
|
+
{"version":3,"file":"graph.cjs","names":["isUuid","isRunnableInterface","toJsonSchema","uuidv4","drawMermaid","drawMermaidImage"],"sources":["../../src/runnables/graph.ts"],"sourcesContent":["import { v4 as uuidv4, validate as isUuid } from \"../utils/uuid/index.js\";\nimport type {\n RunnableInterface,\n RunnableIOSchema,\n Node,\n Edge,\n} from \"./types.js\";\nimport { isRunnableInterface } from \"./utils.js\";\nimport { drawMermaid, drawMermaidImage } from \"./graph_mermaid.js\";\nimport { toJsonSchema } from \"../utils/json_schema.js\";\n\nexport { Node, Edge };\n\nfunction nodeDataStr(\n id: string | undefined,\n data: RunnableInterface | RunnableIOSchema\n): string {\n if (id !== undefined && !isUuid(id)) {\n return id;\n } else if (isRunnableInterface(data)) {\n try {\n let dataStr = data.getName();\n dataStr = dataStr.startsWith(\"Runnable\")\n ? dataStr.slice(\"Runnable\".length)\n : dataStr;\n return dataStr;\n } catch {\n return data.getName();\n }\n } else {\n return data.name ?? \"UnknownSchema\";\n }\n}\n\nfunction nodeDataJson(node: Node) {\n // if node.data implements Runnable\n if (isRunnableInterface(node.data)) {\n return {\n type: \"runnable\",\n data: {\n id: node.data.lc_id,\n name: node.data.getName(),\n },\n };\n } else {\n return {\n type: \"schema\",\n data: { ...toJsonSchema(node.data.schema), title: node.data.name },\n };\n }\n}\n\nexport class Graph {\n nodes: Record<string, Node> = {};\n\n edges: Edge[] = [];\n\n constructor(params?: { nodes: Record<string, Node>; edges: Edge[] }) {\n this.nodes = params?.nodes ?? this.nodes;\n this.edges = params?.edges ?? this.edges;\n }\n\n // Convert the graph to a JSON-serializable format.\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(): Record<string, any> {\n const stableNodeIds: Record<string, string | number> = {};\n Object.values(this.nodes).forEach((node, i) => {\n stableNodeIds[node.id] = isUuid(node.id) ? i : node.id;\n });\n\n return {\n nodes: Object.values(this.nodes).map((node) => ({\n id: stableNodeIds[node.id],\n ...nodeDataJson(node),\n ...(node.metadata != null ? { metadata: node.metadata } : {}),\n })),\n edges: this.edges.map((edge) => {\n const item: Record<string, unknown> = {\n source: stableNodeIds[edge.source],\n target: stableNodeIds[edge.target],\n };\n\n if (typeof edge.data !== \"undefined\") {\n item.data = edge.data;\n }\n\n if (typeof edge.conditional !== \"undefined\") {\n item.conditional = edge.conditional;\n }\n return item;\n }),\n };\n }\n\n addNode(\n data: RunnableInterface | RunnableIOSchema,\n id?: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n metadata?: Record<string, any>\n ): Node {\n if (id !== undefined && this.nodes[id] !== undefined) {\n throw new Error(`Node with id ${id} already exists`);\n }\n const nodeId = id ?? uuidv4();\n const node: Node = {\n id: nodeId,\n data,\n name: nodeDataStr(id, data),\n metadata,\n };\n this.nodes[nodeId] = node;\n return node;\n }\n\n removeNode(node: Node): void {\n // Remove the node from the nodes map\n delete this.nodes[node.id];\n\n // Filter out edges connected to the node\n this.edges = this.edges.filter(\n (edge) => edge.source !== node.id && edge.target !== node.id\n );\n }\n\n addEdge(\n source: Node,\n target: Node,\n data?: string,\n conditional?: boolean\n ): Edge {\n if (this.nodes[source.id] === undefined) {\n throw new Error(`Source node ${source.id} not in graph`);\n }\n if (this.nodes[target.id] === undefined) {\n throw new Error(`Target node ${target.id} not in graph`);\n }\n const edge: Edge = {\n source: source.id,\n target: target.id,\n data,\n conditional,\n };\n this.edges.push(edge);\n return edge;\n }\n\n firstNode(): Node | undefined {\n return _firstNode(this);\n }\n\n lastNode(): Node | undefined {\n return _lastNode(this);\n }\n\n /**\n * Add all nodes and edges from another graph.\n * Note this doesn't check for duplicates, nor does it connect the graphs.\n */\n extend(graph: Graph, prefix = \"\") {\n let finalPrefix = prefix;\n const nodeIds = Object.values(graph.nodes).map((node) => node.id);\n if (nodeIds.every(isUuid)) {\n finalPrefix = \"\";\n }\n\n const prefixed = (id: string) => {\n return finalPrefix ? `${finalPrefix}:${id}` : id;\n };\n\n Object.entries(graph.nodes).forEach(([key, value]) => {\n this.nodes[prefixed(key)] = { ...value, id: prefixed(key) };\n });\n\n const newEdges = graph.edges.map((edge) => {\n return {\n ...edge,\n source: prefixed(edge.source),\n target: prefixed(edge.target),\n };\n });\n // Add all edges from the other graph\n this.edges = [...this.edges, ...newEdges];\n const first = graph.firstNode();\n const last = graph.lastNode();\n return [\n first ? { id: prefixed(first.id), data: first.data } : undefined,\n last ? { id: prefixed(last.id), data: last.data } : undefined,\n ];\n }\n\n trimFirstNode(): void {\n const firstNode = this.firstNode();\n if (firstNode && _firstNode(this, [firstNode.id])) {\n this.removeNode(firstNode);\n }\n }\n\n trimLastNode(): void {\n const lastNode = this.lastNode();\n if (lastNode && _lastNode(this, [lastNode.id])) {\n this.removeNode(lastNode);\n }\n }\n\n /**\n * Return a new graph with all nodes re-identified,\n * using their unique, readable names where possible.\n */\n reid(): Graph {\n const nodeLabels: Record<string, string> = Object.fromEntries(\n Object.values(this.nodes).map((node) => [node.id, node.name])\n );\n const nodeLabelCounts = new Map<string, number>();\n Object.values(nodeLabels).forEach((label) => {\n nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1);\n });\n\n const getNodeId = (nodeId: string): string => {\n const label = nodeLabels[nodeId];\n if (isUuid(nodeId) && nodeLabelCounts.get(label) === 1) {\n return label;\n } else {\n return nodeId;\n }\n };\n\n return new Graph({\n nodes: Object.fromEntries(\n Object.entries(this.nodes).map(([id, node]) => [\n getNodeId(id),\n { ...node, id: getNodeId(id) },\n ])\n ),\n edges: this.edges.map((edge) => ({\n ...edge,\n source: getNodeId(edge.source),\n target: getNodeId(edge.target),\n })),\n });\n }\n\n drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }): string {\n const {\n withStyles,\n curveStyle,\n nodeColors = {\n default: \"fill:#f2f0ff,line-height:1.2\",\n first: \"fill-opacity:0\",\n last: \"fill:#bfb6fc\",\n },\n wrapLabelNWords,\n } = params ?? {};\n const graph = this.reid();\n const firstNode = graph.firstNode();\n\n const lastNode = graph.lastNode();\n\n return drawMermaid(graph.nodes, graph.edges, {\n firstNode: firstNode?.id,\n lastNode: lastNode?.id,\n withStyles,\n curveStyle,\n nodeColors,\n wrapLabelNWords,\n });\n }\n\n async drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }): Promise<Blob> {\n const mermaidSyntax = this.drawMermaid(params);\n return drawMermaidImage(mermaidSyntax, {\n backgroundColor: params?.backgroundColor,\n });\n }\n}\n/**\n * Find the single node that is not a target of any edge.\n * Exclude nodes/sources with ids in the exclude list.\n * If there is no such node, or there are multiple, return undefined.\n * When drawing the graph, this node would be the origin.\n */\nfunction _firstNode(graph: Graph, exclude: string[] = []): Node | undefined {\n const targets = new Set(\n graph.edges\n .filter((edge) => !exclude.includes(edge.source))\n .map((edge) => edge.target)\n );\n\n const found: Node[] = [];\n for (const node of Object.values(graph.nodes)) {\n if (!exclude.includes(node.id) && !targets.has(node.id)) {\n found.push(node);\n }\n }\n return found.length === 1 ? found[0] : undefined;\n}\n\n/**\n * Find the single node that is not a source of any edge.\n * Exclude nodes/targets with ids in the exclude list.\n * If there is no such node, or there are multiple, return undefined.\n * When drawing the graph, this node would be the destination.\n */\nfunction _lastNode(graph: Graph, exclude: string[] = []): Node | undefined {\n const sources = new Set(\n graph.edges\n .filter((edge) => !exclude.includes(edge.target))\n .map((edge) => edge.source)\n );\n\n const found: Node[] = [];\n for (const node of Object.values(graph.nodes)) {\n if (!exclude.includes(node.id) && !sources.has(node.id)) {\n found.push(node);\n }\n }\n return found.length === 1 ? found[0] : undefined;\n}\n"],"mappings":";;;;;;;;AAaA,SAAS,YACP,IACA,MACQ;CACR,IAAI,OAAO,KAAA,KAAa,CAACA,yBAAAA,SAAO,EAAE,GAChC,OAAO;MACF,IAAIC,cAAAA,oBAAoB,IAAI,GACjC,IAAI;EACF,IAAI,UAAU,KAAK,QAAQ;EAC3B,UAAU,QAAQ,WAAW,UAAU,IACnC,QAAQ,MAAM,CAAiB,IAC/B;EACJ,OAAO;CACT,QAAQ;EACN,OAAO,KAAK,QAAQ;CACtB;MAEA,OAAO,KAAK,QAAQ;AAExB;AAEA,SAAS,aAAa,MAAY;CAEhC,IAAIA,cAAAA,oBAAoB,KAAK,IAAI,GAC/B,OAAO;EACL,MAAM;EACN,MAAM;GACJ,IAAI,KAAK,KAAK;GACd,MAAM,KAAK,KAAK,QAAQ;EAC1B;CACF;MAEA,OAAO;EACL,MAAM;EACN,MAAM;GAAE,GAAGC,0BAAAA,aAAa,KAAK,KAAK,MAAM;GAAG,OAAO,KAAK,KAAK;EAAK;CACnE;AAEJ;AAEA,IAAa,QAAb,MAAa,MAAM;CACjB,QAA8B,CAAC;CAE/B,QAAgB,CAAC;CAEjB,YAAY,QAAyD;EACnE,KAAK,QAAQ,QAAQ,SAAS,KAAK;EACnC,KAAK,QAAQ,QAAQ,SAAS,KAAK;CACrC;CAIA,SAA8B;EAC5B,MAAM,gBAAiD,CAAC;EACxD,OAAO,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,MAAM,MAAM;GAC7C,cAAc,KAAK,MAAMF,yBAAAA,SAAO,KAAK,EAAE,IAAI,IAAI,KAAK;EACtD,CAAC;EAED,OAAO;GACL,OAAO,OAAO,OAAO,KA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AC1E,MAAM,UAAU,IAAI,IAClB,MAAM,MACH,QAAQ,SAAS,CAAC,QAAQ,SAAS,KAAK,MAAM,CAAC,CAAC,CAChD,KAAK,SAAS,KAAK,MAAM,CAC9B;CAEA,MAAM,QAAgB,CAAC;CACvB,KAAK,MAAM,QAAQ,OAAO,OAAO,MAAM,KAAK,GAC1C,IAAI,CAAC,QAAQ,SAAS,KAAK,EAAE,KAAK,CAAC,QAAQ,IAAI,KAAK,EAAE,GACpD,MAAM,KAAK,IAAI;CAGnB,OAAO,MAAM,WAAW,IAAI,MAAM,KAAK,KAAA;AACzC;;;;;;;AAQA,SAAS,UAAU,OAAc,UAAoB,CAAC,GAAqB;CACzE,MAAM,UAAU,IAAI,IAClB,MAAM,MACH,QAAQ,SAAS,CAAC,QAAQ,SAAS,KAAK,MAAM,CAAC,CAAC,CAChD,KAAK,SAAS,KAAK,MAAM,CAC9B;CAEA,MAAM,QAAgB,CAAC;CACvB,KAAK,MAAM,QAAQ,OAAO,OAAO,MAAM,KAAK,GAC1C,IAAI,CAAC,QAAQ,SAAS,KAAK,EAAE,KAAK,CAAC,QAAQ,IAAI,KAAK,EAAE,GACpD,MAAM,KAAK,IAAI;CAGnB,OAAO,MAAM,WAAW,IAAI,MAAM,KAAK,KAAA;AACzC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.d.cts","names":["_$__types_js0.RunnableConfig"],"sources":["../../src/runnables/graph.ts"],"mappings":";;qBAoDa;EACX,OAAO,eAAe;EAEtB,OAAO;EAEP,YAAY;IAAW,OAAO,eAAe;IAAO,OAAO;;EAO3D,UAAU;
|
|
1
|
+
{"version":3,"file":"graph.d.cts","names":["_$__types_js0.RunnableConfig"],"sources":["../../src/runnables/graph.ts"],"mappings":";;qBAoDa;EACX,OAAO,eAAe;EAEtB,OAAO;EAEP,YAAY;IAAW,OAAO,eAAe;IAAO,OAAO;;EAO3D,UAAU;EA8BV,QACE,MAAM,oBAAoB,kBAC1B,aAEA,WAAW,sBACV;EAeH,WAAW,MAAM;EAUjB,QACE,QAAQ,MACR,QAAQ,MACR,eACA,wBACC;EAiBH,aAAa;EAIb,YAAY;;;;;EAQZ,OAAO,OAAO,OAAO;;;;EAgCrB;EAOA;;;;;EAWA,QAAQ;EAiCR,YAAY;IACV;IACA;IACA,aAAa;IACb;;EA2BI,eAAe;IACnB;IACA;IACA,aAAa;IACb;IACA;MACE,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.d.ts","names":["_$__types_js0.RunnableConfig"],"sources":["../../src/runnables/graph.ts"],"mappings":";;qBAoDa;EACX,OAAO,eAAe;EAEtB,OAAO;EAEP,YAAY;IAAW,OAAO,eAAe;IAAO,OAAO;;EAO3D,UAAU;
|
|
1
|
+
{"version":3,"file":"graph.d.ts","names":["_$__types_js0.RunnableConfig"],"sources":["../../src/runnables/graph.ts"],"mappings":";;qBAoDa;EACX,OAAO,eAAe;EAEtB,OAAO;EAEP,YAAY;IAAW,OAAO,eAAe;IAAO,OAAO;;EAO3D,UAAU;EA8BV,QACE,MAAM,oBAAoB,kBAC1B,aAEA,WAAW,sBACV;EAeH,WAAW,MAAM;EAUjB,QACE,QAAQ,MACR,QAAQ,MACR,eACA,wBACC;EAiBH,aAAa;EAIb,YAAY;;;;;EAQZ,OAAO,OAAO,OAAO;;;;EAgCrB;EAOA;;;;;EAWA,QAAQ;EAiCR,YAAY;IACV;IACA;IACA,aAAa;IACb;;EA2BI,eAAe;IACnB;IACA;IACA,aAAa;IACb;IACA;MACE,QAAQ"}
|
package/dist/runnables/graph.js
CHANGED
|
@@ -47,7 +47,8 @@ var Graph = class Graph {
|
|
|
47
47
|
return {
|
|
48
48
|
nodes: Object.values(this.nodes).map((node) => ({
|
|
49
49
|
id: stableNodeIds[node.id],
|
|
50
|
-
...nodeDataJson(node)
|
|
50
|
+
...nodeDataJson(node),
|
|
51
|
+
...node.metadata != null ? { metadata: node.metadata } : {}
|
|
51
52
|
})),
|
|
52
53
|
edges: this.edges.map((edge) => {
|
|
53
54
|
const item = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.js","names":["isUuid","uuidv4"],"sources":["../../src/runnables/graph.ts"],"sourcesContent":["import { v4 as uuidv4, validate as isUuid } from \"../utils/uuid/index.js\";\nimport type {\n RunnableInterface,\n RunnableIOSchema,\n Node,\n Edge,\n} from \"./types.js\";\nimport { isRunnableInterface } from \"./utils.js\";\nimport { drawMermaid, drawMermaidImage } from \"./graph_mermaid.js\";\nimport { toJsonSchema } from \"../utils/json_schema.js\";\n\nexport { Node, Edge };\n\nfunction nodeDataStr(\n id: string | undefined,\n data: RunnableInterface | RunnableIOSchema\n): string {\n if (id !== undefined && !isUuid(id)) {\n return id;\n } else if (isRunnableInterface(data)) {\n try {\n let dataStr = data.getName();\n dataStr = dataStr.startsWith(\"Runnable\")\n ? dataStr.slice(\"Runnable\".length)\n : dataStr;\n return dataStr;\n } catch {\n return data.getName();\n }\n } else {\n return data.name ?? \"UnknownSchema\";\n }\n}\n\nfunction nodeDataJson(node: Node) {\n // if node.data implements Runnable\n if (isRunnableInterface(node.data)) {\n return {\n type: \"runnable\",\n data: {\n id: node.data.lc_id,\n name: node.data.getName(),\n },\n };\n } else {\n return {\n type: \"schema\",\n data: { ...toJsonSchema(node.data.schema), title: node.data.name },\n };\n }\n}\n\nexport class Graph {\n nodes: Record<string, Node> = {};\n\n edges: Edge[] = [];\n\n constructor(params?: { nodes: Record<string, Node>; edges: Edge[] }) {\n this.nodes = params?.nodes ?? this.nodes;\n this.edges = params?.edges ?? this.edges;\n }\n\n // Convert the graph to a JSON-serializable format.\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(): Record<string, any> {\n const stableNodeIds: Record<string, string | number> = {};\n Object.values(this.nodes).forEach((node, i) => {\n stableNodeIds[node.id] = isUuid(node.id) ? i : node.id;\n });\n\n return {\n nodes: Object.values(this.nodes).map((node) => ({\n id: stableNodeIds[node.id],\n ...nodeDataJson(node),\n })),\n edges: this.edges.map((edge) => {\n const item: Record<string, unknown> = {\n source: stableNodeIds[edge.source],\n target: stableNodeIds[edge.target],\n };\n\n if (typeof edge.data !== \"undefined\") {\n item.data = edge.data;\n }\n\n if (typeof edge.conditional !== \"undefined\") {\n item.conditional = edge.conditional;\n }\n return item;\n }),\n };\n }\n\n addNode(\n data: RunnableInterface | RunnableIOSchema,\n id?: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n metadata?: Record<string, any>\n ): Node {\n if (id !== undefined && this.nodes[id] !== undefined) {\n throw new Error(`Node with id ${id} already exists`);\n }\n const nodeId = id ?? uuidv4();\n const node: Node = {\n id: nodeId,\n data,\n name: nodeDataStr(id, data),\n metadata,\n };\n this.nodes[nodeId] = node;\n return node;\n }\n\n removeNode(node: Node): void {\n // Remove the node from the nodes map\n delete this.nodes[node.id];\n\n // Filter out edges connected to the node\n this.edges = this.edges.filter(\n (edge) => edge.source !== node.id && edge.target !== node.id\n );\n }\n\n addEdge(\n source: Node,\n target: Node,\n data?: string,\n conditional?: boolean\n ): Edge {\n if (this.nodes[source.id] === undefined) {\n throw new Error(`Source node ${source.id} not in graph`);\n }\n if (this.nodes[target.id] === undefined) {\n throw new Error(`Target node ${target.id} not in graph`);\n }\n const edge: Edge = {\n source: source.id,\n target: target.id,\n data,\n conditional,\n };\n this.edges.push(edge);\n return edge;\n }\n\n firstNode(): Node | undefined {\n return _firstNode(this);\n }\n\n lastNode(): Node | undefined {\n return _lastNode(this);\n }\n\n /**\n * Add all nodes and edges from another graph.\n * Note this doesn't check for duplicates, nor does it connect the graphs.\n */\n extend(graph: Graph, prefix = \"\") {\n let finalPrefix = prefix;\n const nodeIds = Object.values(graph.nodes).map((node) => node.id);\n if (nodeIds.every(isUuid)) {\n finalPrefix = \"\";\n }\n\n const prefixed = (id: string) => {\n return finalPrefix ? `${finalPrefix}:${id}` : id;\n };\n\n Object.entries(graph.nodes).forEach(([key, value]) => {\n this.nodes[prefixed(key)] = { ...value, id: prefixed(key) };\n });\n\n const newEdges = graph.edges.map((edge) => {\n return {\n ...edge,\n source: prefixed(edge.source),\n target: prefixed(edge.target),\n };\n });\n // Add all edges from the other graph\n this.edges = [...this.edges, ...newEdges];\n const first = graph.firstNode();\n const last = graph.lastNode();\n return [\n first ? { id: prefixed(first.id), data: first.data } : undefined,\n last ? { id: prefixed(last.id), data: last.data } : undefined,\n ];\n }\n\n trimFirstNode(): void {\n const firstNode = this.firstNode();\n if (firstNode && _firstNode(this, [firstNode.id])) {\n this.removeNode(firstNode);\n }\n }\n\n trimLastNode(): void {\n const lastNode = this.lastNode();\n if (lastNode && _lastNode(this, [lastNode.id])) {\n this.removeNode(lastNode);\n }\n }\n\n /**\n * Return a new graph with all nodes re-identified,\n * using their unique, readable names where possible.\n */\n reid(): Graph {\n const nodeLabels: Record<string, string> = Object.fromEntries(\n Object.values(this.nodes).map((node) => [node.id, node.name])\n );\n const nodeLabelCounts = new Map<string, number>();\n Object.values(nodeLabels).forEach((label) => {\n nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1);\n });\n\n const getNodeId = (nodeId: string): string => {\n const label = nodeLabels[nodeId];\n if (isUuid(nodeId) && nodeLabelCounts.get(label) === 1) {\n return label;\n } else {\n return nodeId;\n }\n };\n\n return new Graph({\n nodes: Object.fromEntries(\n Object.entries(this.nodes).map(([id, node]) => [\n getNodeId(id),\n { ...node, id: getNodeId(id) },\n ])\n ),\n edges: this.edges.map((edge) => ({\n ...edge,\n source: getNodeId(edge.source),\n target: getNodeId(edge.target),\n })),\n });\n }\n\n drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }): string {\n const {\n withStyles,\n curveStyle,\n nodeColors = {\n default: \"fill:#f2f0ff,line-height:1.2\",\n first: \"fill-opacity:0\",\n last: \"fill:#bfb6fc\",\n },\n wrapLabelNWords,\n } = params ?? {};\n const graph = this.reid();\n const firstNode = graph.firstNode();\n\n const lastNode = graph.lastNode();\n\n return drawMermaid(graph.nodes, graph.edges, {\n firstNode: firstNode?.id,\n lastNode: lastNode?.id,\n withStyles,\n curveStyle,\n nodeColors,\n wrapLabelNWords,\n });\n }\n\n async drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }): Promise<Blob> {\n const mermaidSyntax = this.drawMermaid(params);\n return drawMermaidImage(mermaidSyntax, {\n backgroundColor: params?.backgroundColor,\n });\n }\n}\n/**\n * Find the single node that is not a target of any edge.\n * Exclude nodes/sources with ids in the exclude list.\n * If there is no such node, or there are multiple, return undefined.\n * When drawing the graph, this node would be the origin.\n */\nfunction _firstNode(graph: Graph, exclude: string[] = []): Node | undefined {\n const targets = new Set(\n graph.edges\n .filter((edge) => !exclude.includes(edge.source))\n .map((edge) => edge.target)\n );\n\n const found: Node[] = [];\n for (const node of Object.values(graph.nodes)) {\n if (!exclude.includes(node.id) && !targets.has(node.id)) {\n found.push(node);\n }\n }\n return found.length === 1 ? found[0] : undefined;\n}\n\n/**\n * Find the single node that is not a source of any edge.\n * Exclude nodes/targets with ids in the exclude list.\n * If there is no such node, or there are multiple, return undefined.\n * When drawing the graph, this node would be the destination.\n */\nfunction _lastNode(graph: Graph, exclude: string[] = []): Node | undefined {\n const sources = new Set(\n graph.edges\n .filter((edge) => !exclude.includes(edge.target))\n .map((edge) => edge.source)\n );\n\n const found: Node[] = [];\n for (const node of Object.values(graph.nodes)) {\n if (!exclude.includes(node.id) && !sources.has(node.id)) {\n found.push(node);\n }\n }\n return found.length === 1 ? found[0] : undefined;\n}\n"],"mappings":";;;;;;;AAaA,SAAS,YACP,IACA,MACQ;CACR,IAAI,OAAO,KAAA,KAAa,CAACA,SAAO,EAAE,GAChC,OAAO;MACF,IAAI,oBAAoB,IAAI,GACjC,IAAI;EACF,IAAI,UAAU,KAAK,QAAQ;EAC3B,UAAU,QAAQ,WAAW,UA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AAM,QAAgB,CAAC;CACvB,KAAK,MAAM,QAAQ,OAAO,OAAO,MAAM,KAAK,GAC1C,IAAI,CAAC,QAAQ,SAAS,KAAK,EAAE,KAAK,CAAC,QAAQ,IAAI,KAAK,EAAE,GACpD,MAAM,KAAK,IAAI;CAGnB,OAAO,MAAM,WAAW,IAAI,MAAM,KAAK,KAAA;AACzC"}
|
|
1
|
+
{"version":3,"file":"graph.js","names":["isUuid","uuidv4"],"sources":["../../src/runnables/graph.ts"],"sourcesContent":["import { v4 as uuidv4, validate as isUuid } from \"../utils/uuid/index.js\";\nimport type {\n RunnableInterface,\n RunnableIOSchema,\n Node,\n Edge,\n} from \"./types.js\";\nimport { isRunnableInterface } from \"./utils.js\";\nimport { drawMermaid, drawMermaidImage } from \"./graph_mermaid.js\";\nimport { toJsonSchema } from \"../utils/json_schema.js\";\n\nexport { Node, Edge };\n\nfunction nodeDataStr(\n id: string | undefined,\n data: RunnableInterface | RunnableIOSchema\n): string {\n if (id !== undefined && !isUuid(id)) {\n return id;\n } else if (isRunnableInterface(data)) {\n try {\n let dataStr = data.getName();\n dataStr = dataStr.startsWith(\"Runnable\")\n ? dataStr.slice(\"Runnable\".length)\n : dataStr;\n return dataStr;\n } catch {\n return data.getName();\n }\n } else {\n return data.name ?? \"UnknownSchema\";\n }\n}\n\nfunction nodeDataJson(node: Node) {\n // if node.data implements Runnable\n if (isRunnableInterface(node.data)) {\n return {\n type: \"runnable\",\n data: {\n id: node.data.lc_id,\n name: node.data.getName(),\n },\n };\n } else {\n return {\n type: \"schema\",\n data: { ...toJsonSchema(node.data.schema), title: node.data.name },\n };\n }\n}\n\nexport class Graph {\n nodes: Record<string, Node> = {};\n\n edges: Edge[] = [];\n\n constructor(params?: { nodes: Record<string, Node>; edges: Edge[] }) {\n this.nodes = params?.nodes ?? this.nodes;\n this.edges = params?.edges ?? this.edges;\n }\n\n // Convert the graph to a JSON-serializable format.\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(): Record<string, any> {\n const stableNodeIds: Record<string, string | number> = {};\n Object.values(this.nodes).forEach((node, i) => {\n stableNodeIds[node.id] = isUuid(node.id) ? i : node.id;\n });\n\n return {\n nodes: Object.values(this.nodes).map((node) => ({\n id: stableNodeIds[node.id],\n ...nodeDataJson(node),\n ...(node.metadata != null ? { metadata: node.metadata } : {}),\n })),\n edges: this.edges.map((edge) => {\n const item: Record<string, unknown> = {\n source: stableNodeIds[edge.source],\n target: stableNodeIds[edge.target],\n };\n\n if (typeof edge.data !== \"undefined\") {\n item.data = edge.data;\n }\n\n if (typeof edge.conditional !== \"undefined\") {\n item.conditional = edge.conditional;\n }\n return item;\n }),\n };\n }\n\n addNode(\n data: RunnableInterface | RunnableIOSchema,\n id?: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n metadata?: Record<string, any>\n ): Node {\n if (id !== undefined && this.nodes[id] !== undefined) {\n throw new Error(`Node with id ${id} already exists`);\n }\n const nodeId = id ?? uuidv4();\n const node: Node = {\n id: nodeId,\n data,\n name: nodeDataStr(id, data),\n metadata,\n };\n this.nodes[nodeId] = node;\n return node;\n }\n\n removeNode(node: Node): void {\n // Remove the node from the nodes map\n delete this.nodes[node.id];\n\n // Filter out edges connected to the node\n this.edges = this.edges.filter(\n (edge) => edge.source !== node.id && edge.target !== node.id\n );\n }\n\n addEdge(\n source: Node,\n target: Node,\n data?: string,\n conditional?: boolean\n ): Edge {\n if (this.nodes[source.id] === undefined) {\n throw new Error(`Source node ${source.id} not in graph`);\n }\n if (this.nodes[target.id] === undefined) {\n throw new Error(`Target node ${target.id} not in graph`);\n }\n const edge: Edge = {\n source: source.id,\n target: target.id,\n data,\n conditional,\n };\n this.edges.push(edge);\n return edge;\n }\n\n firstNode(): Node | undefined {\n return _firstNode(this);\n }\n\n lastNode(): Node | undefined {\n return _lastNode(this);\n }\n\n /**\n * Add all nodes and edges from another graph.\n * Note this doesn't check for duplicates, nor does it connect the graphs.\n */\n extend(graph: Graph, prefix = \"\") {\n let finalPrefix = prefix;\n const nodeIds = Object.values(graph.nodes).map((node) => node.id);\n if (nodeIds.every(isUuid)) {\n finalPrefix = \"\";\n }\n\n const prefixed = (id: string) => {\n return finalPrefix ? `${finalPrefix}:${id}` : id;\n };\n\n Object.entries(graph.nodes).forEach(([key, value]) => {\n this.nodes[prefixed(key)] = { ...value, id: prefixed(key) };\n });\n\n const newEdges = graph.edges.map((edge) => {\n return {\n ...edge,\n source: prefixed(edge.source),\n target: prefixed(edge.target),\n };\n });\n // Add all edges from the other graph\n this.edges = [...this.edges, ...newEdges];\n const first = graph.firstNode();\n const last = graph.lastNode();\n return [\n first ? { id: prefixed(first.id), data: first.data } : undefined,\n last ? { id: prefixed(last.id), data: last.data } : undefined,\n ];\n }\n\n trimFirstNode(): void {\n const firstNode = this.firstNode();\n if (firstNode && _firstNode(this, [firstNode.id])) {\n this.removeNode(firstNode);\n }\n }\n\n trimLastNode(): void {\n const lastNode = this.lastNode();\n if (lastNode && _lastNode(this, [lastNode.id])) {\n this.removeNode(lastNode);\n }\n }\n\n /**\n * Return a new graph with all nodes re-identified,\n * using their unique, readable names where possible.\n */\n reid(): Graph {\n const nodeLabels: Record<string, string> = Object.fromEntries(\n Object.values(this.nodes).map((node) => [node.id, node.name])\n );\n const nodeLabelCounts = new Map<string, number>();\n Object.values(nodeLabels).forEach((label) => {\n nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1);\n });\n\n const getNodeId = (nodeId: string): string => {\n const label = nodeLabels[nodeId];\n if (isUuid(nodeId) && nodeLabelCounts.get(label) === 1) {\n return label;\n } else {\n return nodeId;\n }\n };\n\n return new Graph({\n nodes: Object.fromEntries(\n Object.entries(this.nodes).map(([id, node]) => [\n getNodeId(id),\n { ...node, id: getNodeId(id) },\n ])\n ),\n edges: this.edges.map((edge) => ({\n ...edge,\n source: getNodeId(edge.source),\n target: getNodeId(edge.target),\n })),\n });\n }\n\n drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }): string {\n const {\n withStyles,\n curveStyle,\n nodeColors = {\n default: \"fill:#f2f0ff,line-height:1.2\",\n first: \"fill-opacity:0\",\n last: \"fill:#bfb6fc\",\n },\n wrapLabelNWords,\n } = params ?? {};\n const graph = this.reid();\n const firstNode = graph.firstNode();\n\n const lastNode = graph.lastNode();\n\n return drawMermaid(graph.nodes, graph.edges, {\n firstNode: firstNode?.id,\n lastNode: lastNode?.id,\n withStyles,\n curveStyle,\n nodeColors,\n wrapLabelNWords,\n });\n }\n\n async drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }): Promise<Blob> {\n const mermaidSyntax = this.drawMermaid(params);\n return drawMermaidImage(mermaidSyntax, {\n backgroundColor: params?.backgroundColor,\n });\n }\n}\n/**\n * Find the single node that is not a target of any edge.\n * Exclude nodes/sources with ids in the exclude list.\n * If there is no such node, or there are multiple, return undefined.\n * When drawing the graph, this node would be the origin.\n */\nfunction _firstNode(graph: Graph, exclude: string[] = []): Node | undefined {\n const targets = new Set(\n graph.edges\n .filter((edge) => !exclude.includes(edge.source))\n .map((edge) => edge.target)\n );\n\n const found: Node[] = [];\n for (const node of Object.values(graph.nodes)) {\n if (!exclude.includes(node.id) && !targets.has(node.id)) {\n found.push(node);\n }\n }\n return found.length === 1 ? found[0] : undefined;\n}\n\n/**\n * Find the single node that is not a source of any edge.\n * Exclude nodes/targets with ids in the exclude list.\n * If there is no such node, or there are multiple, return undefined.\n * When drawing the graph, this node would be the destination.\n */\nfunction _lastNode(graph: Graph, exclude: string[] = []): Node | undefined {\n const sources = new Set(\n graph.edges\n .filter((edge) => !exclude.includes(edge.target))\n .map((edge) => edge.source)\n );\n\n const found: Node[] = [];\n for (const node of Object.values(graph.nodes)) {\n if (!exclude.includes(node.id) && !sources.has(node.id)) {\n found.push(node);\n }\n }\n return found.length === 1 ? found[0] : undefined;\n}\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,MAAM,KAAK,IAAI;CAGnB,OAAO,MAAM,WAAW,IAAI,MAAM,KAAK,KAAA;AACzC;;;;;;;AAQA,SAAS,UAAU,OAAc,UAAoB,CAAC,GAAqB;CACzE,MAAM,UAAU,IAAI,IAClB,MAAM,MACH,QAAQ,SAAS,CAAC,QAAQ,SAAS,KAAK,MAAM,CAAC,CAAC,CAChD,KAAK,SAAS,KAAK,MAAM,CAC9B;CAEA,MAAM,QAAgB,CAAC;CACvB,KAAK,MAAM,QAAQ,OAAO,OAAO,MAAM,KAAK,GAC1C,IAAI,CAAC,QAAQ,SAAS,KAAK,EAAE,KAAK,CAAC,QAAQ,IAAI,KAAK,EAAE,GACpD,MAAM,KAAK,IAAI;CAGnB,OAAO,MAAM,WAAW,IAAI,MAAM,KAAK,KAAA;AACzC"}
|
|
@@ -8,6 +8,29 @@ const MARKDOWN_SPECIAL_CHARS = [
|
|
|
8
8
|
"_",
|
|
9
9
|
"`"
|
|
10
10
|
];
|
|
11
|
+
const MERMAID_ENTITY_CODES = {
|
|
12
|
+
"#": "#35;",
|
|
13
|
+
"[": "#91;",
|
|
14
|
+
"]": "#93;",
|
|
15
|
+
"(": "#40;",
|
|
16
|
+
")": "#41;",
|
|
17
|
+
"{": "#123;",
|
|
18
|
+
"}": "#125;",
|
|
19
|
+
"\"": "#quot;",
|
|
20
|
+
"<": "#60;",
|
|
21
|
+
">": "#62;",
|
|
22
|
+
"|": "#124;"
|
|
23
|
+
};
|
|
24
|
+
function _escapeMetadataText(text) {
|
|
25
|
+
return text.replace(/[#[\](){}"<>|]/g, (char) => MERMAID_ENTITY_CODES[char]);
|
|
26
|
+
}
|
|
27
|
+
function _isScalar(value) {
|
|
28
|
+
return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
|
|
29
|
+
}
|
|
30
|
+
function _formatMetadataValue(value) {
|
|
31
|
+
if (_isScalar(value)) return String(value);
|
|
32
|
+
if (Array.isArray(value) && value.every(_isScalar)) return value.join(",");
|
|
33
|
+
}
|
|
11
34
|
function _generateMermaidGraphStyles(nodeColors) {
|
|
12
35
|
let styles = "";
|
|
13
36
|
for (const [className, color] of Object.entries(nodeColors)) styles += `\tclassDef ${className} ${color};\n`;
|
|
@@ -27,7 +50,11 @@ function drawMermaid(nodes, edges, config) {
|
|
|
27
50
|
for (const [key, node] of Object.entries(nodes)) {
|
|
28
51
|
const nodeName = node.name.split(":").pop() ?? "";
|
|
29
52
|
let finalLabel = MARKDOWN_SPECIAL_CHARS.some((char) => nodeName.startsWith(char) && nodeName.endsWith(char)) ? `<p>${nodeName}</p>` : nodeName;
|
|
30
|
-
|
|
53
|
+
const metadataLines = Object.entries(node.metadata ?? {}).flatMap(([k, v]) => {
|
|
54
|
+
const value = _formatMetadataValue(v);
|
|
55
|
+
return value === void 0 ? [] : [_escapeMetadataText(`${k} = ${value}`)];
|
|
56
|
+
});
|
|
57
|
+
if (metadataLines.length) finalLabel += `<hr/><small><em>${metadataLines.join("\n")}</em></small>`;
|
|
31
58
|
const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel]).replace("{0}", _escapeNodeLabel(key)).replace("{1}", finalLabel);
|
|
32
59
|
mermaidGraph += `\t${nodeLabel}\n`;
|
|
33
60
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph_mermaid.cjs","names":["toBase64Url"],"sources":["../../src/runnables/graph_mermaid.ts"],"sourcesContent":["import { Edge, Node } from \"./types.js\";\nimport { toBase64Url } from \"./utils.js\";\n\nfunction _escapeNodeLabel(nodeLabel: string): string {\n // Escapes the node label for Mermaid syntax.\n return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, \"_\");\n}\n\nconst MARKDOWN_SPECIAL_CHARS = [\"*\", \"_\", \"`\"];\n\nfunction _generateMermaidGraphStyles(\n nodeColors: Record<string, string>\n): string {\n let styles = \"\";\n for (const [className, color] of Object.entries(nodeColors)) {\n styles += `\\tclassDef ${className} ${color};\\n`;\n }\n return styles;\n}\n\n/**\n * Draws a Mermaid graph using the provided graph data\n */\nexport function drawMermaid(\n nodes: Record<string, Node>,\n edges: Edge[],\n config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }\n): string {\n const {\n firstNode,\n lastNode,\n nodeColors,\n withStyles = true,\n curveStyle = \"linear\",\n wrapLabelNWords = 9,\n } = config ?? {};\n // Initialize Mermaid graph configuration\n let mermaidGraph = withStyles\n ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\\ngraph TD;\\n`\n : \"graph TD;\\n\";\n if (withStyles) {\n // Node formatting templates\n const defaultClassLabel = \"default\";\n const formatDict: Record<string, string> = {\n [defaultClassLabel]: \"{0}({1})\",\n };\n if (firstNode !== undefined) {\n formatDict[firstNode] = \"{0}([{1}]):::first\";\n }\n if (lastNode !== undefined) {\n formatDict[lastNode] = \"{0}([{1}]):::last\";\n }\n\n // Add nodes to the graph\n for (const [key, node] of Object.entries(nodes)) {\n const nodeName = node.name.split(\":\").pop() ?? \"\";\n const label = MARKDOWN_SPECIAL_CHARS.some(\n (char) => nodeName.startsWith(char) && nodeName.endsWith(char)\n )\n ? `<p>${nodeName}</p>`\n : nodeName;\n\n let finalLabel = label;\n if (Object.keys(node.metadata ?? {}).length) {\n finalLabel += `<hr/><small><em>${Object.entries(node.metadata ?? {})\n .map(([k, v]) => `${k} = ${v}`)\n .join(\"\\n\")}</em></small>`;\n }\n\n const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel])\n .replace(\"{0}\", _escapeNodeLabel(key))\n .replace(\"{1}\", finalLabel);\n\n mermaidGraph += `\\t${nodeLabel}\\n`;\n }\n }\n\n // Group edges by their common prefixes\n const edgeGroups: Record<string, Edge[]> = {};\n for (const edge of edges) {\n const srcParts = edge.source.split(\":\");\n const tgtParts = edge.target.split(\":\");\n const commonPrefix = srcParts\n .filter((src, i) => src === tgtParts[i])\n .join(\":\");\n if (!edgeGroups[commonPrefix]) {\n edgeGroups[commonPrefix] = [];\n }\n edgeGroups[commonPrefix].push(edge);\n }\n\n const seenSubgraphs = new Set<string>();\n\n // sort prefixes by path length for correct nesting\n function sortPrefixesByDepth(prefixes: string[]): string[] {\n return [...prefixes].sort((a, b) => {\n return a.split(\":\").length - b.split(\":\").length;\n });\n }\n\n function addSubgraph(edges: Edge[], prefix: string): void {\n const selfLoop = edges.length === 1 && edges[0].source === edges[0].target;\n if (prefix && !selfLoop) {\n const subgraph = prefix.split(\":\").pop()!;\n\n if (seenSubgraphs.has(prefix)) {\n throw new Error(\n `Found duplicate subgraph '${subgraph}' at '${prefix} -- this likely means that ` +\n \"you're reusing a subgraph node with the same name. \" +\n \"Please adjust your graph to have subgraph nodes with unique names.\"\n );\n }\n\n seenSubgraphs.add(prefix);\n mermaidGraph += `\\tsubgraph ${subgraph}\\n`;\n }\n\n // all nested prefixes for this level, sorted by depth\n const nestedPrefixes = sortPrefixesByDepth(\n Object.keys(edgeGroups).filter(\n (nestedPrefix) =>\n nestedPrefix.startsWith(`${prefix}:`) &&\n nestedPrefix !== prefix &&\n nestedPrefix.split(\":\").length === prefix.split(\":\").length + 1\n )\n );\n\n for (const nestedPrefix of nestedPrefixes) {\n addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);\n }\n\n for (const edge of edges) {\n const { source, target, data, conditional } = edge;\n\n let edgeLabel = \"\";\n if (data !== undefined) {\n let edgeData = data;\n const words = edgeData.split(\" \");\n if (words.length > wrapLabelNWords) {\n edgeData = Array.from(\n { length: Math.ceil(words.length / wrapLabelNWords) },\n (_, i) =>\n words\n .slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords)\n .join(\" \")\n ).join(\" <br> \");\n }\n edgeLabel = conditional\n ? ` -. ${edgeData} .-> `\n : ` -- ${edgeData} --> `;\n } else {\n edgeLabel = conditional ? \" -.-> \" : \" --> \";\n }\n\n mermaidGraph += `\\t${_escapeNodeLabel(\n source\n )}${edgeLabel}${_escapeNodeLabel(target)};\\n`;\n }\n\n if (prefix && !selfLoop) {\n mermaidGraph += \"\\tend\\n\";\n }\n }\n\n // Start with the top-level edges (no common prefix)\n addSubgraph(edgeGroups[\"\"] ?? [], \"\");\n\n // Add remaining top-level subgraphs\n for (const prefix in edgeGroups) {\n if (!prefix.includes(\":\") && prefix !== \"\") {\n addSubgraph(edgeGroups[prefix], prefix);\n }\n }\n\n // Add custom styles for nodes\n if (withStyles) {\n mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {});\n }\n\n return mermaidGraph;\n}\n\n/**\n * Renders Mermaid graph using the Mermaid.INK API.\n *\n * @example\n * ```javascript\n * const image = await drawMermaidImage(mermaidSyntax, {\n * backgroundColor: \"white\",\n * imageType: \"png\",\n * });\n * fs.writeFileSync(\"image.png\", image);\n * ```\n *\n * @param mermaidSyntax - The Mermaid syntax to render.\n * @param config - The configuration for the image.\n * @returns The image as a Blob.\n */\nexport async function drawMermaidImage(\n mermaidSyntax: string,\n config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }\n) {\n let backgroundColor = config?.backgroundColor ?? \"white\";\n const imageType = config?.imageType ?? \"png\";\n\n const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax);\n\n // Check if the background color is a hexadecimal color code using regex\n if (backgroundColor !== undefined) {\n const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;\n if (!hexColorPattern.test(backgroundColor)) {\n backgroundColor = `!${backgroundColor}`;\n }\n }\n const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`;\n const res = await fetch(imageUrl);\n if (!res.ok) {\n throw new Error(\n [\n `Failed to render the graph using the Mermaid.INK API.`,\n `Status code: ${res.status}`,\n `Status text: ${res.statusText}`,\n ].join(\"\\n\")\n );\n }\n const content = await res.blob();\n return content;\n}\n"],"mappings":";;AAGA,SAAS,iBAAiB,WAA2B;CAEnD,OAAO,UAAU,Q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"sourcesContent":["import { Edge, Node } from \"./types.js\";\nimport { toBase64Url } from \"./utils.js\";\n\nfunction _escapeNodeLabel(nodeLabel: string): string {\n // Escapes the node label for Mermaid syntax.\n return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, \"_\");\n}\n\nconst MARKDOWN_SPECIAL_CHARS = [\"*\", \"_\", \"`\"];\n\nconst MERMAID_ENTITY_CODES: Record<string, string> = {\n \"#\": \"#35;\",\n \"[\": \"#91;\",\n \"]\": \"#93;\",\n \"(\": \"#40;\",\n \")\": \"#41;\",\n \"{\": \"#123;\",\n \"}\": \"#125;\",\n '\"': \"#quot;\",\n \"<\": \"#60;\",\n \">\": \"#62;\",\n \"|\": \"#124;\",\n};\n\nfunction _escapeMetadataText(text: string): string {\n return text.replace(/[#[\\](){}\"<>|]/g, (char) => MERMAID_ENTITY_CODES[char]);\n}\n\nfunction _isScalar(value: unknown): value is string | number | boolean {\n return (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n );\n}\n\nfunction _formatMetadataValue(value: unknown): string | undefined {\n if (_isScalar(value)) {\n return String(value);\n }\n if (Array.isArray(value) && value.every(_isScalar)) {\n return value.join(\",\");\n }\n return undefined;\n}\n\nfunction _generateMermaidGraphStyles(\n nodeColors: Record<string, string>\n): string {\n let styles = \"\";\n for (const [className, color] of Object.entries(nodeColors)) {\n styles += `\\tclassDef ${className} ${color};\\n`;\n }\n return styles;\n}\n\n/**\n * Draws a Mermaid graph using the provided graph data\n */\nexport function drawMermaid(\n nodes: Record<string, Node>,\n edges: Edge[],\n config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }\n): string {\n const {\n firstNode,\n lastNode,\n nodeColors,\n withStyles = true,\n curveStyle = \"linear\",\n wrapLabelNWords = 9,\n } = config ?? {};\n // Initialize Mermaid graph configuration\n let mermaidGraph = withStyles\n ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\\ngraph TD;\\n`\n : \"graph TD;\\n\";\n if (withStyles) {\n // Node formatting templates\n const defaultClassLabel = \"default\";\n const formatDict: Record<string, string> = {\n [defaultClassLabel]: \"{0}({1})\",\n };\n if (firstNode !== undefined) {\n formatDict[firstNode] = \"{0}([{1}]):::first\";\n }\n if (lastNode !== undefined) {\n formatDict[lastNode] = \"{0}([{1}]):::last\";\n }\n\n // Add nodes to the graph\n for (const [key, node] of Object.entries(nodes)) {\n const nodeName = node.name.split(\":\").pop() ?? \"\";\n const label = MARKDOWN_SPECIAL_CHARS.some(\n (char) => nodeName.startsWith(char) && nodeName.endsWith(char)\n )\n ? `<p>${nodeName}</p>`\n : nodeName;\n\n let finalLabel = label;\n const metadataLines = Object.entries(node.metadata ?? {}).flatMap(\n ([k, v]) => {\n const value = _formatMetadataValue(v);\n return value === undefined\n ? []\n : [_escapeMetadataText(`${k} = ${value}`)];\n }\n );\n if (metadataLines.length) {\n finalLabel += `<hr/><small><em>${metadataLines.join(\n \"\\n\"\n )}</em></small>`;\n }\n\n const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel])\n .replace(\"{0}\", _escapeNodeLabel(key))\n .replace(\"{1}\", finalLabel);\n\n mermaidGraph += `\\t${nodeLabel}\\n`;\n }\n }\n\n // Group edges by their common prefixes\n const edgeGroups: Record<string, Edge[]> = {};\n for (const edge of edges) {\n const srcParts = edge.source.split(\":\");\n const tgtParts = edge.target.split(\":\");\n const commonPrefix = srcParts\n .filter((src, i) => src === tgtParts[i])\n .join(\":\");\n if (!edgeGroups[commonPrefix]) {\n edgeGroups[commonPrefix] = [];\n }\n edgeGroups[commonPrefix].push(edge);\n }\n\n const seenSubgraphs = new Set<string>();\n\n // sort prefixes by path length for correct nesting\n function sortPrefixesByDepth(prefixes: string[]): string[] {\n return [...prefixes].sort((a, b) => {\n return a.split(\":\").length - b.split(\":\").length;\n });\n }\n\n function addSubgraph(edges: Edge[], prefix: string): void {\n const selfLoop = edges.length === 1 && edges[0].source === edges[0].target;\n if (prefix && !selfLoop) {\n const subgraph = prefix.split(\":\").pop()!;\n\n if (seenSubgraphs.has(prefix)) {\n throw new Error(\n `Found duplicate subgraph '${subgraph}' at '${prefix} -- this likely means that ` +\n \"you're reusing a subgraph node with the same name. \" +\n \"Please adjust your graph to have subgraph nodes with unique names.\"\n );\n }\n\n seenSubgraphs.add(prefix);\n mermaidGraph += `\\tsubgraph ${subgraph}\\n`;\n }\n\n // all nested prefixes for this level, sorted by depth\n const nestedPrefixes = sortPrefixesByDepth(\n Object.keys(edgeGroups).filter(\n (nestedPrefix) =>\n nestedPrefix.startsWith(`${prefix}:`) &&\n nestedPrefix !== prefix &&\n nestedPrefix.split(\":\").length === prefix.split(\":\").length + 1\n )\n );\n\n for (const nestedPrefix of nestedPrefixes) {\n addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);\n }\n\n for (const edge of edges) {\n const { source, target, data, conditional } = edge;\n\n let edgeLabel = \"\";\n if (data !== undefined) {\n let edgeData = data;\n const words = edgeData.split(\" \");\n if (words.length > wrapLabelNWords) {\n edgeData = Array.from(\n { length: Math.ceil(words.length / wrapLabelNWords) },\n (_, i) =>\n words\n .slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords)\n .join(\" \")\n ).join(\" <br> \");\n }\n edgeLabel = conditional\n ? ` -. ${edgeData} .-> `\n : ` -- ${edgeData} --> `;\n } else {\n edgeLabel = conditional ? \" -.-> \" : \" --> \";\n }\n\n mermaidGraph += `\\t${_escapeNodeLabel(\n source\n )}${edgeLabel}${_escapeNodeLabel(target)};\\n`;\n }\n\n if (prefix && !selfLoop) {\n mermaidGraph += \"\\tend\\n\";\n }\n }\n\n // Start with the top-level edges (no common prefix)\n addSubgraph(edgeGroups[\"\"] ?? [], \"\");\n\n // Add remaining top-level subgraphs\n for (const prefix in edgeGroups) {\n if (!prefix.includes(\":\") && prefix !== \"\") {\n addSubgraph(edgeGroups[prefix], prefix);\n }\n }\n\n // Add custom styles for nodes\n if (withStyles) {\n mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {});\n }\n\n return mermaidGraph;\n}\n\n/**\n * Renders Mermaid graph using the Mermaid.INK API.\n *\n * @example\n * ```javascript\n * const image = await drawMermaidImage(mermaidSyntax, {\n * backgroundColor: \"white\",\n * imageType: \"png\",\n * });\n * fs.writeFileSync(\"image.png\", image);\n * ```\n *\n * @param mermaidSyntax - The Mermaid syntax to render.\n * @param config - The configuration for the image.\n * @returns The image as a Blob.\n */\nexport async function drawMermaidImage(\n mermaidSyntax: string,\n config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }\n) {\n let backgroundColor = config?.backgroundColor ?? \"white\";\n const imageType = config?.imageType ?? \"png\";\n\n const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax);\n\n // Check if the background color is a hexadecimal color code using regex\n if (backgroundColor !== undefined) {\n const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;\n if (!hexColorPattern.test(backgroundColor)) {\n backgroundColor = `!${backgroundColor}`;\n }\n }\n const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`;\n const res = await fetch(imageUrl);\n if (!res.ok) {\n throw new Error(\n [\n `Failed to render the graph using the Mermaid.INK API.`,\n `Status code: ${res.status}`,\n `Status text: ${res.statusText}`,\n ].join(\"\\n\")\n );\n }\n const content = await res.blob();\n return content;\n}\n"],"mappings":";;AAGA,SAAS,iBAAiB,WAA2B;CAEnD,OAAO,UAAU,QAAQ,mBAAmB,GAAG;AACjD;AAEA,MAAM,yBAAyB;CAAC;CAAK;CAAK;AAAG;AAE7C,MAAM,uBAA+C;CACnD,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,MAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;AACP;AAEA,SAAS,oBAAoB,MAAs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AAW,2BAA2B,qBAAqB,WAAW,gBAAgB,QAAQ;CACpG,MAAM,MAAM,MAAM,MAAM,QAAQ;CAChC,IAAI,CAAC,IAAI,IACP,MAAM,IAAI,MACR;EACE;EACA,gBAAgB,IAAI;EACpB,gBAAgB,IAAI;CACtB,CAAC,CAAC,KAAK,IAAI,CACb;CAGF,OAAO,MADe,IAAI,KAAK;AAEjC"}
|
|
@@ -8,6 +8,29 @@ const MARKDOWN_SPECIAL_CHARS = [
|
|
|
8
8
|
"_",
|
|
9
9
|
"`"
|
|
10
10
|
];
|
|
11
|
+
const MERMAID_ENTITY_CODES = {
|
|
12
|
+
"#": "#35;",
|
|
13
|
+
"[": "#91;",
|
|
14
|
+
"]": "#93;",
|
|
15
|
+
"(": "#40;",
|
|
16
|
+
")": "#41;",
|
|
17
|
+
"{": "#123;",
|
|
18
|
+
"}": "#125;",
|
|
19
|
+
"\"": "#quot;",
|
|
20
|
+
"<": "#60;",
|
|
21
|
+
">": "#62;",
|
|
22
|
+
"|": "#124;"
|
|
23
|
+
};
|
|
24
|
+
function _escapeMetadataText(text) {
|
|
25
|
+
return text.replace(/[#[\](){}"<>|]/g, (char) => MERMAID_ENTITY_CODES[char]);
|
|
26
|
+
}
|
|
27
|
+
function _isScalar(value) {
|
|
28
|
+
return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
|
|
29
|
+
}
|
|
30
|
+
function _formatMetadataValue(value) {
|
|
31
|
+
if (_isScalar(value)) return String(value);
|
|
32
|
+
if (Array.isArray(value) && value.every(_isScalar)) return value.join(",");
|
|
33
|
+
}
|
|
11
34
|
function _generateMermaidGraphStyles(nodeColors) {
|
|
12
35
|
let styles = "";
|
|
13
36
|
for (const [className, color] of Object.entries(nodeColors)) styles += `\tclassDef ${className} ${color};\n`;
|
|
@@ -27,7 +50,11 @@ function drawMermaid(nodes, edges, config) {
|
|
|
27
50
|
for (const [key, node] of Object.entries(nodes)) {
|
|
28
51
|
const nodeName = node.name.split(":").pop() ?? "";
|
|
29
52
|
let finalLabel = MARKDOWN_SPECIAL_CHARS.some((char) => nodeName.startsWith(char) && nodeName.endsWith(char)) ? `<p>${nodeName}</p>` : nodeName;
|
|
30
|
-
|
|
53
|
+
const metadataLines = Object.entries(node.metadata ?? {}).flatMap(([k, v]) => {
|
|
54
|
+
const value = _formatMetadataValue(v);
|
|
55
|
+
return value === void 0 ? [] : [_escapeMetadataText(`${k} = ${value}`)];
|
|
56
|
+
});
|
|
57
|
+
if (metadataLines.length) finalLabel += `<hr/><small><em>${metadataLines.join("\n")}</em></small>`;
|
|
31
58
|
const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel]).replace("{0}", _escapeNodeLabel(key)).replace("{1}", finalLabel);
|
|
32
59
|
mermaidGraph += `\t${nodeLabel}\n`;
|
|
33
60
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph_mermaid.js","names":[],"sources":["../../src/runnables/graph_mermaid.ts"],"sourcesContent":["import { Edge, Node } from \"./types.js\";\nimport { toBase64Url } from \"./utils.js\";\n\nfunction _escapeNodeLabel(nodeLabel: string): string {\n // Escapes the node label for Mermaid syntax.\n return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, \"_\");\n}\n\nconst MARKDOWN_SPECIAL_CHARS = [\"*\", \"_\", \"`\"];\n\nfunction _generateMermaidGraphStyles(\n nodeColors: Record<string, string>\n): string {\n let styles = \"\";\n for (const [className, color] of Object.entries(nodeColors)) {\n styles += `\\tclassDef ${className} ${color};\\n`;\n }\n return styles;\n}\n\n/**\n * Draws a Mermaid graph using the provided graph data\n */\nexport function drawMermaid(\n nodes: Record<string, Node>,\n edges: Edge[],\n config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }\n): string {\n const {\n firstNode,\n lastNode,\n nodeColors,\n withStyles = true,\n curveStyle = \"linear\",\n wrapLabelNWords = 9,\n } = config ?? {};\n // Initialize Mermaid graph configuration\n let mermaidGraph = withStyles\n ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\\ngraph TD;\\n`\n : \"graph TD;\\n\";\n if (withStyles) {\n // Node formatting templates\n const defaultClassLabel = \"default\";\n const formatDict: Record<string, string> = {\n [defaultClassLabel]: \"{0}({1})\",\n };\n if (firstNode !== undefined) {\n formatDict[firstNode] = \"{0}([{1}]):::first\";\n }\n if (lastNode !== undefined) {\n formatDict[lastNode] = \"{0}([{1}]):::last\";\n }\n\n // Add nodes to the graph\n for (const [key, node] of Object.entries(nodes)) {\n const nodeName = node.name.split(\":\").pop() ?? \"\";\n const label = MARKDOWN_SPECIAL_CHARS.some(\n (char) => nodeName.startsWith(char) && nodeName.endsWith(char)\n )\n ? `<p>${nodeName}</p>`\n : nodeName;\n\n let finalLabel = label;\n if (Object.keys(node.metadata ?? {}).length) {\n finalLabel += `<hr/><small><em>${Object.entries(node.metadata ?? {})\n .map(([k, v]) => `${k} = ${v}`)\n .join(\"\\n\")}</em></small>`;\n }\n\n const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel])\n .replace(\"{0}\", _escapeNodeLabel(key))\n .replace(\"{1}\", finalLabel);\n\n mermaidGraph += `\\t${nodeLabel}\\n`;\n }\n }\n\n // Group edges by their common prefixes\n const edgeGroups: Record<string, Edge[]> = {};\n for (const edge of edges) {\n const srcParts = edge.source.split(\":\");\n const tgtParts = edge.target.split(\":\");\n const commonPrefix = srcParts\n .filter((src, i) => src === tgtParts[i])\n .join(\":\");\n if (!edgeGroups[commonPrefix]) {\n edgeGroups[commonPrefix] = [];\n }\n edgeGroups[commonPrefix].push(edge);\n }\n\n const seenSubgraphs = new Set<string>();\n\n // sort prefixes by path length for correct nesting\n function sortPrefixesByDepth(prefixes: string[]): string[] {\n return [...prefixes].sort((a, b) => {\n return a.split(\":\").length - b.split(\":\").length;\n });\n }\n\n function addSubgraph(edges: Edge[], prefix: string): void {\n const selfLoop = edges.length === 1 && edges[0].source === edges[0].target;\n if (prefix && !selfLoop) {\n const subgraph = prefix.split(\":\").pop()!;\n\n if (seenSubgraphs.has(prefix)) {\n throw new Error(\n `Found duplicate subgraph '${subgraph}' at '${prefix} -- this likely means that ` +\n \"you're reusing a subgraph node with the same name. \" +\n \"Please adjust your graph to have subgraph nodes with unique names.\"\n );\n }\n\n seenSubgraphs.add(prefix);\n mermaidGraph += `\\tsubgraph ${subgraph}\\n`;\n }\n\n // all nested prefixes for this level, sorted by depth\n const nestedPrefixes = sortPrefixesByDepth(\n Object.keys(edgeGroups).filter(\n (nestedPrefix) =>\n nestedPrefix.startsWith(`${prefix}:`) &&\n nestedPrefix !== prefix &&\n nestedPrefix.split(\":\").length === prefix.split(\":\").length + 1\n )\n );\n\n for (const nestedPrefix of nestedPrefixes) {\n addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);\n }\n\n for (const edge of edges) {\n const { source, target, data, conditional } = edge;\n\n let edgeLabel = \"\";\n if (data !== undefined) {\n let edgeData = data;\n const words = edgeData.split(\" \");\n if (words.length > wrapLabelNWords) {\n edgeData = Array.from(\n { length: Math.ceil(words.length / wrapLabelNWords) },\n (_, i) =>\n words\n .slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords)\n .join(\" \")\n ).join(\" <br> \");\n }\n edgeLabel = conditional\n ? ` -. ${edgeData} .-> `\n : ` -- ${edgeData} --> `;\n } else {\n edgeLabel = conditional ? \" -.-> \" : \" --> \";\n }\n\n mermaidGraph += `\\t${_escapeNodeLabel(\n source\n )}${edgeLabel}${_escapeNodeLabel(target)};\\n`;\n }\n\n if (prefix && !selfLoop) {\n mermaidGraph += \"\\tend\\n\";\n }\n }\n\n // Start with the top-level edges (no common prefix)\n addSubgraph(edgeGroups[\"\"] ?? [], \"\");\n\n // Add remaining top-level subgraphs\n for (const prefix in edgeGroups) {\n if (!prefix.includes(\":\") && prefix !== \"\") {\n addSubgraph(edgeGroups[prefix], prefix);\n }\n }\n\n // Add custom styles for nodes\n if (withStyles) {\n mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {});\n }\n\n return mermaidGraph;\n}\n\n/**\n * Renders Mermaid graph using the Mermaid.INK API.\n *\n * @example\n * ```javascript\n * const image = await drawMermaidImage(mermaidSyntax, {\n * backgroundColor: \"white\",\n * imageType: \"png\",\n * });\n * fs.writeFileSync(\"image.png\", image);\n * ```\n *\n * @param mermaidSyntax - The Mermaid syntax to render.\n * @param config - The configuration for the image.\n * @returns The image as a Blob.\n */\nexport async function drawMermaidImage(\n mermaidSyntax: string,\n config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }\n) {\n let backgroundColor = config?.backgroundColor ?? \"white\";\n const imageType = config?.imageType ?? \"png\";\n\n const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax);\n\n // Check if the background color is a hexadecimal color code using regex\n if (backgroundColor !== undefined) {\n const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;\n if (!hexColorPattern.test(backgroundColor)) {\n backgroundColor = `!${backgroundColor}`;\n }\n }\n const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`;\n const res = await fetch(imageUrl);\n if (!res.ok) {\n throw new Error(\n [\n `Failed to render the graph using the Mermaid.INK API.`,\n `Status code: ${res.status}`,\n `Status text: ${res.statusText}`,\n ].join(\"\\n\")\n );\n }\n const content = await res.blob();\n return content;\n}\n"],"mappings":";;AAGA,SAAS,iBAAiB,WAA2B;CAEnD,OAAO,UAAU,QAAQ,mBAAmB,GAAG;AACjD;AAEA,MAAM,yBAAyB;CAAC;CAAK;CAAK;AAAG;AAE7C,SAAS,4BACP,YACQ;CACR,IAAI,SAAS;CACb,KAAK,MAAM,CAAC,WAAW,UAAU,OAAO,QAAQ,UAAU,GACxD,UAAU,cAAc,UAAU,GAAG,MAAM;CAE7C,OAAO;AACT;;;;AAKA,SAAgB,YACd,OACA,OACA,QAQQ;CACR,M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a,SAAS;GAC5B,OACE,YAAY,cAAc,WAAW;GAGvC,gBAAgB,KAAK,iBACnB,MACF,IAAI,YAAY,iBAAiB,MAAM,EAAE;EAC3C;EAEA,IAAI,UAAU,CAAC,UACb,gBAAgB;CAEpB;CAGA,YAAY,WAAW,OAAO,CAAC,GAAG,EAAE;CAGpC,KAAK,MAAM,UAAU,YACnB,IAAI,CAAC,OAAO,SAAS,GAAG,KAAK,WAAW,IACtC,YAAY,WAAW,SAAS,MAAM;CAK1C,IAAI,YACF,gBAAgB,4BAA4B,cAAc,CAAC,CAAC;CAG9D,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,eAAsB,iBACpB,eACA,QAQA;CACA,IAAI,kBAAkB,QAAQ,mBAAmB;CACjD,MAAM,YAAY,QAAQ,aAAa;CAEvC,MAAM,uBAAuB,YAAY,aAAa;CAGtD,IAAI,oBAAoB,KAAA,GAElB;MAAA,CAAC,6BAAgB,KAAK,eAAe,GACvC,kBAAkB,IAAI;CAAA;CAG1B,MAAM,WAAW,2BAA2B,qBAAqB,WAAW,gBAAgB,QAAQ;CACpG,MAAM,MAAM,MAAM,MAAM,QAAQ;CAChC,IAAI,CAAC,IAAI,IACP,MAAM,IAAI,MACR;EACE;EACA,gBAAgB,IAAI;EACpB,gBAAgB,IAAI;CACtB,CAAC,CAAC,KAAK,IAAI,CACb;CAGF,OAAO,MADe,IAAI,KAAK;AAEjC"}
|
|
1
|
+
{"version":3,"file":"graph_mermaid.js","names":[],"sources":["../../src/runnables/graph_mermaid.ts"],"sourcesContent":["import { Edge, Node } from \"./types.js\";\nimport { toBase64Url } from \"./utils.js\";\n\nfunction _escapeNodeLabel(nodeLabel: string): string {\n // Escapes the node label for Mermaid syntax.\n return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, \"_\");\n}\n\nconst MARKDOWN_SPECIAL_CHARS = [\"*\", \"_\", \"`\"];\n\nconst MERMAID_ENTITY_CODES: Record<string, string> = {\n \"#\": \"#35;\",\n \"[\": \"#91;\",\n \"]\": \"#93;\",\n \"(\": \"#40;\",\n \")\": \"#41;\",\n \"{\": \"#123;\",\n \"}\": \"#125;\",\n '\"': \"#quot;\",\n \"<\": \"#60;\",\n \">\": \"#62;\",\n \"|\": \"#124;\",\n};\n\nfunction _escapeMetadataText(text: string): string {\n return text.replace(/[#[\\](){}\"<>|]/g, (char) => MERMAID_ENTITY_CODES[char]);\n}\n\nfunction _isScalar(value: unknown): value is string | number | boolean {\n return (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n );\n}\n\nfunction _formatMetadataValue(value: unknown): string | undefined {\n if (_isScalar(value)) {\n return String(value);\n }\n if (Array.isArray(value) && value.every(_isScalar)) {\n return value.join(\",\");\n }\n return undefined;\n}\n\nfunction _generateMermaidGraphStyles(\n nodeColors: Record<string, string>\n): string {\n let styles = \"\";\n for (const [className, color] of Object.entries(nodeColors)) {\n styles += `\\tclassDef ${className} ${color};\\n`;\n }\n return styles;\n}\n\n/**\n * Draws a Mermaid graph using the provided graph data\n */\nexport function drawMermaid(\n nodes: Record<string, Node>,\n edges: Edge[],\n config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }\n): string {\n const {\n firstNode,\n lastNode,\n nodeColors,\n withStyles = true,\n curveStyle = \"linear\",\n wrapLabelNWords = 9,\n } = config ?? {};\n // Initialize Mermaid graph configuration\n let mermaidGraph = withStyles\n ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\\ngraph TD;\\n`\n : \"graph TD;\\n\";\n if (withStyles) {\n // Node formatting templates\n const defaultClassLabel = \"default\";\n const formatDict: Record<string, string> = {\n [defaultClassLabel]: \"{0}({1})\",\n };\n if (firstNode !== undefined) {\n formatDict[firstNode] = \"{0}([{1}]):::first\";\n }\n if (lastNode !== undefined) {\n formatDict[lastNode] = \"{0}([{1}]):::last\";\n }\n\n // Add nodes to the graph\n for (const [key, node] of Object.entries(nodes)) {\n const nodeName = node.name.split(\":\").pop() ?? \"\";\n const label = MARKDOWN_SPECIAL_CHARS.some(\n (char) => nodeName.startsWith(char) && nodeName.endsWith(char)\n )\n ? `<p>${nodeName}</p>`\n : nodeName;\n\n let finalLabel = label;\n const metadataLines = Object.entries(node.metadata ?? {}).flatMap(\n ([k, v]) => {\n const value = _formatMetadataValue(v);\n return value === undefined\n ? []\n : [_escapeMetadataText(`${k} = ${value}`)];\n }\n );\n if (metadataLines.length) {\n finalLabel += `<hr/><small><em>${metadataLines.join(\n \"\\n\"\n )}</em></small>`;\n }\n\n const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel])\n .replace(\"{0}\", _escapeNodeLabel(key))\n .replace(\"{1}\", finalLabel);\n\n mermaidGraph += `\\t${nodeLabel}\\n`;\n }\n }\n\n // Group edges by their common prefixes\n const edgeGroups: Record<string, Edge[]> = {};\n for (const edge of edges) {\n const srcParts = edge.source.split(\":\");\n const tgtParts = edge.target.split(\":\");\n const commonPrefix = srcParts\n .filter((src, i) => src === tgtParts[i])\n .join(\":\");\n if (!edgeGroups[commonPrefix]) {\n edgeGroups[commonPrefix] = [];\n }\n edgeGroups[commonPrefix].push(edge);\n }\n\n const seenSubgraphs = new Set<string>();\n\n // sort prefixes by path length for correct nesting\n function sortPrefixesByDepth(prefixes: string[]): string[] {\n return [...prefixes].sort((a, b) => {\n return a.split(\":\").length - b.split(\":\").length;\n });\n }\n\n function addSubgraph(edges: Edge[], prefix: string): void {\n const selfLoop = edges.length === 1 && edges[0].source === edges[0].target;\n if (prefix && !selfLoop) {\n const subgraph = prefix.split(\":\").pop()!;\n\n if (seenSubgraphs.has(prefix)) {\n throw new Error(\n `Found duplicate subgraph '${subgraph}' at '${prefix} -- this likely means that ` +\n \"you're reusing a subgraph node with the same name. \" +\n \"Please adjust your graph to have subgraph nodes with unique names.\"\n );\n }\n\n seenSubgraphs.add(prefix);\n mermaidGraph += `\\tsubgraph ${subgraph}\\n`;\n }\n\n // all nested prefixes for this level, sorted by depth\n const nestedPrefixes = sortPrefixesByDepth(\n Object.keys(edgeGroups).filter(\n (nestedPrefix) =>\n nestedPrefix.startsWith(`${prefix}:`) &&\n nestedPrefix !== prefix &&\n nestedPrefix.split(\":\").length === prefix.split(\":\").length + 1\n )\n );\n\n for (const nestedPrefix of nestedPrefixes) {\n addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);\n }\n\n for (const edge of edges) {\n const { source, target, data, conditional } = edge;\n\n let edgeLabel = \"\";\n if (data !== undefined) {\n let edgeData = data;\n const words = edgeData.split(\" \");\n if (words.length > wrapLabelNWords) {\n edgeData = Array.from(\n { length: Math.ceil(words.length / wrapLabelNWords) },\n (_, i) =>\n words\n .slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords)\n .join(\" \")\n ).join(\" <br> \");\n }\n edgeLabel = conditional\n ? ` -. ${edgeData} .-> `\n : ` -- ${edgeData} --> `;\n } else {\n edgeLabel = conditional ? \" -.-> \" : \" --> \";\n }\n\n mermaidGraph += `\\t${_escapeNodeLabel(\n source\n )}${edgeLabel}${_escapeNodeLabel(target)};\\n`;\n }\n\n if (prefix && !selfLoop) {\n mermaidGraph += \"\\tend\\n\";\n }\n }\n\n // Start with the top-level edges (no common prefix)\n addSubgraph(edgeGroups[\"\"] ?? [], \"\");\n\n // Add remaining top-level subgraphs\n for (const prefix in edgeGroups) {\n if (!prefix.includes(\":\") && prefix !== \"\") {\n addSubgraph(edgeGroups[prefix], prefix);\n }\n }\n\n // Add custom styles for nodes\n if (withStyles) {\n mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {});\n }\n\n return mermaidGraph;\n}\n\n/**\n * Renders Mermaid graph using the Mermaid.INK API.\n *\n * @example\n * ```javascript\n * const image = await drawMermaidImage(mermaidSyntax, {\n * backgroundColor: \"white\",\n * imageType: \"png\",\n * });\n * fs.writeFileSync(\"image.png\", image);\n * ```\n *\n * @param mermaidSyntax - The Mermaid syntax to render.\n * @param config - The configuration for the image.\n * @returns The image as a Blob.\n */\nexport async function drawMermaidImage(\n mermaidSyntax: string,\n config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }\n) {\n let backgroundColor = config?.backgroundColor ?? \"white\";\n const imageType = config?.imageType ?? \"png\";\n\n const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax);\n\n // Check if the background color is a hexadecimal color code using regex\n if (backgroundColor !== undefined) {\n const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;\n if (!hexColorPattern.test(backgroundColor)) {\n backgroundColor = `!${backgroundColor}`;\n }\n }\n const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`;\n const res = await fetch(imageUrl);\n if (!res.ok) {\n throw new Error(\n [\n `Failed to render the graph using the Mermaid.INK API.`,\n `Status code: ${res.status}`,\n `Status text: ${res.statusText}`,\n ].join(\"\\n\")\n );\n }\n const content = await res.blob();\n return content;\n}\n"],"mappings":";;AAGA,SAAS,iBAAiB,WAA2B;CAEnD,OAAO,UAAU,QAAQ,mBAAmB,GAAG;AACjD;AAEA,MAAM,yBAAyB;CAAC;CAAK;CAAK;AAAG;AAE7C,MAAM,uBAA+C;CACnD,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,MAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;AACP;AAEA,SAAS,oBAAoB,MAAsB;CACjD,OAAO,KAAK,QAAQ,oBAAoB,SAAS,qBAAqB,KAAK;AAC7E;AAEA,SAAS,UAAU,OAAoD;CACrE,OACE,OAAO,UAAU,YACjB,OAAO,UAAU,YACjB,OAAO,UAAU;AAErB;AAEA,SAAS,qBAAqB,OAAoC;CAChE,IAAI,UAAU,KAAK,GACjB,OAAO,OAAO,KAAK;CAErB,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,MAAM,SAAS,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