-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathgenerate-docs.ts
More file actions
executable file
·2833 lines (2414 loc) · 94.3 KB
/
generate-docs.ts
File metadata and controls
executable file
·2833 lines (2414 loc) · 94.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env ts-node
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import { glob } from 'glob'
console.log('Starting documentation generator...')
/**
* Cache for resolved const definitions from types files.
* Key: "toolPrefix:constName" (e.g., "calcom:SCHEDULE_DATA_OUTPUT_PROPERTIES")
* Value: The resolved properties object
*/
const constResolutionCache = new Map<string, Record<string, any>>()
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const rootDir = path.resolve(__dirname, '..')
const BLOCKS_PATH = path.join(rootDir, 'apps/sim/blocks/blocks')
const DOCS_OUTPUT_PATH = path.join(rootDir, 'apps/docs/content/docs/en/tools')
const ICONS_PATH = path.join(rootDir, 'apps/sim/components/icons.tsx')
const DOCS_ICONS_PATH = path.join(rootDir, 'apps/docs/components/icons.tsx')
const LANDING_INTEGRATIONS_DATA_PATH = path.join(
rootDir,
'apps/sim/app/(landing)/integrations/data'
)
const TRIGGERS_PATH = path.join(rootDir, 'apps/sim/triggers')
if (!fs.existsSync(DOCS_OUTPUT_PATH)) {
fs.mkdirSync(DOCS_OUTPUT_PATH, { recursive: true })
}
// Ensure docs components directory exists
const docsComponentsDir = path.dirname(DOCS_ICONS_PATH)
if (!fs.existsSync(docsComponentsDir)) {
fs.mkdirSync(docsComponentsDir, { recursive: true })
}
interface BlockConfig {
type: string
name: string
description: string
longDescription?: string
category: string
bgColor?: string
outputs?: Record<string, any>
tools?: {
access?: string[]
}
operations?: OperationInfo[]
docsLink?: string
[key: string]: any
}
interface TriggerInfo {
id: string
name: string
description: string
}
interface OperationInfo {
name: string
description: string
}
interface IntegrationEntry {
type: string
slug: string
name: string
description: string
longDescription: string
bgColor: string
iconName: string
docsUrl: string
operations: OperationInfo[]
operationCount: number
triggers: TriggerInfo[]
triggerCount: number
authType: 'oauth' | 'api-key' | 'none'
category: string
integrationType?: string
tags?: string[]
}
/**
* Copy the icons.tsx file from the main sim app to the docs app
* This ensures icons are rendered consistently across both apps
*/
function copyIconsFile(): void {
try {
console.log('Copying icons from sim app to docs app...')
if (!fs.existsSync(ICONS_PATH)) {
console.error(`Source icons file not found: ${ICONS_PATH}`)
return
}
const iconsContent = fs.readFileSync(ICONS_PATH, 'utf-8')
fs.writeFileSync(DOCS_ICONS_PATH, iconsContent)
console.log('✓ Icons successfully copied to docs app')
} catch (error) {
console.error('Error copying icons file:', error)
}
}
/**
* Generate icon mapping from all block definitions
* Maps block types to their icon component names
* Skips blocks that don't have documentation generated (same logic as generateBlockDoc)
*/
async function generateIconMapping(): Promise<Record<string, string>> {
try {
console.log('Generating icon mapping from block definitions...')
const iconMapping: Record<string, string> = {}
const blockFiles = (await glob(`${BLOCKS_PATH}/*.ts`)).sort()
for (const blockFile of blockFiles) {
const fileContent = fs.readFileSync(blockFile, 'utf-8')
// For icon mapping, we need ALL blocks including hidden ones
// because V2 blocks inherit icons from legacy blocks via spread
// First, extract the primary icon from the file (usually the legacy block's icon)
const primaryIcon = extractIconNameFromContent(fileContent)
// Find all block exports and their types
const exportRegex = /export\s+const\s+(\w+)Block\s*:\s*BlockConfig[^=]*=\s*\{/g
let match
while ((match = exportRegex.exec(fileContent)) !== null) {
const blockName = match[1]
const startIndex = match.index + match[0].length - 1
// Extract the block content
let braceCount = 1
let endIndex = startIndex + 1
while (endIndex < fileContent.length && braceCount > 0) {
if (fileContent[endIndex] === '{') braceCount++
else if (fileContent[endIndex] === '}') braceCount--
endIndex++
}
if (braceCount === 0) {
const blockContent = fileContent.substring(startIndex, endIndex)
// Check hideFromToolbar - skip hidden blocks for docs but NOT for icon mapping
const hideFromToolbar = /hideFromToolbar\s*:\s*true/.test(blockContent)
// Get block type
const blockType =
extractStringPropertyFromContent(blockContent, 'type') || blockName.toLowerCase()
// Get icon - either from this block or inherited from primary
const iconName = extractIconNameFromContent(blockContent) || primaryIcon
if (!blockType || !iconName) {
continue
}
// Skip trigger/webhook/rss blocks
if (
blockType.includes('_trigger') ||
blockType.includes('_webhook') ||
blockType.includes('rss')
) {
continue
}
// Get category for additional filtering
const category = extractStringPropertyFromContent(blockContent, 'category') || 'misc'
if (
(category === 'blocks' && blockType !== 'memory' && blockType !== 'knowledge') ||
blockType === 'evaluator' ||
blockType === 'number' ||
blockType === 'webhook' ||
blockType === 'schedule' ||
blockType === 'mcp' ||
blockType === 'generic_webhook' ||
blockType === 'rss'
) {
continue
}
// Only add non-hidden blocks to icon mapping (docs won't be generated for hidden)
if (!hideFromToolbar) {
iconMapping[blockType] = iconName
}
}
}
}
console.log(`✓ Generated icon mapping for ${Object.keys(iconMapping).length} blocks`)
return iconMapping
} catch (error) {
console.error('Error generating icon mapping:', error)
return {}
}
}
/**
* Write the icon mapping to the docs app
* This file is imported by BlockInfoCard to resolve icons automatically
*/
function writeIconMapping(iconMapping: Record<string, string>): void {
try {
const iconMappingPath = path.join(rootDir, 'apps/docs/components/ui/icon-mapping.ts')
// Get unique icon names
const iconNames = [...new Set(Object.values(iconMapping))].sort()
// Generate imports
const imports = iconNames.map((icon) => ` ${icon},`).join('\n')
// Generate mapping with direct references (no dynamic access for tree shaking)
const mappingEntries = Object.entries(iconMapping)
.sort(([a], [b]) => a.localeCompare(b))
.map(([blockType, iconName]) => ` ${blockType}: ${iconName},`)
.join('\n')
const content = `// Auto-generated file - do not edit manually
// Generated by scripts/generate-docs.ts
// Maps block types to their icon component references
import type { ComponentType, SVGProps } from 'react'
import {
${imports}
} from '@/components/icons'
type IconComponent = ComponentType<SVGProps<SVGSVGElement>>
export const blockTypeToIconMap: Record<string, IconComponent> = {
${mappingEntries}
}
`
fs.writeFileSync(iconMappingPath, content)
console.log('✓ Icon mapping file written to docs app')
} catch (error) {
console.error('Error writing icon mapping:', error)
}
}
/**
* Extract operation options from the subBlock with id: 'operation' (if present).
* Returns { label, id } pairs — label is the display name, id is the option's id field
* (used to construct the tool ID as `{blockType}_{id}`).
* Parses the subBlocks array using brace/bracket counting to safely traverse
* the nested structure without eval or a full AST parser.
*/
function extractOperationsFromContent(blockContent: string): { label: string; id: string }[] {
const subBlocksMatch = /subBlocks\s*:\s*\[/.exec(blockContent)
if (!subBlocksMatch) return []
// Locate the opening '[' of the subBlocks array
const arrayStart = subBlocksMatch.index + subBlocksMatch[0].length - 1
let bracketCount = 1
let pos = arrayStart + 1
while (pos < blockContent.length && bracketCount > 0) {
if (blockContent[pos] === '[') bracketCount++
else if (blockContent[pos] === ']') bracketCount--
pos++
}
const subBlocksContent = blockContent.substring(arrayStart + 1, pos - 1)
// Iterate over top-level objects in the subBlocks array, looking for id: 'operation'
let i = 0
while (i < subBlocksContent.length) {
if (subBlocksContent[i] === '{') {
let braceCount = 1
let j = i + 1
while (j < subBlocksContent.length && braceCount > 0) {
if (subBlocksContent[j] === '{') braceCount++
else if (subBlocksContent[j] === '}') braceCount--
j++
}
const objContent = subBlocksContent.substring(i, j)
if (/\bid\s*:\s*['"]operation['"]/.test(objContent)) {
const optionsMatch = /options\s*:\s*\[/.exec(objContent)
if (!optionsMatch) return []
const optArrayStart = optionsMatch.index + optionsMatch[0].length - 1
let bc = 1
let op = optArrayStart + 1
while (op < objContent.length && bc > 0) {
if (objContent[op] === '[') bc++
else if (objContent[op] === ']') bc--
op++
}
const optionsContent = objContent.substring(optArrayStart + 1, op - 1)
// Extract { label, id } pairs from each option object
const pairs: { label: string; id: string }[] = []
const optionObjectRegex = /\{[^{}]*\}/g
let m
while ((m = optionObjectRegex.exec(optionsContent)) !== null) {
const optObj = m[0]
const labelMatch = /label\s*:\s*['"]([^'"]+)['"]/.exec(optObj)
const idMatch = /\bid\s*:\s*['"]([^'"]+)['"]/.exec(optObj)
if (labelMatch) {
pairs.push({ label: labelMatch[1], id: idMatch ? idMatch[1] : '' })
}
}
return pairs
}
i = j
} else {
i++
}
}
return []
}
/**
* Extract a mapping from operation id → tool id by scanning switch/case/return
* patterns in a block file. Handles both simple returns and ternary returns
* (for ternaries, takes the last quoted tool-like string, which is typically
* the default/list variant). Also picks up named helper functions referenced
* from tools.config.tool (e.g. selectGmailToolId).
*/
function extractSwitchCaseToolMapping(fileContent: string): Map<string, string> {
const mapping = new Map<string, string>()
const caseRegex = /\bcase\s+['"]([^'"]+)['"]\s*:/g
let caseMatch: RegExpExecArray | null
while ((caseMatch = caseRegex.exec(fileContent)) !== null) {
const opId = caseMatch[1]
if (mapping.has(opId)) continue
const searchStart = caseMatch.index + caseMatch[0].length
const searchEnd = Math.min(searchStart + 300, fileContent.length)
const segment = fileContent.substring(searchStart, searchEnd)
const returnIdx = segment.search(/\breturn\b/)
if (returnIdx === -1) continue
const afterReturn = segment.substring(returnIdx + 'return'.length)
// Limit scope to before the next case/default to avoid capturing sibling cases
const nextCaseIdx = afterReturn.search(/\bcase\b|\bdefault\b/)
const returnScope = nextCaseIdx > 0 ? afterReturn.substring(0, nextCaseIdx) : afterReturn
const toolMatches = [...returnScope.matchAll(/['"]([a-z][a-z0-9_]+)['"]/g)]
// Take the last tool-like string (underscore = tool ID pattern); for ternaries this
// is the fallback/list variant
const toolId = toolMatches
.map((m) => m[1])
.filter((id) => id.includes('_'))
.pop()
if (toolId) {
mapping.set(opId, toolId)
}
}
return mapping
}
/**
* Scan all tool files under apps/sim/tools/ and build a map from tool ID to description.
* Used to enrich operation entries with descriptions.
*/
interface ToolMaps {
desc: Map<string, string>
name: Map<string, string>
}
async function buildToolDescriptionMap(): Promise<ToolMaps> {
const toolsDir = path.join(rootDir, 'apps/sim/tools')
const desc = new Map<string, string>()
const name = new Map<string, string>()
try {
const toolFiles = await glob(`${toolsDir}/**/*.ts`)
for (const file of toolFiles) {
const basename = path.basename(file)
if (basename === 'index.ts' || basename === 'types.ts') continue
const content = fs.readFileSync(file, 'utf-8')
// Find every `id: 'tool_id'` occurrence in the file. For each, search
// the next ~600 characters for `name:` and `description:` fields, cutting
// off at the first `params:` block within that window. This handles both
// the simple inline pattern (id → description → params in one object) and
// the two-step pattern (base object holds params, ToolConfig export holds
// id + description after the base object).
const idRegex = /\bid\s*:\s*['"]([^'"]+)['"]/g
let idMatch: RegExpExecArray | null
while ((idMatch = idRegex.exec(content)) !== null) {
const toolId = idMatch[1]
if (desc.has(toolId)) continue
const windowStart = idMatch.index
const windowEnd = Math.min(windowStart + 600, content.length)
const window = content.substring(windowStart, windowEnd)
// Stop before any params block so we don't pick up param-level values
const paramsOffset = window.search(/\bparams\s*:\s*\{/)
const searchWindow = paramsOffset > 0 ? window.substring(0, paramsOffset) : window
const descMatch = searchWindow.match(/\bdescription\s*:\s*['"]([^'"]{5,})['"]/)
const nameMatch = searchWindow.match(/\bname\s*:\s*['"]([^'"]+)['"]/)
if (descMatch) desc.set(toolId, descMatch[1])
if (nameMatch) name.set(toolId, nameMatch[1])
}
}
} catch {
// Non-fatal: descriptions will be empty strings
}
return { desc, name }
}
/**
* Detect the authentication type from block content.
* Returns 'oauth' if the block uses oauth-input credentials,
* 'api-key' if it uses a plain API key field, or 'none' otherwise.
*/
function extractAuthType(blockContent: string): 'oauth' | 'api-key' | 'none' {
if (/type\s*:\s*['"]oauth-input['"]/.test(blockContent)) return 'oauth'
if (/\bid\s*:\s*['"](?:apiKey|api_key|accessToken)['"]/.test(blockContent)) return 'api-key'
return 'none'
}
/**
* Extract the list of trigger IDs from the block's `triggers.available` array.
* Handles blocks that declare `triggers: { enabled: true, available: [...] }`.
*/
function extractTriggersAvailable(blockContent: string): string[] {
const triggersMatch = /\btriggers\s*:\s*\{/.exec(blockContent)
if (!triggersMatch) return []
const start = triggersMatch.index + triggersMatch[0].length - 1
let braceCount = 1
let pos = start + 1
while (pos < blockContent.length && braceCount > 0) {
if (blockContent[pos] === '{') braceCount++
else if (blockContent[pos] === '}') braceCount--
pos++
}
const triggersContent = blockContent.substring(start, pos)
if (!/enabled\s*:\s*true/.test(triggersContent)) return []
const availableMatch = /available\s*:\s*\[/.exec(triggersContent)
if (!availableMatch) return []
const arrayStart = availableMatch.index + availableMatch[0].length - 1
let bracketCount = 1
let ap = arrayStart + 1
while (ap < triggersContent.length && bracketCount > 0) {
if (triggersContent[ap] === '[') bracketCount++
else if (triggersContent[ap] === ']') bracketCount--
ap++
}
const arrayContent = triggersContent.substring(arrayStart + 1, ap - 1)
const ids: string[] = []
const idRegex = /['"]([^'"]+)['"]/g
let m
while ((m = idRegex.exec(arrayContent)) !== null) {
ids.push(m[1])
}
return ids
}
/**
* Scan all trigger definition files and build a registry mapping trigger IDs
* to their human-readable name and description.
*/
async function buildTriggerRegistry(): Promise<Map<string, TriggerInfo>> {
const registry = new Map<string, TriggerInfo>()
const SKIP = new Set(['index.ts', 'registry.ts', 'types.ts', 'constants.ts', 'utils.ts'])
const triggerFiles = (await glob(`${TRIGGERS_PATH}/**/*.ts`)).filter(
(f) => !SKIP.has(path.basename(f)) && !f.includes('.test.')
)
for (const file of triggerFiles) {
try {
const content = fs.readFileSync(file, 'utf-8')
// Each trigger file exports a single TriggerConfig with id, name, description
const idMatch = /\bid\s*:\s*['"]([^'"]+)['"]/.exec(content)
const nameMatch = /\bname\s*:\s*['"]([^'"]+)['"]/.exec(content)
const descMatch = /\bdescription\s*:\s*['"]([^'"]+)['"]/.exec(content)
if (idMatch && nameMatch) {
registry.set(idMatch[1], {
id: idMatch[1],
name: nameMatch[1],
description: descMatch?.[1] ?? '',
})
}
} catch {
// skip unreadable files silently
}
}
console.log(`✓ Loaded ${registry.size} trigger definitions`)
return registry
}
/**
* Write the icon mapping TypeScript file for the landing integrations page.
* Mirrors writeIconMapping but targets the sim app so it imports from @/components/icons.
*/
function writeIntegrationsIconMapping(iconMapping: Record<string, string>): void {
try {
if (!fs.existsSync(LANDING_INTEGRATIONS_DATA_PATH)) {
fs.mkdirSync(LANDING_INTEGRATIONS_DATA_PATH, { recursive: true })
}
const iconMappingPath = path.join(LANDING_INTEGRATIONS_DATA_PATH, 'icon-mapping.ts')
const iconNames = [...new Set(Object.values(iconMapping))].sort()
const imports = iconNames.map((icon) => ` ${icon},`).join('\n')
const mappingEntries = Object.entries(iconMapping)
.sort(([a], [b]) => a.localeCompare(b))
.map(([blockType, iconName]) => ` ${blockType}: ${iconName},`)
.join('\n')
const content = `// Auto-generated file - do not edit manually
// Generated by scripts/generate-docs.ts
// Maps block types to their icon component references for the integrations page
import type { ComponentType, SVGProps } from 'react'
import {
${imports}
} from '@/components/icons'
type IconComponent = ComponentType<SVGProps<SVGSVGElement>>
export const blockTypeToIconMap: Record<string, IconComponent> = {
${mappingEntries}
}
`
fs.writeFileSync(iconMappingPath, content)
console.log('✓ Integration icon mapping written to landing app')
} catch (error) {
console.error('Error writing integration icon mapping:', error)
}
}
/**
* Collect all integration entries from block definitions and write integrations.json
* to the landing integrations page data directory.
* Applies the same visibility filters as the docs generation pipeline.
*/
async function writeIntegrationsJson(iconMapping: Record<string, string>): Promise<void> {
try {
if (!fs.existsSync(LANDING_INTEGRATIONS_DATA_PATH)) {
fs.mkdirSync(LANDING_INTEGRATIONS_DATA_PATH, { recursive: true })
}
const triggerRegistry = await buildTriggerRegistry()
const { desc: toolDescMap, name: toolNameMap } = await buildToolDescriptionMap()
const integrations: IntegrationEntry[] = []
const seenBaseTypes = new Set<string>()
const blockFiles = (await glob(`${BLOCKS_PATH}/*.ts`)).sort()
for (const blockFile of blockFiles) {
const fileContent = fs.readFileSync(blockFile, 'utf-8')
const switchCaseMap = extractSwitchCaseToolMapping(fileContent)
const configs = extractAllBlockConfigs(fileContent)
for (const config of configs) {
const blockType = config.type
// Apply the same filters as docs/icon-mapping generation
if (
blockType.includes('_trigger') ||
blockType.includes('_webhook') ||
blockType.includes('rss') ||
(config.category === 'blocks' && blockType !== 'memory' && blockType !== 'knowledge') ||
blockType === 'evaluator' ||
blockType === 'number' ||
blockType === 'webhook' ||
blockType === 'schedule' ||
blockType === 'mcp' ||
blockType === 'generic_webhook'
) {
continue
}
// Deduplicate by stripped base type
const baseType = stripVersionSuffix(blockType)
if (seenBaseTypes.has(baseType)) continue
seenBaseTypes.add(baseType)
const iconName = (config as any).iconName || iconMapping[blockType] || ''
const rawOps: { label: string; id: string }[] = (config as any).operations || []
// Enrich each operation with a description from the tool registry.
// Lookup order:
// 1. Derive toolId as `{baseType}_{operationId}` and check directly.
// 2. Check switch/case mapping parsed from tools.config.tool (handles
// cases where op IDs differ from tool IDs, e.g. get_carts → list_carts,
// or send_gmail → gmail_send).
// 3. Find the tool in tools.access whose name exactly matches the label.
const toolsAccess: string[] = (config as any).tools?.access || []
const operations: OperationInfo[] = rawOps.map(({ label, id }) => {
const toolId = `${baseType}_${id}`
let opDesc = toolDescMap.get(toolId) || toolDescMap.get(id) || ''
if (!opDesc) {
const switchMappedId = switchCaseMap.get(id)
if (switchMappedId) {
opDesc = toolDescMap.get(switchMappedId) || ''
// Also check versioned variants in tools.access (e.g. gmail_send_v2)
if (!opDesc) {
for (const tId of toolsAccess) {
if (tId === switchMappedId || tId.startsWith(`${switchMappedId}_v`)) {
opDesc = toolDescMap.get(tId) || ''
if (opDesc) break
}
}
}
}
}
if (!opDesc && toolsAccess.length > 0) {
for (const tId of toolsAccess) {
if (toolNameMap.get(tId)?.toLowerCase() === label.toLowerCase()) {
opDesc = toolDescMap.get(tId) || ''
if (opDesc) break
}
}
}
return { name: label, description: opDesc }
})
const triggerIds: string[] = (config as any).triggerIds || []
const triggers: TriggerInfo[] = triggerIds
.map((id) => triggerRegistry.get(id))
.filter((t): t is TriggerInfo => t !== undefined)
const docsUrl = (config as any).docsLink || `https://docs.sim.ai/tools/${baseType}`
const slug = config.name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
const authType = extractAuthType(fileContent)
integrations.push({
type: blockType,
slug,
name: config.name,
description: config.description,
longDescription: config.longDescription || '',
bgColor: config.bgColor || '#6B7280',
iconName,
docsUrl,
operations,
operationCount: operations.length,
triggers,
triggerCount: triggers.length,
authType,
category: config.category,
...(config.integrationType ? { integrationType: config.integrationType } : {}),
...(config.tags ? { tags: config.tags } : {}),
})
}
}
// Sort alphabetically by name for a predictable, crawl-friendly order
integrations.sort((a, b) => a.name.localeCompare(b.name))
const jsonPath = path.join(LANDING_INTEGRATIONS_DATA_PATH, 'integrations.json')
fs.writeFileSync(jsonPath, JSON.stringify(integrations, null, 2))
console.log(`✓ Integration data written: ${integrations.length} integrations → ${jsonPath}`)
} catch (error) {
console.error('Error writing integrations JSON:', error)
}
}
/**
* Extract ALL block configs from a file, filtering out hidden blocks
*/
function extractAllBlockConfigs(fileContent: string): BlockConfig[] {
const configs: BlockConfig[] = []
// First, extract the primary icon from the file (for V2 blocks that inherit via spread)
const primaryIcon = extractIconNameFromContent(fileContent)
// Find all block exports in the file
const exportRegex = /export\s+const\s+(\w+)Block\s*:\s*BlockConfig[^=]*=\s*\{/g
let match
while ((match = exportRegex.exec(fileContent)) !== null) {
const blockName = match[1]
const startIndex = match.index + match[0].length - 1 // Position of opening brace
// Extract the block content by matching braces
let braceCount = 1
let endIndex = startIndex + 1
while (endIndex < fileContent.length && braceCount > 0) {
if (fileContent[endIndex] === '{') braceCount++
else if (fileContent[endIndex] === '}') braceCount--
endIndex++
}
if (braceCount === 0) {
const blockContent = fileContent.substring(startIndex, endIndex)
// Check if this block has hideFromToolbar: true
const hideFromToolbar = /hideFromToolbar\s*:\s*true/.test(blockContent)
if (hideFromToolbar) {
console.log(`Skipping ${blockName}Block - hideFromToolbar is true`)
continue
}
// Pass fileContent to enable spread inheritance resolution
const config = extractBlockConfigFromContent(blockContent, blockName, fileContent)
if (config) {
// For V2 blocks that don't have an explicit icon, use the primary icon from the file
if (!config.iconName && primaryIcon) {
;(config as any).iconName = primaryIcon
}
configs.push(config)
}
}
}
return configs
}
/**
* Extract the name of the spread base block (e.g., "GitHubBlock" from "...GitHubBlock")
*/
function extractSpreadBase(blockContent: string): string | null {
const spreadMatch = blockContent.match(/^\s*\.\.\.(\w+Block)\s*,/m)
return spreadMatch ? spreadMatch[1] : null
}
/**
* Extract block config from a specific block's content
* If the block uses spread inheritance (e.g., ...GitHubBlock), attempts to resolve
* missing properties from the base block in the file content.
*/
function extractBlockConfigFromContent(
blockContent: string,
blockName: string,
fileContent?: string
): BlockConfig | null {
try {
// Check for spread inheritance
const spreadBase = extractSpreadBase(blockContent)
let baseConfig: BlockConfig | null = null
if (spreadBase && fileContent) {
// Extract the base block's content from the file
const baseBlockRegex = new RegExp(
`export\\s+const\\s+${spreadBase}\\s*:\\s*BlockConfig[^=]*=\\s*\\{`,
'g'
)
const baseMatch = baseBlockRegex.exec(fileContent)
if (baseMatch) {
const startIndex = baseMatch.index + baseMatch[0].length - 1
let braceCount = 1
let endIndex = startIndex + 1
while (endIndex < fileContent.length && braceCount > 0) {
if (fileContent[endIndex] === '{') braceCount++
else if (fileContent[endIndex] === '}') braceCount--
endIndex++
}
if (braceCount === 0) {
const baseBlockContent = fileContent.substring(startIndex, endIndex)
// Recursively extract base config (but don't pass fileContent to avoid infinite loops)
baseConfig = extractBlockConfigFromContent(
baseBlockContent,
spreadBase.replace('Block', '')
)
}
}
}
// Extract properties from this block, using topLevelOnly=true for main properties
const blockType =
extractStringPropertyFromContent(blockContent, 'type', true) || blockName.toLowerCase()
const name =
extractStringPropertyFromContent(blockContent, 'name', true) ||
baseConfig?.name ||
`${blockName} Block`
const description =
extractStringPropertyFromContent(blockContent, 'description', true) ||
baseConfig?.description ||
''
const longDescription =
extractStringPropertyFromContent(blockContent, 'longDescription', true) ||
baseConfig?.longDescription ||
''
const category =
extractStringPropertyFromContent(blockContent, 'category', true) ||
baseConfig?.category ||
'misc'
const bgColor =
extractStringPropertyFromContent(blockContent, 'bgColor', true) ||
baseConfig?.bgColor ||
'#F5F5F5'
const iconName = extractIconNameFromContent(blockContent) || (baseConfig as any)?.iconName || ''
const outputs = extractOutputsFromContent(blockContent)
const toolsAccess = extractToolsAccessFromContent(blockContent)
// For tools.access, if not found directly, check if it's derived from base via map
let finalToolsAccess = toolsAccess
if (toolsAccess.length === 0 && baseConfig?.tools?.access) {
// Check if there's a map operation on base tools
// Pattern: access: (SomeBlock.tools?.access || []).map((toolId) => `${toolId}_v2`)
const mapMatch = blockContent.match(
/access\s*:\s*\(\s*\w+Block\.tools\?\.access\s*\|\|\s*\[\]\s*\)\.map\s*\(\s*\(\s*\w+\s*\)\s*=>\s*`\$\{\s*\w+\s*\}_v(\d+)`\s*\)/
)
if (mapMatch) {
// V2 block - append the version suffix to base tools
const versionSuffix = `_v${mapMatch[1]}`
finalToolsAccess = baseConfig.tools.access.map((tool) => `${tool}${versionSuffix}`)
}
}
const operations = extractOperationsFromContent(blockContent)
const triggerIds = extractTriggersAvailable(blockContent)
const docsLink =
extractStringPropertyFromContent(blockContent, 'docsLink', true) ||
baseConfig?.docsLink ||
`https://docs.sim.ai/tools/${stripVersionSuffix(blockType)}`
const integrationType =
extractEnumPropertyFromContent(blockContent, 'integrationType') ||
baseConfig?.integrationType ||
null
const tags = extractArrayPropertyFromContent(blockContent, 'tags') || baseConfig?.tags || null
return {
type: blockType,
name,
description,
longDescription,
category,
bgColor,
iconName,
outputs,
tools: {
access: finalToolsAccess.length > 0 ? finalToolsAccess : baseConfig?.tools?.access || [],
},
operations: operations.length > 0 ? operations : (baseConfig as any)?.operations || [],
triggerIds: triggerIds.length > 0 ? triggerIds : (baseConfig as any)?.triggerIds || [],
docsLink,
...(integrationType ? { integrationType } : {}),
...(tags ? { tags } : {}),
}
} catch (error) {
console.error(`Error extracting block configuration for ${blockName}:`, error)
return null
}
}
/**
* Strip version suffix (e.g., _v2, _v3) from a type for display purposes
* The internal type remains unchanged for icon mapping
*/
function stripVersionSuffix(type: string): string {
return type.replace(/_v\d+$/, '')
}
/**
* Extract a string property from block content.
* For top-level properties like 'description', only looks in the portion before nested objects
* to avoid matching properties inside nested structures like outputs.
*/
function extractStringPropertyFromContent(
content: string,
propName: string,
topLevelOnly = false
): string | null {
let searchContent = content
// For top-level properties, only search before nested objects like outputs, tools, inputs, subBlocks
if (topLevelOnly) {
const nestedObjectPatterns = [
/\boutputs\s*:\s*\{/,
/\btools\s*:\s*\{/,
/\binputs\s*:\s*\{/,
/\bsubBlocks\s*:\s*\[/,
/\btriggers\s*:\s*\{/,
]
let cutoffIndex = content.length
for (const pattern of nestedObjectPatterns) {
const match = content.match(pattern)
if (match && match.index !== undefined && match.index < cutoffIndex) {
cutoffIndex = match.index
}
}
searchContent = content.substring(0, cutoffIndex)
}
const singleQuoteMatch = searchContent.match(new RegExp(`${propName}\\s*:\\s*'([^']*)'`, 'm'))
if (singleQuoteMatch) return singleQuoteMatch[1]
const doubleQuoteMatch = searchContent.match(new RegExp(`${propName}\\s*:\\s*"([^"]*)"`, 'm'))
if (doubleQuoteMatch) return doubleQuoteMatch[1]
const templateMatch = searchContent.match(new RegExp(`${propName}\\s*:\\s*\`([^\`]+)\``, 's'))
if (templateMatch) {
let templateContent = templateMatch[1]
templateContent = templateContent.replace(/\$\{[^}]+\}/g, '')
templateContent = templateContent.replace(/\s+/g, ' ').trim()
return templateContent
}
return null
}
/**
* Extract an enum property value from block content.
* Matches patterns like `integrationType: IntegrationType.DeveloperTools`
* and returns the string value (e.g., 'developer-tools').
*/
function extractEnumPropertyFromContent(content: string, propName: string): string | null {
const match = content.match(new RegExp(`${propName}\\s*:\\s*IntegrationType\\.(\\w+)`))
if (!match) return null
const enumKey = match[1]
// Convert enum key to kebab-case value (e.g., DeveloperTools -> developer-tools)
const ENUM_MAP: Record<string, string> = {
AI: 'ai',
Analytics: 'analytics',
Automation: 'automation',
Communication: 'communication',
CRM: 'crm',
CustomerSupport: 'customer-support',
Databases: 'databases',
Design: 'design',
DeveloperTools: 'developer-tools',
Documents: 'documents',
Ecommerce: 'ecommerce',
Email: 'email',
FileStorage: 'file-storage',
HR: 'hr',
Media: 'media',
Other: 'other',
Productivity: 'productivity',
SalesIntelligence: 'sales-intelligence',
Search: 'search',
Security: 'security',
Social: 'social',
}
return ENUM_MAP[enumKey] || enumKey.toLowerCase()
}
/**
* Extract a string array property from block content.
* Matches patterns like `tags: ['api', 'oauth', 'webhooks']`
*/
function extractArrayPropertyFromContent(content: string, propName: string): string[] | null {
const match = content.match(new RegExp(`${propName}\\s*:\\s*\\[([^\\]]+)\\]`))
if (!match) return null
const items = match[1].match(/'([^']+)'|"([^"]+)"/g)
if (!items) return null
return items.map((item) => item.replace(/['"]/g, ''))
}
function extractIconNameFromContent(content: string): string | null {
const iconMatch = content.match(/icon\s*:\s*(\w+Icon)/)
return iconMatch ? iconMatch[1] : null
}
function extractOutputsFromContent(content: string): Record<string, any> {
const outputsStart = content.search(/outputs\s*:\s*{/)
if (outputsStart === -1) return {}
const openBracePos = content.indexOf('{', outputsStart)
if (openBracePos === -1) return {}
let braceCount = 1
let pos = openBracePos + 1
while (pos < content.length && braceCount > 0) {
if (content[pos] === '{') braceCount++
else if (content[pos] === '}') braceCount--
pos++
}
if (braceCount === 0) {
const outputsContent = content.substring(openBracePos + 1, pos - 1).trim()
const outputs: Record<string, any> = {}
const fieldRegex = /(\w+)\s*:\s*{/g
let match
const fieldPositions: Array<{ name: string; start: number }> = []
while ((match = fieldRegex.exec(outputsContent)) !== null) {
fieldPositions.push({
name: match[1],
start: match.index + match[0].length - 1,
})
}
fieldPositions.forEach((field) => {