Line data Source code
1 : import type {
2 : WorkflowReference,
3 : WorkflowReferenceMetadata
4 : } from '@/workbench/extensions/agent/types/workflowReference'
5 : import { workflowReferenceParts } from './workflowReferenceParts'
6 :
7 0 : function workflowReferenceUrl(id: string): string {
8 0 : return `workflow://${encodeURIComponent(id).replaceAll('(', '%28').replaceAll(')', '%29')}`
9 : }
10 :
11 0 : export function serializeWorkflowReferences(
12 : text: string,
13 : references: WorkflowReference[]
14 : ): string {
15 0 : return workflowReferenceParts(text, references)
16 : .map((part) => {
17 0 : if (part.type === 'text') return part.text
18 : const name = part.reference.name.replace(/[\\[\]]/g, '\\$&')
19 0 : return `[${name}](${workflowReferenceUrl(part.reference.id)})`
20 : })
21 : .join('')
22 : }
23 :
24 0 : export function parseWorkflowReferences(
25 : content: string,
26 : references: WorkflowReferenceMetadata[]
27 : ): { text: string; references: WorkflowReference[] } {
28 0 : const remaining = new Map(
29 : references.map((reference) => [
30 : workflowReferenceUrl(reference.id),
31 : { ...reference, textOffset: 0 }
32 : ])
33 : )
34 0 : const positioned: WorkflowReference[] = []
35 0 : let text = ''
36 0 : let offset = 0
37 0 : for (const match of content.matchAll(
38 : /\[((?:\\.|[^\]\\])*)\]\((workflow:\/\/[^\s)]+)\)/g
39 : )) {
40 0 : const reference = remaining.get(match[2])
41 0 : if (!reference) continue
42 0 : text += content.slice(offset, match.index)
43 0 : positioned.push({
44 : ...reference,
45 : name: match[1].replace(/\\([\\[\]])/g, '$1'),
46 : textOffset: text.length
47 : })
48 0 : remaining.delete(match[2])
49 0 : offset = match.index + match[0].length
50 : }
51 0 : return {
52 : text: text + content.slice(offset),
53 : references: [...remaining.values(), ...positioned]
54 : }
55 : }
|