Files
sim/scripts/generate-docs.ts
T
Will ChenandClaude Opus 4.8 bc55fc3b50 improvement(docs): builder-first IA reorganization of the English docs (#4896)
* docs: reorganize into topic/ontology IA with a builder-first rewrite

Restructure the English docs from internal product categories into a
topic-based information architecture, and rewrite the conceptual pages
to install a mental model first rather than enumerate features.

Structure & navigation
- Reorder the sidebar to follow how someone builds: Get Started ->
  Workflows -> Tables -> Files -> Knowledge Bases -> Logs ->
  Building agents -> Mothership -> Workspaces -> Platform -> Reference.
- Demote the generated blocks/tools/triggers catalogs to a Reference
  section at the bottom.
- Break up the monolithic execution/ folder into deployment/ and
  logs-debugging/; collapse connections/* and variables/* into single
  pages under workflows/.
- Rename capabilities/ to building-agents/; relabel the integration
  catalog as "Integrations". Remove deprecated copilot and form
  deployment. Redirects added in next.config.ts for every moved URL.

Conceptual rewrites
- Workflows core (index, how-it-runs, data-flow, connections,
  variables): one mental model, one running example, terser prose.
- New building-agents overview distinguishes an agent (a workflow you
  build) from an Agent block (one reasoning step), plus a "choosing
  what to use" guide.
- Concept-trim passes on Knowledge Base, Tables, Blocks, Triggers
  overviews; new task pages for KB, Tables, and Files.
- New code-verified Alerts page.

Infrastructure
- pageType frontmatter (concept/guide/reference) + badge render.
- WorkflowPreview / OutputBundle components to embed real, app-styled
  workflow diagrams (adds framer-motion + reactflow to apps/docs).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(docs): spec-driven BlockPreview for block reference heroes

Replace the static screenshot hero on each block reference page with a
<BlockPreview> that renders the block exactly as the builder canvas shows
it — header icon, sub-block rows, and branch/error handles — from a
hand-authored display spec. Static and non-interactive (no ReactFlow), so
it can't be panned or dragged, and self-updating to edit.

- block-display-specs.ts: one editable spec per block (rows, branches, handles)
- block-preview.tsx: static scaled card renderer with decorative handles
- block-icons.tsx: brand glyphs for the core block types; icons.tsx adds WaitIcon
- 14 block + 3 trigger pages swapped from <Image> to <BlockPreview>

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(docs): correct stale navigation and removed-feature references

Audited the docs against the product changelog (GitHub releases / staging
git history) for content that misleads readers — features that moved, were
renamed, or removed — rather than cosmetic drift. Fixes:

- Skills: no longer a Settings tab. It was promoted to its own workspace
  page (#4354), so "Settings → Skills under the Tools section" sent readers
  to a tab that no longer exists. (skills/index.mdx)
- Env vars: the workspace tab is "Secrets", not "Environment Variables"
  (credentials→secrets rename, #4364). (quick-reference/index.mdx)
- Mothership FAQ pointed to "Settings → Credentials" for integration
  connections; integrations moved to their own page and there is no
  Credentials tab. (mothership/tasks.mdx)
- Vision block was retired (#4684); a tip still named it. Reworded to
  "an Agent using a vision-capable model". (files/passing-files.mdx)
- Getting-started FAQ told new users to "use the Copilot feature" to build
  in natural language — that surface is Mothership. (getting-started)
- Removed the dead "Mod+Y → Go to templates" shortcut; the templates
  gallery was removed (#4354). (keyboard-shortcuts)

Note: MCP "tools" (Settings → Tools, for consuming) and MCP "servers"
(Settings → System, for exposing) are distinct surfaces — both doc
references are correct and were intentionally left as-is.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(docs): repair broken /docs-prefixed enterprise links

The enterprise overview linked to /docs/enterprise/* (access-control, sso,
whitelabeling, audit-logs, data-retention, data-drains), but the docs site
is served at root — those 6 links 404'd. Now root-relative /enterprise/*.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(docs): refresh stale workflow-preview example blocks

The /workflows diagram blocks are hand-authored (separate from the
spec-driven BlockPreview heroes) and had drifted from the real UI:
- Agent color purple #6f3dfa -> green #33C482 (the var(--brand) rebrand)
- Model gpt-4o -> claude-sonnet-4-6 (current default)
- "Prompt" row -> "Messages" (the actual agent sub-block)
- Start color #34B5FF -> #2FB3FF (real starter bgColor)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(docs): align BlockPreview input/output handles to the card edge

The header (input/output) handles are positioned relative to the card and
used a -16px offset, so they floated 8px past the edge. Row/error handles
are -16px relative to a row that's already inset 8px by content padding, so
they sit correctly. Header handles are now -8px, so every handle sticks out
the same 8px and hugs the block edge.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): rewrite Agent reference to match the current block

The page documented the old UI (System/User Prompt, no Files or Skills, Memory
taught as a separate block — contradicting its own FAQ). Rewritten to the real
sub-blocks (Messages, Model, Files, Tools, Skills, Memory, Response Format) in
the builder voice of the workflows exemplars: oriented opening, agent vs
Agent-block callout, outputs table, a live WorkflowPreview example, FAQ kept and
corrected (tool control "Force", not "Required"). pageType: reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): rewrite API reference to match the current block

Tightened to the builder voice and the real config (URL, Method, Query Params,
Headers, Body + Advanced timeout/retries/backoff). Dropped the off-topic
"Dynamic URL Construction" / "Response Validation" sections (those are
Function-block techniques, not API config). Outputs table, FAQ kept. The example
is now a live WorkflowPreview (new API_FETCH_WORKFLOW in examples.ts, exported
via the barrel). pageType: reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): rewrite Condition reference to match the current block

Tightened to the builder voice: oriented opening (branches on boolean
expressions, no model call, vs Router), the real branch model (if / else if /
else, checked top to bottom), connection-tag expression examples, an error-path
callout, outputs table, and a live branching WorkflowPreview example
(CONDITION_ROUTE_WORKFLOW). FAQ kept. pageType: reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): restore Best Practices + multi-example workflows on Condition

Recalibration: reference pages keep genuine substance (Best Practices, every
distinct example), cutting only redundancy and verbose register. Restores the
Best Practices section and turns the three use cases into three rendered
WorkflowPreview examples (route by priority, moderate content, branch
onboarding). Adds CONDITION_MODERATE_WORKFLOW and CONDITION_ONBOARD_WORKFLOW.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): restore Best Practices on Agent reference

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): restore Best Practices on API reference

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): rewrite Function reference to match the current block

Fixed the verbose register and dropped the duplicated outputs section + the
stale Python screenshot/TODO, while keeping the real substance: JS vs Python
(local vs E2B sandbox), the large-inputs sim.files/sim.values helpers, the
worked loyalty-score example, and Best Practices. The use cases are now two
rendered WorkflowPreview examples (reshape an API response, validate input).
Adds FUNCTION_RESHAPE_WORKFLOW and FUNCTION_VALIDATE_WORKFLOW. pageType: reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): rewrite Router reference to match the current block

Cleaned the register, generalized the drifting model list, and folded the
Router-vs-Condition guidance into a callout. Kept the substance (routes as
output ports, NO_MATCH error path, all seven outputs, Best Practices, FAQ). The
three same-shape use cases collapse to one rendered triage WorkflowPreview
(ROUTER_TRIAGE_WORKFLOW), which the prose notes stands for the pattern.
pageType: reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): restore the classify and lead-qual examples on Router

I wrongly folded two distinct Router scenarios into a note. Restored all three
as their own rendered WorkflowPreview examples: triage a support ticket,
classify feedback (to child workflows), qualify a lead (sales vs self-serve).
Adds ROUTER_CLASSIFY_WORKFLOW and ROUTER_LEAD_WORKFLOW. (Also exports
RESPONSE_API_WORKFLOW for the next page.)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): rewrite Response reference to match the current block

Cleaned the register and broadened "Variable References" to connection tags
(any output, not just workflow variables). Kept the substance: exit-point
semantics, Builder/Editor mode, status codes, headers, the parallel-branch
warning, Best Practices, FAQ. All three use cases are now rendered
WorkflowPreview examples (API endpoint, webhook ack, status-per-branch). Adds
RESPONSE_API/WEBHOOK/ERROR_WORKFLOW. pageType: reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): rewrite Variables reference to match the current block

Cleaned the register, corrected the outputs (each assignment is also exposed as
<variables.name>, not "no outputs"), and kept the substance: assignments
reference earlier outputs and current values, global <variable.name> access,
Best Practices, FAQ. Two use cases now render as WorkflowPreview examples (count
retries, hold config). Adds VARIABLES_RETRY_WORKFLOW and VARIABLES_CONFIG_WORKFLOW.
pageType: reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): rewrite Wait reference to match the current block

Corrected a real staleness: the block now has an Async mode that suspends the
run for minutes/hours/days (not a hard 10-minute cap), plus a resumeAt output.
Documents Wait Amount / Unit / Async, the sync-vs-async distinction, all three
outputs, Best Practices, and updated FAQ. Two rendered WorkflowPreview examples
(space out API calls, delayed follow-up). Adds WAIT_RATELIMIT_WORKFLOW and
WAIT_FOLLOWUP_WORKFLOW. pageType: reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): polish Credential reference (frontmatter, fold redundant tabs)

The page was already accurate to the block (Select/List operations, the outputs
tabs, the wiring steps). Light touch only: added description + pageType, made the
header consistent, and folded the two identical Gmail/Slack "how to wire" tabs
into one line. Examples stay as labeled flows + the List/ForEach screenshot,
since they use integration blocks and a Loop the WorkflowPreview can't render.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): render the shared-credential example + icon fallback for integrations

Addressing the gap: WorkflowPreview block nodes now fall back to the integration
icon map, so diagrams can show Gmail/Drive/Slack/etc. with their real glyphs, not
just core blocks. Renders the Credential "share one account across blocks" example
as a WorkflowPreview (CREDENTIAL_SHARE_WORKFLOW). The multi-account and
List+ForEach examples stay as labeled flows + screenshot (the latter uses a Loop
container the preview can't render). Also exports EVALUATOR_GATE_WORKFLOW for the
next page.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): rewrite Evaluator reference to match the current block

Cleaned the register, generalized the drifting model list, and documented the
per-metric outputs (<evaluator.metricname>), which the page omitted. Kept the
substance (metrics with name/description/range, structured-output guarantee,
Best Practices, FAQ). The quality-gate example renders as a WorkflowPreview;
the same shape covers the parallel-variations and support-QC patterns, noted in
prose. pageType: reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): render the Credential route-by-logic example too

The icon fallback unblocked it: the "route to a different account by logic"
example now renders as a WorkflowPreview (CREDENTIAL_ROUTE_WORKFLOW), a Condition
selecting a production vs staging credential. The List + ForEach example stays a
screenshot because it nests blocks in a Loop container the flat WorkflowPreview
can't represent.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): render Guardrails examples + light accuracy pass

Kept the full substance (four validation types, PII entity/language detail,
the PII screenshot and video, outputs, Best Practices, FAQ). Light fixes:
frontmatter, and generalized the drifting model names (GPT-4o / Claude 3.7) to
"a strong reasoning model" with the current default. The three use cases now
render as WorkflowPreview examples (validate JSON, check grounding, block PII).
Adds GUARDRAILS_JSON/HALLUCINATION/PII_WORKFLOW. pageType: reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): render Human-in-the-Loop examples + frontmatter

Kept all the substance (Display Data, Notification, Resume Form, the Approval
Methods and API Execute Behavior tabs, outputs, the paused/resume example).
Added frontmatter and rendered the use cases as WorkflowPreview examples
(approve before publish, two-stage approval, verify extracted data); Quality
Control folds into the approval note as the same approve-then-act shape. Adds
HITL_APPROVAL/MULTISTAGE/VALIDATE_WORKFLOW. pageType: reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): render Webhook examples + frontmatter

The page was already accurate (Webhook URL/Payload/Signing Secret/Headers, the
automatic-headers table, HMAC details, outputs, POST-only callout, FAQ). Added
frontmatter and rendered the two use cases as WorkflowPreview examples (notify a
service, fire on a check). Adds WEBHOOK_NOTIFY_WORKFLOW and
WEBHOOK_TRIGGER_WORKFLOW. pageType: reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): add example + pageType to Workflow block reference

The page was already accurate and well-structured (Configure It, outputs,
deployment-status badge, execution notes, FAQ). Added pageType: reference and a
rendered WorkflowPreview example showing a parent calling the child workflow
enrich-lead and reading its result. Adds WORKFLOW_CALL_WORKFLOW.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): container rendering for Loop/Parallel + render the Loop example

Adds subflow/container support to WorkflowPreview, modeled on the app's
subflow-node.tsx: a solid-bordered box with a header (icon + name), an internal
"Start" pill whose handle feeds the first nested block, and target/source
handles at the vertical center. PreviewBlock gains size/parentId; edges gain an
optional sourceHandle; nodes render nested children via React Flow parentNode.
Renders the Loop reference's ForEach example (LOOP_WORKFLOW) and keeps the four
loop-type sections + inside/outside referencing + caps. pageType: reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): fix the Loop container's Start-pill connector

The Start pill -> first-block edge wasn't rendering: it was a React Flow
parent->child edge (unreliable), and the opaque container body hid it. Nested
blocks now render as absolute-positioned top-level nodes (container below at
zIndex 0, blocks above at zIndex 1), so the connector is an ordinary edge, and
the container body is see-through so it's visible.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): render the Parallel example + frontmatter (last core block)

Reuses the container rendering for the Parallel reference. Kept all substance
(count/collection types, inside/outside referencing, batch size of 20, instance
isolation, the Parallel-vs-Loop table, Best Practices, FAQ). Added frontmatter
and a rendered container WorkflowPreview (PARALLEL_WORKFLOW: distribute tasks,
call concurrently, aggregate <parallel.results>); the two use cases stay as
labeled flows. Adds PARALLEL_WORKFLOW. pageType: reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): prose glow-up for Guardrails to match the agent/condition voice

Rewrote the listy register (**Use Cases:** / **How It Works:** / **Configuration:**
scaffolding, "Use this when you need to..." filler) into the plain builder voice,
matching the depth of the Agent/Condition/Function rewrites. Kept every
validation type, option, range, the full PII entity/region list, the screenshot
and video, the outputs table, the rendered examples, Best Practices, and FAQ.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): prose glow-up for Loop to match the agent/condition voice

Rewrote into the plain builder voice and cut the filler: dropped the "Use this
when you need to..." lines and the ASCII "Example: Iteration 1, 2, 3" pseudo-code,
and folded the duplicated Inputs/Outputs tabs into Configuration + Referencing
sections. Kept all four loop types with their screenshots, the inside/outside
reference rules, the 1,000-iteration cap, sequential-vs-parallel guidance, the
rendered example, and FAQ.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): prose glow-up for Parallel to match the agent/condition voice

Same treatment as Loop: plain builder voice, dropped the ASCII pseudo-code and
the duplicated Inputs/Outputs tabs, folded the verbose Advanced Features into
tight Configuration + Referencing sections. Kept both types with screenshots,
the batch-size-of-20 cap, instance isolation, large-result indexing, the
Parallel-vs-Loop table, the rendered example, and FAQ.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): prose glow-up for Human-in-the-Loop

Tightened the register: folded the pause sentence into the intro, made the
section headers consistent (Configuration, Outputs), converted the bold-list
Block Outputs into a table, condensed the Notification channel bullets to a
line, and renamed the second "Example" so it no longer collides with the
rendered Examples. Kept all the substance — Display Data / Notification / Resume
Form, the Approval Methods and API Execute Behavior tabs, the portal video, and FAQ.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): re-enrich Loop prose (fuller, explanatory — not terse)

The first glow-up overcorrected into terse fragments. Restored proper
docs-quality prose at the Agent/Condition level: each loop type now explains
what it does, when to use it, and the relevant reference; Configuration,
Referencing, nesting, and Best Practices give context and the "why," not just
bullets. Same substance, readable depth.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): re-balance Parallel prose to the Agent/Condition register

Calibrated to the level signed off on elsewhere: each concept explained in a
couple of clear sentences with a concrete detail — informative, not terse, not
padded. Kept both types with screenshots, batch-size cap, isolation, large-result
indexing, the Parallel-vs-Loop table, the rendered example, and FAQ.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): restore the Notification channel detail on HITL

The glow-up over-compressed: it flattened the five notification channels (each
with what they do) into one sentence. Restored them as a list in plain voice —
tightening register shouldn't drop genuinely useful reference detail.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): builder-voice polish on the Credential intro

Light touch only — the page was already well-structured and explanatory, so just
led the intro with what the block does (and bolded the name) to match the other
references. No content changed elsewhere.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(triggers): rewrite Start trigger in the builder voice

Tightened the register, swapped the <code>&lt;&gt;</code> noise for backticks,
added pageType + an outputs table, and kept all substance: Input Format types,
chat-only outputs (input/conversationId/files), the editor/API/chat tabs, and
best practices.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(triggers): rewrite Schedule trigger in the builder voice

Plain voice and clean markdown (dropped the raw <ul>/<div> lists). Kept all
substance: simple intervals, cron examples, timezone, deploy-tied activation,
the 100-failure auto-disable, and FAQ. Added pageType.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(triggers): refocus Webhook trigger on the generic (native) trigger

Rewrote in the builder voice and separated out the integration content: the
page now documents the generic Webhook trigger (URL, Input Format, auth, custom
response, outputs, dedup/rate-limit/deploy/no-auto-disable). The "trigger mode
for service blocks" section is reduced to a short pointer + the demo video, and
the long supported-services catalog and vague use-case bullets are dropped in
favor of the Triggers index. Fixed the title (Webhook) and added pageType.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(triggers): builder-voice glow-up for RSS

Light pass: added pageType + description, tightened the intro, and presented the
output fields as an <rss.*> outputs table. Kept the polling config, use cases,
the published-after-save callout, and the FAQ (poll cadence, dedup, 25-item cap,
auto-disable, Atom support).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(triggers): rewrite Table trigger off the auto-generated card

Replaced the BlockInfoCard/'provides 1 trigger' auto-gen format with a real
builder-voice page: a spec-driven BlockPreview hero (added a 'table' spec),
plain-language Configuration (table, event type, watch columns, include
headers), and a full <table.*> outputs table. pageType: reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(triggers): frame the index around native triggers + separate the catalog

Reframed "generic" as native (no connected account) and promoted RSS and Table
into the native set alongside Start/Schedule/Webhook — cards, comparison table,
and integration paragraph updated to match. In the sidebar, grouped the five
native triggers under a "Native triggers" header and divided the ~44 service
triggers under "Integration triggers" (nav-only — no files moved, URLs stable;
the move to integrations/ is a later, separate change).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: promote Core Blocks + Core Triggers into the Workflows area

Restructured the Documentation sidebar (meta-only — no files moved, URLs stable):
after Deployment, the 16 core block pages now live under a "Core Blocks" section
and the 5 native trigger pages under "Core Triggers", instead of buried in the
bottom Reference catalog. Removed the now-redundant blocks tree from Reference,
and retitled the Reference triggers tree "Integration triggers" so it holds just
the service catalog (the native ones are promoted up top).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: merge block/trigger overviews into the Workflows overview; Core accordions

Restructured the sidebar and overview hub (meta + content only, no integration
files moved):

- Folded the /blocks and /triggers overview pages into /workflows: the overview
  now carries the core-block catalog (do work / direct flow / shape run), the
  Integrations-and-triggers families framing, the native + integration trigger
  framing, the trigger comparison, manual-run priority, and email-polling groups.
  Deleted blocks/index.mdx and triggers/index.mdx as redundant.
- Promoted the 16 core blocks into a "Core Blocks" folder accordion and the
  native triggers into a "Core Triggers" accordion, both under Workflows after
  Deployment. Integration triggers stay inside Core Triggers under a labeled
  divider, temporary until they move to integrations/<service> (tabs) later.
- Repointed every /blocks and /triggers index link to the /workflows#blocks and
  /workflows#triggers sections.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: split integration triggers into their own Reference accordion

Core Triggers is now the 5 native triggers only. Moved the 43 service triggers
out of triggers/ into a new integration-triggers/ folder, surfaced as an
"Integration triggers" accordion under Reference (an accordion must be its own
folder in Fumadocs). In Workflows, Core Triggers now sits before Core Blocks.
URLs: /triggers/<service> -> /integration-triggers/<service> (native /triggers/*
unchanged); the integrations/<service> tabbed-page migration remains the later step.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(workflows): trim the overview back to an introduction

It had drifted from a concept intro into a catalog. Kept the spine (the four
parts with their previews, how-it-runs, workflows-in-context) and compressed the
merged-in material: the full 16-block enumeration becomes a three-kind taxonomy
with examples, the trigger section a short native/integration framing. Cut the
anxious in-between — manual-run trigger priority, the niche email-polling-groups
feature (belongs on the Gmail/Outlook trigger pages), the redundant block-def
line, the Start-outputs callout half, the connections video, and the catalog-y
FAQ items. Dropped the unused Video import.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: relocate email-polling + trigger-priority out of the overview

Moved the two bits cut from the workflows overview to durable, generator-safe
homes: email-polling groups -> the Integrations (connecting accounts) page;
manual-run trigger priority -> the Start trigger page. Also added 'table' to the
generator's HANDWRITTEN_TRIGGER_DOCS / SKIP_TRIGGER_PROVIDERS so the hand-written
Table trigger page is no longer overwritten by generate-docs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(docs-gen): emit per-service integration pages (actions + Trigger section)

Rewrites the generator to output one page per service under integrations/
instead of split tools/ + triggers/. Block pass writes the service's actions;
trigger pass appends a '## Triggers' section (badged) to the same page, or writes
a standalone page for trigger-only services. Meta is written after both passes;
hand-written integration pages are preserved; docsUrl repointed to /integrations.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(docs): unify tools + triggers into per-service /integrations pages

Encodes the ontology "everything is a block; some blocks are triggers." The
generator now emits one page per service under integrations/ — the service's
Actions plus, when it has one, a Triggers section on the same page — replacing
the split tools/<service> + triggers/<service>. No "Tools" terminology.

- generate-docs.ts: output to integrations/, merge trigger sections into each
  service page (standalone for trigger-only services), Actions heading, table
  block now generated, docsUrl -> /integrations, hand-written pages preserved.
- Nuked tools/ (213) and the interim integration-triggers/ (43); moved the
  custom-tools guide to building-agents/; knowledge/memory/file/table links and
  meta repointed to /integrations.
- Sidebar: integrations catalog now under Reference (was tools); removed the
  Workspaces integrations entry and the integration-triggers tree.
- block-icons: wait uses lucide Clock (the generated icons.tsx no longer carries
  a hand-added WaitIcon). Landing integrations data regenerated.

No redirects (fresh start). Native Core Blocks/Core Triggers unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(docs): recover the hand-written manual-content intros on integration pages

The tools->integrations relocation generated fresh pages, so the generator never
saw the old tools/<service>.mdx to preserve its {/* MANUAL-CONTENT */} sections —
198 curated intros (AgentMail, etc.) were dropped. Reseeded each integrations
page from the pre-move tools page in git, re-ran the generator (which now merges
the manual intro into the new Actions/Triggers format), and repointed /tools/
links inside the recovered prose.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(scripts): rewrite the generator README for the integrations model

Brings scripts/README.md current: integration pages are derived from the
apps/sim block/tool/trigger registry (canonical-sources map), the golden rule
not to hand-edit generated pages, the MANUAL-CONTENT escape hatch, which pages
are hand-written/skipped, and the icons.tsx-overwrite gotcha.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: regenerate integration docs from staging-synced apps/sim

After merging staging, regenerated so the integration pages reflect current
source: correct block colors/configs (e.g. Gmail #FFFFFF), the new integrations
(sendblue, millionverifier, neverbounce, zerobounce), and staging's icon set.
Pages for integrations staging hid are removed; manual-content intros preserved.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(docs-gen): don't let stale-doc cleanup delete hand-written integration pages

Staging's cleanupStaleToolDocs removes any integrations/*.mdx that isn't a visible
tools block — it only guarded `index`, so it deleted the hand-written
google/atlassian service-account pages. Now guards all HANDWRITTEN_INTEGRATION_DOCS.
Restored the two pages, and repointed /integrations/file links to /files (staging
hides the file block, so it has no integration page).

Note: staging recategorized a2a/mysql/postgresql tools -> 'blocks' (and hid file),
so they correctly drop out of the integration catalog and are currently
undocumented — an IA decision to revisit.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(docs-gen): stop cleanup/writer filter mismatch from eating manual content

Comprehensive-review findings, all generator-consistency bugs:
- cleanup used staging's isIntegrationBlock while the writer kept the legacy
  filter, so integrations/{knowledge,memory,table}.mdx were deleted then
  regenerated without their manual intros every run. Both now honor a shared
  NATIVE_RESOURCE_BLOCK_TYPES set; intros reseeded.
- Trigger-only services (imap, circleback; category 'triggers') were likewise
  deleted each run; the canonical set now includes visible trigger-category
  blocks, the standalone writer preserves manual content, and their intros are
  reseeded.
- Mapped jsm -> jira_service_management, so JSM triggers merge into the JSM
  integration page instead of an orphan jsm.mdx (removed).
- Repointed lingering bare /tools links to /integrations; added missing
  pageType to integrations/index and building-agents/custom-tools.
Double-regen is now churn-free (idempotent) with all manual content intact.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(docs): recover staging's enriched Table doc + never drop manual content

The merge resolution deleted staging's relocated blocks/table.mdx, which carried
substantial enrichment our integrations/table.mdx (reseeded from the older
tools/ version) lacked: Creating Tables (column types/constraints), Filter
Operators, Combining Filters, Sort Specification, Built-in Columns, Limits, and
Notes. Recomposed integrations/table.mdx with that content — Creating Tables
inside the intro manual section, the reference tail in a notes manual section.

Generator fix uncovered en route: a manual section whose insertion anchor is
missing in the generated markdown (e.g. notes with no "## Notes" heading) was
silently dropped on regen. Unplaceable sections now append at the end instead —
manual content is never lost. Verified idempotent across double regeneration.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(workspaces): de-philosophize the fundamentals prose

Rewrote in the plain register of the workflows overview: 'draws the boundary
for access' / 'Nothing crosses the boundary' / 'follow the same edge' become
direct statements (only members can access it; a workflow in one workspace
cannot read a table in another). '## The boundary' is now '## Access and
isolation'. All substance kept: every resource type, permission levels,
personal/organization/grandfathered kinds, deployments callout, VISUAL markers.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(docs): restore #blocks and #triggers anchors on the workflows overview

The editorial trim renamed '## Blocks' -> '## Kinds of blocks' and
'## Triggers' -> '## How a workflow starts', silently breaking the ten
/workflows#blocks and /workflows#triggers anchor links pointed there when the
old index pages were folded in. Pinned the original ids with explicit heading
anchors. Found by the comparative prose review.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: restore the genuinely useful reference bits the rewrite dropped

From the comparative prose review, restored in guidance register (no spec
dumps): temperature tiers on Agent (low/middle/high with ranges), loop/parallel
iteration references in the variables syntax-at-a-glance table, and a short
"Test it" section on the Webhook trigger (curl + check the run in Logs). The
fourth flagged loss (tag-resolver mechanics on connections) turned out to be
already covered — name normalization, case-sensitive paths, missing-output
behavior, and value formatting are all on the page; only the internal resolver
precedence chain was dropped, deliberately.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): rework the Agent intro — encyclopedia register

Replaced the flat opening with a denser, factual one (no metaphor): what the
block does, and its centrality stated as fact — 'Most workflows are built
around one or more Agent blocks.' The agent-vs-Agent-block disambiguation moves
from an info callout into a second paragraph on the block's role in building
agents. Dropped the now-unused Callout import.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(integrations): add the HubSpot setup guide for the Marketplace listing

Addresses HubSpot Marketplace review item A1: a public, HubSpot-specific setup
guide following their template — what the app does, install + connect through
the current flow (sidebar Integrations page -> HubSpot -> Add to Sim -> connect
dialog -> HubSpot OAuth), with real screenshots of each step and a placeholder
for the scope-approval shot; configure in a workflow (one-click skills/templates
+ the HubSpot block + trigger mode), use, disconnect (with data consequences),
uninstall from the HubSpot side, troubleshooting. Capability wording is by CRM
object rather than scope enumeration, so it stays accurate after the A2 scope
trim. Lives at /integrations/hubspot-setup, guarded as hand-written,
cross-linked from the HubSpot reference page's intro.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(integrations): rewrite the Integrations guide for the sidebar flow

Integrations moved out of Settings to a top-level sidebar page. Rewrote the
guide to the current journey: the Integrations page (Connected/Featured/search),
service pages with one-click skills and templates, + Add to Sim -> connect
dialog (display name + permissions) -> provider OAuth. Replaced the four
Settings-era screenshots with current captures (connect dialog illustrated via
HubSpot); block-side screenshots (account selector, manual credential ID) kept;
one VISUAL marker for the connection detail view pending a fresh capture.
Members/roles, credential-ID, reconnect/disconnect, email polling, and FAQ
substance unchanged apart from navigation.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: move Building agents directly after Workflows in the sidebar

The agent-building journey follows straight from workflows (blocks, triggers,
deployment) rather than after the tour of every resource type. Tables/Files/
Knowledge Bases/Logs now follow it. Meta-only reorder.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: fill the visual slots coverable by existing components

Six VISUAL markers filled with no new captures needed:
- building-agents overview: rendered the minimal lead-scoring agent
  (Start -> Agent with tool chips -> Response, Agent highlighted) as a
  WorkflowPreview (BUILD_AGENT_WORKFLOW)
- files guide: the read -> summarize -> write chain as a WorkflowPreview
  (FILE_SUMMARY_WORKFLOW)
- tables guide: the query -> classify -> write-back roundtrip as a
  WorkflowPreview (TABLE_ROUNDTRIP_WORKFLOW)
- choosing guide: the six-kind comparison grid as a markdown table
- knowledgebase guide: the Knowledge block's output as an OutputBundle
- workspace fundamentals: removed a duplicate nesting-diagram marker

42 -> 39 VISUAL markers remaining (screenshots + designed diagrams).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(components): run-inspector OutputBundle + lightbox with block inspector

Two visual-component upgrades, both mirroring the real app:

- OutputBundle is now a miniature of the run inspector: a Logs column (block
  rows with icon chips and durations, source selected) beside the Output panel's
  typed tree — keys with the app's type-badge semantics (string green, number
  blue, object gray, array purple, boolean orange), chevrons, indent guides,
  primitive values. Styling lifted from the terminal's structured-output.
  Dropped the "Read one value by name" footer (the prose teaches the tag).
  The three usages (data-flow, tables, knowledgebase) get real typed trees;
  data-flow's stale purple/gpt-4o example corrected en route.

- WorkflowPreview gains a lightbox + read-only block inspector: clicking a
  block (or the expand control) opens a 92vw/86vh overlay with zoom and pan,
  and a right-hand inspector panel showing the selected block's full
  configuration — canvas rows truncate, the inspector doesn't. Fields render as
  app-style controls (dropdown/textarea/input by heuristic) with dashed
  dividers, tool chips, and a Connections footer computed from the edges.
  Selection rings without dimming (new selectedBlock option in workflow-data).
  Esc/backdrop closes; body scroll locks while open.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: regenerate after staging merge — AppConfig joins integrations/

Staging's new AWS AppConfig integration (#4928) generated its docs into the old
tools/ layout; re-homed to integrations/appconfig.mdx (Actions heading, meta
entry) via the generator. tools/ stays deleted.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: redirect the retired tools/ and trigger URLs to integrations/

Revises the earlier fresh-start call: /tools/* are ~200 live, indexed URLs
referenced by deployed app versions' docsLink fields and marketplace listings,
so dropping them cold would 404 from the live product. next.config now 308s:
- /tools -> /integrations, /tools/:slug -> /integrations/:slug
  (custom-tools -> building-agents/custom-tools first)
- old /triggers/<service> -> /integrations/<service>, enumerated so the native
  trigger pages keep resolving; provider-slug mappings for jsm and the
  hyphenated Google/Microsoft slugs
- /blocks and /triggers index URLs -> the workflows overview anchors
Verified every class + native passthroughs against the dev server. Spec updated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(getting-started): rewrite — current UI, cut the post-tutorial padding

The last old-guard page. Accuracy: Agent config now uses Messages (System/User
message) instead of the removed System Prompt/User Prompt fields, the default
model instead of GPT-4o, the banned 'no-code' phrasing is gone, the deploy card
points at /deployment, and frontmatter gets description + pageType. Weight: cut
the 'What You've Built' checklist, the 'Key Concepts You Learned' re-teach
section, the duplicate 'Resources' links, the Start-block hand-holding, and ten
dead icon imports; tightened every step preamble. 203 -> 113 lines with the
full 5-step tutorial, videos, and FAQ intact. (Videos still show the old UI
until the re-recording pass.)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: de-fluff the Tier-1 heavy pages (logging, mcp, passing-files, permissions)

From the exhaustive fluff audit, keeping all substance:
- logging: merged the duplicated Console/Logs-page structure, snapshot concept
  stated once instead of three times, cut the generic Best Practices, trivial
  tab walkthrough condensed. Frontmatter added.
- mcp: intro + "What is MCP?" generic bullets folded into two sentences, cut
  the Common Use Cases catalog and the verify-your-config Troubleshooting
  checklists, merged the twice-stated Refresh behavior, security kept as one
  real warning.
- passing-files: marketing opener replaced with a factual lead, fixed the stale
  retired-Vision-block reference (now Agent with a vision model), dropped the
  FAQ item that restated the block catalog verbatim.
- permissions: heading-restating intro replaced with the two-layer model, cut
  the three "Perfect for: stakeholders..." persona lines and the generic Best
  Practices section, dropped the FAQ restating the limits table.
- connectors: audit over-flagged it — the categorized support matrix, API-key
  table, and config examples are genuine reference; frontmatter only.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: tier-2 fluff trims (costs, enterprise, mailer, skills)

Conservative sweep from the audit, unambiguous cuts only: the costs CYA opener
and formula restatement, the enterprise marketing intro (now a functional
summary), mailer's restated convenience line and chat-upload comparison, and
skills' third restatement of progressive disclosure. Audit flags screened out
as misfires: mothership/tasks (immediate-vs-scheduled are two facts, not a
duplicate), self-hosting telemetry (real sizing data), and the recently
approved credential/HITL/workflow-block/trigger pages.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(skills): update to the Skills tab on the Integrations page + document import

Skills moved again — they now live on the Integrations page's Skills tab in the
workspace sidebar (the doc said "Open the Skills page"). Updated the create flow
(+ Add to Sim -> Add Skill dialog) with fresh screenshots of the tab and both
dialog tabs, and documented the previously-missing Import flow: upload a .md
with YAML frontmatter or a .zip containing SKILL.md, fetch from a GitHub URL, or
paste SKILL.md content (verified against the import route/component; name 64 /
description 1024 limits verified against the contract). Noted the curated
skills suggested on integration pages, cross-linked the Skills tab from the
Integrations guide, and refreshed the location FAQ. Mechanics (progressive
disclosure, load_skill, agent-block attachment) unchanged and still accurate.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(building-agents): render the lead-scorer running example on choosing

The page narrated its running example through six sections without ever showing
it. Authored LEAD_SCORER_WORKFLOW (Start -> Enrich workflow-as-tool -> Function
reshape -> Agent with Search/Send Email/CRM tool chips -> Google Sheets append)
and rendered it after the intro, with highlightBlock re-renders in the three
sections that map to a node (deterministic block -> the Sheets append, agent
tool -> the Agent, workflow-as-tool -> Enrich) — the same pattern as the
workflows overview.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(tables): rewrite workflow columns around the real lead-scoring example

Rebuilt the page on the ai_startup_customers screenshots instead of captioning
them onto the old hypothetical: one running example throughout — Company Domain
fills domain, Company Info reads it into employee_count/description, Lead Score
Enrichment writes lead_score/priority/score_reasoning. Every section now
describes the actual UI: the grid with group headers, per-row run buttons, and
the 21-running toolbar; the Configure workflow panel (picker, column inputs,
output selection, Auto-run, Run after); the Company Info input/output mapping;
Not found cells explained where the screenshot shows them; the cascade section
describes the example itself. All placeholder markers on the page resolved.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: regenerate after staging merge — Slack trigger update + file block re-visible

Staging's mothership v0.2 (#4923) expanded the Slack trigger payload
(interactivity, slash commands: event_type, command, action_id/value/actions,
response_url, trigger_id, callback_id, ...) — regenerated so it lands on the
unified integrations/slack page; the old-layout triggers/slack.mdx from
staging's generator was dropped in the merge. The file block is visible again
upstream, so integrations/file.mdx is back in the catalog.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(tables): playbook prose pass on workflow columns + restore File block links

Workflow columns, against the docs-writing playbook: killed the banned
'Term — desc' bullets in the Configure list (term + verb form), restored the one
universal analog (spreadsheet macro), fixed the clipped 'On,/Off,' fragments,
replaced an invented <start.companyDomain> tag with the verified description,
and thinned em-dashes to four page-wide with no clustering. Also repointed
[File] block mentions back to /integrations/file now that the page exists again
(FileV5 is visible upstream); the Files-store links stay on /files.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(tables): per-row execution inspection on workflow columns

Two new captures: the cell menu (View execution, Re-run cell, row actions) and
the Log Details trace for a single row's run. New 'Inspecting a row's run'
section ties cell values to real, traceable runs; corrected the re-run guidance
now that Re-run cell exists (the page previously said Run all rows was the only
way to retry).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(workflows): drop the confusing 'order by hand' sentence

'You never set the order by hand' read wrong (wiring connections is setting it
by hand), and the replacement was over-explanation. The first sentence already
carries it: Sim works out the order from the connections.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(workflows): fix the over-claim about independent blocks

'Two blocks that don't depend on each other run at the same time' is wrong —
independent blocks at different depths run at different times. Concurrency
follows from readiness, not independence: blocks whose dependencies have all
finished run together. Reworded to say that, tied to the image's two agents.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(workflows): accuracy audit of how-it-runs against the executor

Verified every claim on the page against apps/sim/executor. One claim was
materially false: "a failed block stops its own path but leaves independent
paths running" — in the engine, an unhandled block failure sets the error flag
and stops scheduling entirely (in-flight blocks finish, nothing new starts);
only a connected error port routes the failure and keeps the run alive. Now
says that. Two imprecisions tightened: a join waits for every feeder *that is
going to run* (deactivated-branch feeders don't hold it up, per the
edge-manager cascade), and Loop also repeats while a condition holds. Confirmed
accurate: per-block readiness scheduling (readyQueue + race, not layers),
branch-skip cascade and empty tags, the 25-hop call-chain cap.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(logs): real captures on the overview + prose matched to the UI

The logs-debugging overview had six visual placeholders and no visuals. Three
real captures placed: the workspace Logs page as the hero (rows with status,
credits, trigger, duration), Log Details' Trace tab at the blocks section (the
CRM sync run's spans, with a one-line read of where the time went), and the
editor's live run console at the input/output section. Prose corrected to what
the UI shows: cost is in credits, failed runs are badged Error (dropped the
five-state enum the list doesn't display), and the Trace tab is named. The
row-anatomy marker is covered by the hero; the two designed-diagram markers
(debug-loop flowchart, failed-vs-success comparison) remain.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(workflows): one reference syntax, named sources — untangle variables vs connection tags

An exhaustive sweep of "connection tag" found the docs asserting both that a
workflow variable is a connection tag (response.mdx used it as the umbrella for
all angle-bracket references) and that it isn't (variables.mdx). Ruled the
narrow definition canonical — a connection tag reads a block's output; the name
follows the connection — and restructured around the real model:

- variables.mdx: new "One syntax, named sources" section states that everything
  in angle brackets is one mechanism whose first segment names the source, with
  the load-bearing fact stated plainly: `variable` is literal, a connection tag
  starts with the block's own name. The syntax table drops the redundant
  dot-notation row, gets one row per source, and is ordered by resolution
  precedence with the order explained beneath it (absorbing the old Name
  conflicts section). The credentials pointer folds into the env-var section;
  trimmed the "never appears in outputs" overclaim.
- response.mdx: no longer calls a workflow variable a connection tag.
- connections.mdx: the owner page closes the loop — same syntax also reads
  variables and loop/parallel context; a connection tag is the block-output case.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(workflows): verify the reference model against the resolver; fix one imprecision

Checked every claim in the new 'One syntax, named sources' section against
apps/sim/executor/variables: resolver chain order is Loop -> Parallel ->
WorkflowVariables -> Env -> Block (matches the table); 'variable'/'loop'/
'parallel' are literal prefixes (REFERENCE.PREFIX); block names normalize via
toLowerCase + strip spaces; an unmatched reference is genuinely left in place
(resolver returns undefined -> the replacer emits the raw match). One claim
tightened: {{KEY}} is a different syntax and can never collide with
angle-bracket references, so the precedence sentence now scopes collisions to
the angle-bracket sources with a concrete example (a block named 'variable').

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(building-agents): workflow-as-tool is agent-decided, not the Workflow block

The choosing page defined workflow-as-tool as the Workflow block (path-decided),
contradicting its own name and the comparison table's premise. Verified against
the product: workflow_executor is an agent tool — you pick the workflow in the
Agent block's tool list, the model decides when to call it and supplies the
inputMapping (user-or-llm), inputs arrive at the child's Start trigger.

Rewritten agent-first: the section defines it as a workflow handed to an agent
as one callable tool, the lead scorer gains a Deep Enrich workflow tool chip on
the agent (diagram updated), and the deterministic Workflow block becomes the
explicit contrast in a callout — same child workflow, the difference is who
decides, mirroring the block/agent-tool contrast. Table row corrected to
"The agent"; the summary paragraph follows.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: theme-aware previews + enrichments vs workflow groups split

Light-mode support for every preview component (WorkflowPreview canvas, nodes,
containers, edges, lightbox, BlockPreview, OutputBundle, BlockInspector): a
wp-scope token block in the docs global stylesheet whose values mirror the OG
repository's globals.css in both modes (surfaces, borders, --workflow-edge,
text tiers, the --badge-* type-badge palette). Every hardcoded hex swapped to a
--wp-* var; brand colors, selection blue, and error red stay literal.

tables/workflow-columns: separated the two group kinds per the contract's
workflowGroupType enum ('manual' | 'enrichment'). New "Two kinds of groups"
section opens with the + New column menu capture (Enrichments above the types,
Workflow below); Enrichments documented from the code-defined registry (company
domain, company info, email verification, phone number, work email) including
the provider-cascade behavior that produces Not found cells; the Company Info
panel capture is now correctly labeled as an enrichment config; workflow groups
keep the Configure workflow panel. Shared machinery generalized under "How
groups run"; the cascade section names which stage is which kind; the two
portrait screenshots render smaller.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(tables): don't enumerate the enrichment catalog; don't assert a group's kind

Two corrections on workflow columns: the prose no longer lists the enrichment
catalog (growable, not procedurally tracked — it now describes the category and
points at the Enrichments panel; the provider-cascade/Not-found explanation
stays, it's behavior not catalog), and the page no longer asserts which kind
the example's Company Domain / Company Info groups are (Company Info may be a
user-built workflow, not the built-in). The input/output bindings capture moved
to "How groups run" as the kind-agnostic illustration; only Lead Score — whose
panel shows the workflow picker — is named as a workflow group.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(components): per-branch source handles — conditions and routers finally branch

WorkflowPreview's node only ever had one header source handle, so every
condition/router example fanned both edges out of a single point and never
showed the if/else rows the real canvas (and the BlockPreview hero specs)
render. PreviewBlock now supports `branches` (each rendered as a row with its
own right-edge source handle, id `branch-<id>`) and `showError` (red error
handle), mirroring the executor's per-branch condition-true/condition-false and
router-<route> handle model. A block with branches emits from them, not the
header.

Every affected example rewired (13 workflows): the three condition examples,
status-per-branch, credential routing, and the webhook-trigger check route
their edges through branch-if/branch-else with the expression on the If row and
an explicit else; the three router examples list their actual routes as branch
rows (Sales/Support/Billing, Product/Bug report, Enterprise/Self-serve); the
terminal gates (variables retry, evaluator gate, the three guardrails gates)
show dangling if/else branch rows like the canvas does.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(components): inspector shows branch rows

Moving condition expressions from rows into branches emptied the lightbox
inspector for condition/router blocks — it only mapped rows to fields. Branches
now map too: each branch renders as a field (If with its expression as code,
else as an empty control, router routes by name).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(components): branch handle ids match the app's workflow representation

Verified against the source after the branch-handles work: the canvas emits
condition-${cond.id} handles per condition row (workflow-block.tsx) and Router
V2 uses router-${routeId} port handles, and edges carry those ids as
sourceHandle — the docs' invented branch- prefix was a gratuitous divergence
that the planned fromWorkflowState() adapter would have had to translate. The
node now uses the authored branch id as the handle id directly, and every
example authors ids in the app's own scheme (condition-if/condition-else,
router-<route>), so example edges now match real workflow edges verbatim.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: agent skills mint /integrations/ docs links and describe the new output

The add-integration/add-block/validate-integration skills — what Claude Code
follows when integrations land on staging — still taught the old layout:
docsLink templates pointing at docs.sim.ai/tools/{service} and 'generates
tools/{service}.mdx'. Updated so that once this PR merges, the instructions on
staging produce the new way by themselves: /integrations/ docsLinks, the
per-service page description, and the don't-hand-edit/manual-content pointer.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(workflows): execution semantics, not simultaneity

The concurrency section drifted into 'run at the same time' framing across two
accuracy passes — but the semantics are non-blocking execution: a block starts
the moment its dependencies finish and waits on nothing else. Section retitled
'Blocks run as soon as they can', the rule stated in two plain sentences, the
duplicated pre-image example narration gone (the post-image caption carries it).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(workflows): errors are execution semantics — own section on how-it-runs

Failure behavior was buried inside 'Watching a run' (the live-UI section). Now
a first-class 'When a block fails' section in the execution story: an error
fails the run (in-flight blocks finish, nothing new starts) unless the block's
error port is connected, in which case the run follows the error path.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: data-driven additions from the platform-metrics read

Three targeted edits from the sim-internals analysis, each carrying an inline
{/* why */} provenance comment so future editorial passes know the data behind
it:

- workflows/how-it-runs gains "How long a run can take" — run timeouts are the
  only hard-error class provable at scale (2,415 five-minute timeouts in 14
  days); limits verified in lib/core/execution-limits/types.ts (5 min free /
  50 min paid sync, 90 min async, env-overridable).
- getting-started gains an "if the run doesn't go green" callout at the Test
  step — the largest funnel drop is created-workflow -> first-successful-run
  (92% -> 49%), and this is the stall point.
- function/api Best Practices: the existing error-path bullets get a guard
  comment (<1% of deployed workflows connect an error port — under-adopted,
  not under-needed) instead of duplicate bullets.
- visuals manifest: capture priority reordered by integration adoption
  (Sheets, Gmail, Telegram, WhatsApp, ...).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: regenerate after staging merge (integration validation batch + Gong tools)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: rename Building agents -> Agents; URLs match the settled IA

The section's pages now live where the sidebar says they do:
building-agents/ -> agents/, and the stray top-level /mcp and /skills fold in
as /agents/mcp and /agents/skills (they were always part of the agents story —
the URLs predated the IA settling). Sidebar section header is now "Agents",
link labels updated, and every old URL 308s: /building-agents(/*) -> /agents(/*),
/mcp, /skills, plus the existing capabilities/ and tools/custom-tools redirect
destinations retargeted. Verified: all five new pages render and every old-URL
class redirects correctly.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(workflows): connections gets its video, an FAQ, and accurate output examples

The reorg dropped two things from the old tags page that belonged on the
connections reference: the connections.mp4 walkthrough (restored after the
intro) and the FAQ (rebuilt in the robust JSX form — resolver order, name
normalization, env-var syntax pointer, didn't-run behavior, array indexing,
Function-block formatting; answers aligned with the since-verified resolver
facts, including unmatched-references-left-in-place).

Editorial/accuracy pass on the output-shape tabs while in there: stale gpt-4o
and gpt-5 examples now claude-sonnet-4-6, the Agent tokens shape corrected to
the verified { input, output, total } (the page contradicted blocks/agent), and
the dubious cost: [] line dropped — the example now matches the real run
inspector.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: regenerate after staging merge — sim trigger, enrichment + logs blocks, re-shown DB integrations

Staging's #4941 added the Sim workspace-event trigger (hand-written page adopted
into Core Triggers), the Enrichment and Logs blocks (category 'blocks' — added
to NATIVE_RESOURCE_BLOCK_TYPES so they live in the integrations catalog like
table/knowledge/memory), and re-categorized mysql/postgresql/sftp/smtp/ssh back
to visible tools (their pages return to the catalog). Generator sets merged as
the union of both sides (sim in HANDWRITTEN_TRIGGER_DOCS + SKIP_TRIGGER_PROVIDERS,
enrichment in the icon allowlist).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: regenerate after staging merge (CodePipeline); suppress sim trigger from catalog

The native Sim workspace-event trigger is documented at triggers/sim — the
block writer no longer emits an integrations page for it (skip + canonical-set
exclusion). CodePipeline (#4945) lands in the catalog in the Actions format.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(blocks): cross-link the Memory block from the Agent memory section

Final loss audit found the old page's pointer from built-in agent memory to the
standalone Memory block had been dropped; one line restores it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: URLs now mirror the sidebar — sections own their pages

Every page lives at a path matching its meta.json section, done now while none
of these URLs are publicly live (the last free window before merge):

- Workflows owns its accordions: /blocks/* -> /workflows/blocks/*,
  /triggers/{start,schedule,webhook,rss,table,sim} -> /workflows/triggers/*,
  /deployment/* -> /workflows/deployment/*
- Mothership owns Mailer: /mailer -> /mothership/mailer
- Workspaces & Access folds into Platform, sequenced concept-first with the
  reference tail last: /platform/{workspaces,organization,permissions,
  credentials,costs}, then platform/self-hosting/*, platform/enterprise/*
  (from /workspaces/fundamentals+organization, /permissions/roles-and-
  permissions, /credentials, /costs, /self-hosting/*, /enterprise/*)

All internal links swept (0 broken in a full-tree resolver sweep), root
meta.json repointed, and every previously-live URL 308s to its new home —
including retargeted destinations of existing redirects so chains stay
single-hop (verified: /execution/chat reaches /workflows/deployment/chat in
one hop), and the native-trigger rule ordered after the enumerated
integration-trigger redirects so /triggers/gmail still reaches
/integrations/gmail. Production build passes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: untrack .plans/ (local agent planning files)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(preview): tool chips use the EMCN ChipTag chrome

The canvas previews' tool chips were ad-hoc (5px radius, header surface, plain
border). The app's canonical chip chrome is the ChipTag family: 20px tall,
rounded-md, px-1, gap-1.5, --surface-5 light / --surface-4 dark with an inset
--border-1 ring and --text-body label. Mirrored those values into --wp-chip-*
tokens (both modes) and restyled the chip; the integration's brand-color icon
square stays, sized to the chip.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(blocks): one-time shift of all docsLinks to the new docs URLs

Block definitions are the patterns coding agents copy from, so redirects alone
leave new blocks minting dead conventions. Every docs.sim.ai link in apps/sim
now points at the final URL scheme: /tools/<slug> -> /integrations/<slug>
(433 links), /blocks/<core> -> /workflows/blocks/<core> (knowledge/enrichment/
logs -> /integrations/*), native /triggers/* -> /workflows/triggers/*,
/mcp -> /agents/mcp, /self-hosting + /enterprise -> /platform/*, plus the
llms.txt listings and the blocks.test.ts assertions.

Verified every rewritten target against the docs tree: all resolve except ten
hidden blocks (vision, spotify, thinking, tts...) and a2a whose links were
already dead pre-reorg — no regressions introduced.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: ignore .plans/ (local agent planning files)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(files): align every File-block claim with the shipped file_v5 block

Accuracy audit against apps/sim/blocks/blocks/file.ts (FileV5Block, the visible
block) and tools/file/*:

- The block has FIVE operations, not four — Get Content was missing entirely.
- Read outputs file objects only; the page claimed it also returned extracted
  text. Text comes from Get Content (contents, per file) or Fetch
  (combinedContent) — table, prose, and the Fetch callout corrected.
- Functions CAN read files: sim.files.readText/readBase64 exist in the sandbox
  (isolated-vm-worker.cjs), so "doesn't reach into workspace storage" is gone;
  the section now teaches Get Content text or sim.files on the file object.
- Workspace file IDs are wf_<shortId> (workspace-file-manager.ts:511), not f_.
- Stale "such as Claude or GPT-4o" vision parenthetical dropped.
- "File block reference" card pointed at /files (the section overview); now
  /integrations/file.
- FILE_SUMMARY example agent consumed <file.combinedContent>, which Read never
  produces — now binds the file object to the Files input.
- passing-files.mdx: combinedContent scoped to Fetch, contents documented.

Verified intact: Write's numeric-suffix collision behavior, Fetch's auth
headers, Append-by-name, and the file-object shape.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: keyboard-shortcuts audited against the command registry; cut legacy workspace detail

Every binding verified against commands-utils.ts (the global registry),
workflow.tsx, and table-grid.tsx. Three fixes: tables Mod+A (select all rows)
doesn't exist — the real bindings are Shift+Space (select row, was misworded
as a toggle) and the undocumented Mod+Space (select column); the global
Mod+Shift+A row conflated two commands — add-agent (Mod+Shift+A) and
add-workflow (Mod+Shift+P) are separate. All 29 other documented shortcuts
confirmed accurate, including tables clipboard (native copy/cut/paste events)
and Mod+Y redo (tables only — correctly absent from the workflow editor
section).

Also drops the grandfathered_shared workspace paragraph — internal billing
taxonomy, not something a reader can act on.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: apply Theodore's accuracy feedback

- getting-started: workflow creation is the + button next to Workflows in the
  sidebar (no "New Workflow" button exists); Exa/Linkup no longer need
  user-supplied API keys on hosted Sim (apiKey is hideWhenHosted in the Exa
  block) — step and FAQ updated.
- workflows overview: chat and API are entry points of the Start trigger, not
  separate triggers — the "swap in a chat/API trigger" sentence now matches
  triggers/start's own model.
- variables: names cannot contain periods — the resolver reads everything
  after the first dot as a path into the value (executor/variables/resolvers/
  workflow.ts splits on dots) — constraint now stated where name normalization
  is taught.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: Python sandbox package list (verified) + agent/agents cross-linking

Function block: the Python callout's "common packages like matplotlib" becomes
the actual package list, grouped by use. Sources verified 2026-06-10 and cited
in an inline provenance comment: E2B's code-interpreter template requirements
(the base Sim's mothership-shell template builds from) plus Sim's three pip
additions (awscli/yq/csvkit, per the copilot repo's template.ts via
sim-internals). Versions omitted so the list doesn't rot on routine bumps.

Agent surfaces deduplicated by direction: blocks/agent's Tools section now
links custom tools and MCP and points at the Agents concept page for tool
sourcing; agents/index drops its duplicated Auto/Force/None enumeration in
favor of the block reference, which owns config mechanics.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 18:39:57 -07:00

3785 lines
132 KiB
TypeScript
Executable File

#!/usr/bin/env ts-node
import fs from 'fs'
import path from 'path'
import { fileURLToPath, pathToFileURL } from 'url'
import { isVersionedType, stripVersionSuffix } from '@sim/utils/string'
import { glob } from 'glob'
import type { BlockCategory } from '../apps/sim/blocks/types'
import { IntegrationType } from '../apps/sim/blocks/types'
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/integrations')
const ICONS_PATH = path.join(rootDir, 'apps/sim/components/icons.tsx')
const DOCS_ICONS_PATH = path.join(rootDir, 'apps/docs/components/icons.tsx')
const INTEGRATIONS_DATA_PATH = path.join(rootDir, 'apps/sim/lib/integrations')
const LANDING_INTEGRATIONS_DATA_PATH = path.join(
rootDir,
'apps/sim/app/(landing)/integrations/data'
)
const TRIGGERS_PATH = path.join(rootDir, 'apps/sim/triggers')
// Integration triggers are merged into the same per-service page as the service's
// actions (one block per integration: actions + an optional Trigger).
const TRIGGER_DOCS_OUTPUT_PATH = DOCS_OUTPUT_PATH
/** Hand-written integration pages in DOCS_OUTPUT_PATH that the generator must never clobber. */
const HANDWRITTEN_INTEGRATION_DOCS = new Set([
'index',
'google-service-account',
'atlassian-service-account',
'hubspot-setup',
])
/**
* Native Sim resource blocks (category 'blocks') that still get a generated
* integration page. The writer's filter and the stale-doc cleanup must both
* honor this set, or cleanup deletes what the writer emits (losing manual content).
*/
const NATIVE_RESOURCE_BLOCK_TYPES = new Set(['memory', 'knowledge', 'table', 'enrichment', 'logs'])
/** Trigger doc pages that are hand-written and must never be overwritten. */
const HANDWRITTEN_TRIGGER_DOCS = new Set([
'index',
'start',
'schedule',
'webhook',
'rss',
'table',
'sim',
])
/** Providers whose docs are already covered by hand-written pages. */
const SKIP_TRIGGER_PROVIDERS = new Set(['generic', 'rss', 'table', 'sim'])
/**
* Maps trigger provider names (from TriggerConfig.provider) to their
* corresponding block type when the two differ. Used to resolve icon
* colours from the block registry.
*/
const PROVIDER_TO_BLOCK_TYPE: Record<string, string> = {
'microsoft-teams': 'microsoft_teams',
'google-calendar': 'google_calendar',
'google-drive': 'google_drive',
'google-sheets': 'google_sheets',
jsm: 'jira_service_management',
}
/** Human-readable display names for trigger providers. */
const TRIGGER_PROVIDER_DISPLAY_NAMES: Record<string, string> = {
airtable: 'Airtable',
ashby: 'Ashby',
attio: 'Attio',
calcom: 'Cal.com',
calendly: 'Calendly',
circleback: 'Circleback',
confluence: 'Confluence',
fathom: 'Fathom',
fireflies: 'Fireflies',
github: 'GitHub',
gmail: 'Gmail',
gong: 'Gong',
'google-calendar': 'Google Calendar',
'google-drive': 'Google Drive',
'google-sheets': 'Google Sheets',
google_forms: 'Google Forms',
grain: 'Grain',
greenhouse: 'Greenhouse',
hubspot: 'HubSpot',
imap: 'IMAP',
intercom: 'Intercom',
jira: 'Jira',
lemlist: 'Lemlist',
linear: 'Linear',
'microsoft-teams': 'Microsoft Teams',
notion: 'Notion',
outlook: 'Outlook',
resend: 'Resend',
salesforce: 'Salesforce',
servicenow: 'ServiceNow',
slack: 'Slack',
stripe: 'Stripe',
telegram: 'Telegram',
twilio_voice: 'Twilio Voice',
typeform: 'Typeform',
vercel: 'Vercel',
webflow: 'Webflow',
whatsapp: 'WhatsApp',
zoom: 'Zoom',
}
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 })
}
/** Runtime set of valid `IntegrationType` values, derived from the canonical enum. */
const INTEGRATION_CATEGORY_VALUES: ReadonlySet<IntegrationType> = new Set(
Object.values(IntegrationType)
)
/**
* Defensive shape for blocks parsed out of source files. Fields stay loose
* (`string`) so the AST-style extractor can populate them progressively; the
* canonical taxonomy is enforced at the JSON-write boundary inside
* `writeIntegrationsJson`.
*/
interface BlockConfig {
type: string
name: string
description: string
longDescription?: string
category: string
integrationType?: string
bgColor?: string
outputs?: Record<string, any>
tools?: {
access?: string[]
}
operations?: OperationInfo[]
docsLink?: string
[key: string]: any
}
/**
* Find the position after the matching close delimiter for an opening delimiter.
* Assumes `content[openPos]` is the opening char (e.g. `{` or `[`).
* Returns the index one past the matching close char, or -1 if unbalanced.
*/
function findMatchingClose(
content: string,
openPos: number,
openChar = '{',
closeChar = '}'
): number {
let count = 1
let pos = openPos + 1
while (pos < content.length && count > 0) {
if (content[pos] === openChar) count++
else if (content[pos] === closeChar) count--
pos++
}
return count === 0 ? pos : -1
}
interface TriggerInfo {
id: string
name: string
description: string
}
interface TriggerConfigField {
id: string
title: string
type: string
required: boolean
description?: string
placeholder?: string
}
interface TriggerFullInfo {
id: string
name: string
description: string
provider: string
polling: boolean
outputs: Record<string, any>
configFields: TriggerConfigField[]
}
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: BlockCategory
integrationType: IntegrationType
tags?: string[]
landingContent?: Record<string, unknown>
}
/**
* 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 block definitions.
* Docs need hidden historical version keys so old BlockInfoCard references and
* versioned docs links still render icons, while landing only needs visible blocks.
*/
async function generateIconMapping(options: {
includeHidden: boolean
}): 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
const endIndex = findMatchingClose(fileContent, startIndex)
if (endIndex !== -1) {
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'
// Exclude first-party `blocks`-category primitives (except the small
// catalog-surfaced allowlist) and core/plumbing types. This mirrors
// the catalog/docs `isIntegrationBlock` predicate, with the two
// explicit `blocks`-category exceptions folded in here.
if (
(category === 'blocks' && !ICON_MAP_BLOCK_CATEGORY_ALLOWLIST.has(blockType)) ||
ICON_MAP_EXCLUDED_TYPES.has(blockType)
) {
continue
}
const isVersionedBlockType = isVersionedType(blockType)
if (!hideFromToolbar || (options.includeHidden && isVersionedBlockType)) {
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
*/
/**
* Sort strings to match Biome's organizeImports order:
* case-insensitive character-by-character, uppercase before lowercase as tiebreaker.
*/
function biomeSortCompare(a: string, b: string): number {
const minLen = Math.min(a.length, b.length)
for (let i = 0; i < minLen; i++) {
const al = a[i].toLowerCase()
const bl = b[i].toLowerCase()
if (al !== bl) return al < bl ? -1 : 1
if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1
}
return a.length - b.length
}
function writeIconMapping(iconMapping: Record<string, string>): void {
try {
const iconMappingPath = path.join(rootDir, 'apps/docs/components/ui/icon-mapping.ts')
// Add bare-name aliases for versioned block types so trigger provider names resolve correctly.
// e.g. github_v2 → github, fireflies_v2 → fireflies, gmail_v2 → gmail
const withAliases: Record<string, string> = { ...iconMapping }
for (const [blockType, iconName] of Object.entries(iconMapping)) {
const baseType = stripVersionSuffix(blockType)
if (baseType !== blockType && !withAliases[baseType]) {
withAliases[baseType] = iconName
}
}
// Get unique icon names, sorted to match Biome's organizeImports
const iconNames = [...new Set(Object.values(withAliases))].sort(biomeSortCompare)
// 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(withAliases)
.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
const arrayEnd = findMatchingClose(blockContent, arrayStart, '[', ']')
if (arrayEnd === -1) return []
const subBlocksContent = blockContent.substring(arrayStart + 1, arrayEnd - 1)
// Iterate over top-level objects in the subBlocks array, looking for id: 'operation'
let i = 0
while (i < subBlocksContent.length) {
if (subBlocksContent[i] === '{') {
const j = findMatchingClose(subBlocksContent, i)
if (j === -1) break
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
const optArrayEnd = findMatchingClose(objContent, optArrayStart, '[', ']')
if (optArrayEnd === -1) return []
const optionsContent = objContent.substring(optArrayStart + 1, optArrayEnd - 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' {
// Prefer the authoritative `authMode` declaration when present.
if (/authMode\s*:\s*AuthMode\.OAuth\b/.test(blockContent)) return 'oauth'
if (/authMode\s*:\s*AuthMode\.(?:ApiKey|BotToken)\b/.test(blockContent)) return 'api-key'
// Fall back to credential subBlock heuristics for blocks without authMode.
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
const trigEnd = findMatchingClose(blockContent, start)
if (trigEnd === -1) return []
const triggersContent = blockContent.substring(start, trigEnd)
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
const arrayEnd = findMatchingClose(triggersContent, arrayStart, '[', ']')
if (arrayEnd === -1) return []
const arrayContent = triggersContent.substring(arrayStart + 1, arrayEnd - 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')
// A file may export multiple TriggerConfig objects (e.g. v1 + v2 in
// the same file). Extract all exported configs by splitting on the
// export boundaries and parsing each one independently.
const exportRegex = /export\s+const\s+\w+\s*:\s*TriggerConfig\s*=\s*\{/g
let exportMatch
const exportStarts: number[] = []
while ((exportMatch = exportRegex.exec(content)) !== null) {
exportStarts.push(exportMatch.index)
}
// If no typed exports found, fall back to simple regex on whole file
const segments =
exportStarts.length > 0
? exportStarts.map((start, i) => content.substring(start, exportStarts[i + 1]))
: [content]
for (const segment of segments) {
const idMatch = /\bid\s*:\s*['"]([^'"]+)['"]/.exec(segment)
const nameMatch = /\bname\s*:\s*['"]([^'"]+)['"]/.exec(segment)
const descMatch = /\bdescription\s*:\s*['"]([^'"]+)['"]/.exec(segment)
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 shared integrations data
* directory (`apps/sim/lib/integrations`). Mirrors `writeIconMapping` (the
* docs-app variant) but targets the sim app so it imports from
* `@/components/icons`. Unlike the docs variant, no bare-name aliasing is
* applied because consumers always look up by the canonical (possibly
* versioned) `integration.type` emitted into `integrations.json`.
*/
function writeIntegrationsIconMapping(iconMapping: Record<string, string>): void {
try {
if (!fs.existsSync(INTEGRATIONS_DATA_PATH)) {
fs.mkdirSync(INTEGRATIONS_DATA_PATH, { recursive: true })
}
const iconMappingPath = path.join(INTEGRATIONS_DATA_PATH, 'icon-mapping.ts')
const iconNames = [...new Set(Object.values(iconMapping))].sort(biomeSortCompare)
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')
} catch (error) {
console.error('Error writing integration icon mapping:', error)
}
}
/**
* Collect all integration entries from block definitions and write integrations.json
* to the shared integrations data directory (`apps/sim/lib/integrations`).
* Applies the same visibility filters as the docs generation pipeline.
*/
async function writeIntegrationsJson(iconMapping: Record<string, string>): Promise<void> {
try {
if (!fs.existsSync(INTEGRATIONS_DATA_PATH)) {
fs.mkdirSync(INTEGRATIONS_DATA_PATH, { recursive: true })
}
const triggerRegistry = await buildTriggerRegistry()
const { desc: toolDescMap, name: toolNameMap } = await buildToolDescriptionMap()
// Hand-authored, integration-specific landing content (install walkthrough,
// privacy blurb), keyed by slug. Imported as pure data — its only import is
// type-only and erased at runtime — and baked into the entries below so the
// landing page reads a single source instead of augmenting at render time.
const landingContentModule = await import(
pathToFileURL(path.join(LANDING_INTEGRATIONS_DATA_PATH, 'landing-content.ts')).href
)
const landingContentMap = (landingContentModule.INTEGRATION_LANDING_CONTENT ?? {}) as Record<
string,
Record<string, unknown>
>
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
// Canonical integrations filter: only third-party tool blocks visible in the toolbar.
// `isIntegrationBlock` is the single source of truth for "is integration".
if (!isIntegrationBlock(config)) continue
// Every tools-category block MUST declare an `integrationType` from the canonical
// 16-value enum (apps/sim/blocks/types.ts). Fail loudly so the catalog never
// ships a tool without a category bucket.
if (!config.integrationType) {
throw new Error(
`Block "${blockType}" has \`category: 'tools'\` but is missing required \`integrationType\`. ` +
`Add one of the IntegrationType values from apps/sim/blocks/types.ts.`
)
}
if (!INTEGRATION_CATEGORY_VALUES.has(config.integrationType as IntegrationType)) {
throw new Error(
`Block "${blockType}" has unrecognised \`integrationType: "${config.integrationType}"\`. ` +
`Use one of: ${[...INTEGRATION_CATEGORY_VALUES].join(', ')}.`
)
}
const integrationType = config.integrationType as IntegrationType
// 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/integrations/${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: 'tools',
integrationType,
...(config.tags ? { tags: config.tags } : {}),
...(landingContentMap[slug] ? { landingContent: landingContentMap[slug] } : {}),
})
}
}
// Sort alphabetically by name for a predictable, crawl-friendly order
integrations.sort((a, b) => a.name.localeCompare(b.name))
const jsonPath = path.join(INTEGRATIONS_DATA_PATH, 'integrations.json')
// `JSON.stringify` always expands every array across multiple lines, but Biome's
// JSON formatter inlines short arrays of primitive strings. Pre-collapse those
// arrays here so the emitted file is already in Biome's canonical shape and
// `bun run check` does not churn it on every commit.
const json = JSON.stringify(integrations, null, 2).replace(
/\[\n(\s+"[^"\n]*"(?:,\n\s+"[^"\n]*")*)\n\s+\]/g,
(_match, inner) => {
const items = (inner as string).split(',\n').map((s: string) => s.trim())
return `[${items.join(', ')}]`
}
)
fs.writeFileSync(jsonPath, `${json}\n`)
console.log(`✓ Integration data written: ${integrations.length} integrations → ${jsonPath}`)
} catch (error) {
// Surface taxonomy violations (missing/invalid `integrationType`) loudly —
// they are programmer errors that must fail the generator, not be logged
// and silently swallowed.
console.error('Error writing integrations JSON:', error)
throw 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
const endIndex = findMatchingClose(fileContent, startIndex)
if (endIndex !== -1) {
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
const endIndex = findMatchingClose(fileContent, startIndex)
if (endIndex !== -1) {
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 || ''
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/integrations/${stripVersionSuffix(blockType)}`
const integrationType =
extractEnumPropertyFromContent(blockContent, 'integrationType') ||
baseConfig?.integrationType ||
null
// Tags live on the block's `<BlockName>BlockMeta` export. For spread-inheriting
// blocks (e.g. `ConfluenceV2Block` extending `ConfluenceBlock`), also try the
// spread base's meta so V2 variants inherit tags.
const tags =
(fileContent ? extractTagsFromBlockMeta(fileContent, blockName) : null) ||
(fileContent && spreadBase
? extractTagsFromBlockMeta(fileContent, spreadBase.replace(/Block$/, ''))
: 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
}
}
/**
* The single predicate that decides whether an extracted block config belongs
* in the integration surfaces emitted by this script — the integrations
* catalog (`integrations.json`) and the per-tool `/tools/*.mdx` docs. A block
* qualifies only when it is a third-party integration (`category: 'tools'`)
* that is currently surfaced in the toolbar (`hideFromToolbar` not set). Under
* the versioning upgrade paradigm only the latest version is visible, so this
* also naturally selects the canonical version. Recategorizing a block to
* `'blocks'` or `'triggers'` removes it from all integration surfaces.
*/
function isIntegrationBlock(config: { category?: string; hideFromToolbar?: boolean }): boolean {
return config.category === 'tools' && !config.hideFromToolbar
}
/**
* First-party `category: 'blocks'` primitives that are nonetheless surfaced on
* the integrations page (and therefore need an icon-mapping entry) even though
* they are not third-party integrations. Everything else in the `'blocks'`
* category — including first-party AI capabilities like the image/video
* generators, vision, and STT/TTS — is excluded from the integrations icon
* map, matching {@link isIntegrationBlock}.
*/
const ICON_MAP_BLOCK_CATEGORY_ALLOWLIST = new Set(['memory', 'knowledge', 'enrichment'])
/**
* Block types that never belong in the integrations icon map regardless of
* category — core primitives, triggers, and webhook/feed plumbing.
*/
const ICON_MAP_EXCLUDED_TYPES = new Set([
'evaluator',
'number',
'webhook',
'schedule',
'mcp',
'generic_webhook',
'rss',
])
/**
* 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. Maps an `IntegrationType`
* enum key (e.g. `Communication`) to its slug value (e.g. `'communication'`).
* Mirrors `apps/sim/blocks/types.ts → IntegrationType` — keep in sync.
*/
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]
const ENUM_MAP: Record<string, string> = {
AI: 'ai',
Analytics: 'analytics',
Commerce: 'commerce',
Communication: 'communication',
Databases: 'databases',
DevOps: 'devops',
Documents: 'documents',
Email: 'email',
HR: 'hr',
Marketing: 'marketing',
Observability: 'observability',
Productivity: 'productivity',
Sales: 'sales',
Search: 'search',
Security: 'security',
Support: 'support',
}
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, ''))
}
/**
* Extract `tags` from a `<BlockName>BlockMeta` literal in the source file.
* Looks for `export const <BlockName>BlockMeta = { ... tags: [...] ... }`
* at file scope and scans only the body of that literal. Returns null when
* no matching meta export exists or it contains no `tags` array.
*
* During the in-progress migration to per-block meta, some blocks declare
* `tags` on `BlockConfig` and others on `*BlockMeta`. The caller should
* try this extractor first and fall back to the `BlockConfig` extractor.
*/
function extractTagsFromBlockMeta(fileContent: string, blockName: string): string[] | null {
const headerRegex = new RegExp(`export\\s+const\\s+${blockName}BlockMeta\\s*(?::[^=]+)?=\\s*\\{`)
const metaHeaderMatch = fileContent.match(headerRegex)
if (!metaHeaderMatch || metaHeaderMatch.index === undefined) return null
const openBracePos = fileContent.indexOf('{', metaHeaderMatch.index)
if (openBracePos === -1) return null
const closeBracePos = findMatchingClose(fileContent, openBracePos)
if (closeBracePos === -1) return null
const metaBody = fileContent.substring(openBracePos + 1, closeBracePos)
return extractArrayPropertyFromContent(metaBody, 'tags')
}
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 {}
const pos = findMatchingClose(content, openBracePos)
if (pos === -1) return {}
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) => {
const endPos = findMatchingClose(outputsContent, field.start)
if (endPos !== -1) {
const fieldContent = outputsContent.substring(field.start + 1, endPos - 1).trim()
const typeMatch = fieldContent.match(/type\s*:\s*['"](.*?)['"]/)
const description = extractDescription(fieldContent)
if (typeMatch) {
outputs[field.name] = {
type: typeMatch[1],
description: description || `${field.name} output from the block`,
}
}
}
})
return outputs
}
function extractToolsAccessFromContent(content: string): string[] {
const accessMatch = content.match(/access\s*:\s*\[\s*([^\]]+)\s*\]/)
if (!accessMatch) return []
return [...accessMatch[1].matchAll(/['"]([^'"]+)['"]/g)].map((m) => m[1])
}
/**
* Get the tool prefix (service name) from a tool name.
* e.g., "calcom_list_schedules" -> "calcom"
*/
function getToolPrefixFromName(toolName: string): string {
const parts = toolName.split('_')
// Try to find a valid tool directory
for (let i = parts.length - 1; i >= 1; i--) {
const possiblePrefix = parts.slice(0, i).join('_')
const toolDirPath = path.join(rootDir, `apps/sim/tools/${possiblePrefix}`)
if (fs.existsSync(toolDirPath) && fs.statSync(toolDirPath).isDirectory()) {
return possiblePrefix
}
}
return parts[0]
}
/**
* Resolve a const reference from a types file.
* Handles nested const references recursively.
*
* @param constName - The const name to resolve (e.g., "SCHEDULE_DATA_OUTPUT_PROPERTIES")
* @param toolPrefix - The tool prefix/service name (e.g., "calcom")
* @param depth - Recursion depth to prevent infinite loops
* @returns Resolved properties object or null if not found
*/
function resolveConstReference(
constName: string,
toolPrefix: string,
depth = 0
): Record<string, any> | null {
// Prevent infinite recursion
if (depth > 10) {
console.warn(`Max recursion depth reached resolving const: ${constName}`)
return null
}
// Check cache first
const cacheKey = `${toolPrefix}:${constName}`
if (constResolutionCache.has(cacheKey)) {
return constResolutionCache.get(cacheKey)!
}
// Read the types file for this tool
const typesFilePath = path.join(rootDir, `apps/sim/tools/${toolPrefix}/types.ts`)
if (!fs.existsSync(typesFilePath)) {
// Try to find const in the tool file itself
return null
}
const typesContent = fs.readFileSync(typesFilePath, 'utf-8')
// Find the const definition
// Pattern: export const CONST_NAME = { ... } as const
const constRegex = new RegExp(
`export\\s+const\\s+${constName}\\s*(?::\\s*[^=]+)?\\s*=\\s*\\{`,
'g'
)
const constMatch = constRegex.exec(typesContent)
if (!constMatch) {
return null
}
// Extract the const content
const startIndex = constMatch.index + constMatch[0].length - 1
const endIndex = findMatchingClose(typesContent, startIndex)
if (endIndex === -1) {
return null
}
const constContent = typesContent.substring(startIndex + 1, endIndex - 1).trim()
// Check if this const defines a complete output field (has type property)
// like EVENT_TYPE_OUTPUT = { type: 'object', description: '...', properties: {...} }
const typeMatch = constContent.match(/^\s*type\s*:\s*['"]([^'"]+)['"]/)
if (typeMatch) {
// This is a complete output definition - use parseConstFieldContent
const result = parseConstFieldContent(constContent, toolPrefix, typesContent, depth + 1)
if (result) {
constResolutionCache.set(cacheKey, result)
}
return result
}
// Otherwise, this is a properties object - use parseConstProperties
const properties = parseConstProperties(constContent, toolPrefix, typesContent, depth + 1)
// Cache the result
constResolutionCache.set(cacheKey, properties)
return properties
}
/**
* Parse properties from a const definition, resolving nested const references.
*/
function parseConstProperties(
content: string,
toolPrefix: string,
typesContent: string,
depth: number
): Record<string, any> {
const properties: Record<string, any> = {}
// First, handle spread operators (e.g., "...COMMENT_OUTPUT_PROPERTIES,")
const spreadRegex = /\.\.\.([A-Z][A-Z_0-9]+)\s*(?:,|$)/g
let spreadMatch
while ((spreadMatch = spreadRegex.exec(content)) !== null) {
const constName = spreadMatch[1]
// Check if at depth 0
const beforeMatch = content.substring(0, spreadMatch.index)
const openBraces = (beforeMatch.match(/\{/g) || []).length
const closeBraces = (beforeMatch.match(/\}/g) || []).length
if (openBraces !== closeBraces) {
continue
}
const resolvedConst = resolveConstFromTypesContent(constName, typesContent, toolPrefix, depth)
if (resolvedConst && typeof resolvedConst === 'object') {
// Spread all properties from the resolved const
Object.assign(properties, resolvedConst)
}
}
// Find all top-level property definitions
const propRegex = /(\w+)\s*:\s*(?:\{|([A-Z][A-Z_0-9]+)(?:\s*,|\s*$))/g
let match
while ((match = propRegex.exec(content)) !== null) {
const propName = match[1]
const constRef = match[2]
// Skip 'items' keyword (always a nested structure, never a field name)
if (propName === 'items') {
continue
}
// Check if this match is at depth 0 (not inside nested braces)
const beforeMatch = content.substring(0, match.index)
const openBraces = (beforeMatch.match(/\{/g) || []).length
const closeBraces = (beforeMatch.match(/\}/g) || []).length
if (openBraces !== closeBraces) {
continue // Skip - this is a nested property
}
// For 'properties' or 'type', check if it's an output field definition vs a keyword
// Output field definitions have 'type:' inside (e.g., { type: 'string', description: '...' })
if ((propName === 'properties' || propName === 'type') && !constRef) {
// Peek at what's inside the braces
const startPos = match.index + match[0].length - 1
const endPos = findMatchingClose(content, startPos)
if (endPos !== -1) {
const propContent = content.substring(startPos + 1, endPos - 1).trim()
// If it starts with 'type:', it's an output field definition - process it
if (propContent.match(/^\s*type\s*:/)) {
const parsedProp = parseConstFieldContent(propContent, toolPrefix, typesContent, depth)
if (parsedProp) {
properties[propName] = parsedProp
}
}
// Otherwise, it's a keyword usage (nested properties block or type specifier) - skip it
}
continue
}
if (constRef) {
// This property references a const (e.g., "attendees: ATTENDEES_OUTPUT")
const resolvedConst = resolveConstFromTypesContent(constRef, typesContent, toolPrefix, depth)
if (resolvedConst) {
properties[propName] = resolvedConst
}
} else {
// This property has inline definition
const startPos = match.index + match[0].length - 1
const endPos = findMatchingClose(content, startPos)
if (endPos !== -1) {
const propContent = content.substring(startPos + 1, endPos - 1).trim()
const parsedProp = parseConstFieldContent(propContent, toolPrefix, typesContent, depth)
if (parsedProp) {
properties[propName] = parsedProp
}
}
}
}
return properties
}
/**
* Resolve a const from the types content (for nested references within the same file).
*/
function resolveConstFromTypesContent(
constName: string,
typesContent: string,
toolPrefix: string,
depth: number
): Record<string, any> | null {
if (depth > 10) return null
// Check cache
const cacheKey = `${toolPrefix}:${constName}`
if (constResolutionCache.has(cacheKey)) {
return constResolutionCache.get(cacheKey)!
}
// Find the const definition in typesContent
const constRegex = new RegExp(
`export\\s+const\\s+${constName}\\s*(?::\\s*[^=]+)?\\s*=\\s*\\{`,
'g'
)
const constMatch = constRegex.exec(typesContent)
if (!constMatch) {
return null
}
const startIndex = constMatch.index + constMatch[0].length - 1
const endIndex = findMatchingClose(typesContent, startIndex)
if (endIndex === -1) return null
const constContent = typesContent.substring(startIndex + 1, endIndex - 1).trim()
// Check if this const defines a complete output field (has type property)
const typeMatch = constContent.match(/^\s*type\s*:\s*['"]([^'"]+)['"]/)
if (typeMatch) {
// This is a complete output definition (like ATTENDEES_OUTPUT)
const result = parseConstFieldContent(constContent, toolPrefix, typesContent, depth)
if (result) {
constResolutionCache.set(cacheKey, result)
}
return result
}
// This is a properties object (like ATTENDEE_OUTPUT_PROPERTIES)
const properties = parseConstProperties(constContent, toolPrefix, typesContent, depth + 1)
constResolutionCache.set(cacheKey, properties)
return properties
}
/**
* Parse a field content from a const, resolving nested const references.
*/
/**
* Extract description from field content, handling quoted strings properly.
* Handles single quotes, double quotes, and backticks, preserving internal quotes.
*/
function extractDescription(fieldContent: string): string | null {
// Walk through all `description:` matches and return the first one at depth 0.
// This prevents accidentally picking up `description:` keys inside nested child objects.
const descRegex = /description\s*:\s*('([^']*)'|"([^"]*)"|`([^`]*)`)/g
let m: RegExpExecArray | null
while ((m = descRegex.exec(fieldContent)) !== null) {
if (isAtDepthZero(fieldContent, m.index)) {
return m[2] ?? m[3] ?? m[4] ?? null
}
}
return null
}
function parseConstFieldContent(
fieldContent: string,
toolPrefix: string,
typesContent: string,
depth: number
): any {
const typeMatch = fieldContent.match(/type\s*:\s*['"]([^'"]+)['"]/)
const description = extractDescription(fieldContent)
if (!typeMatch) return null
const fieldType = typeMatch[1]
const result: any = {
type: fieldType,
description: description || '',
}
// Check for properties - either inline or const reference
if (fieldType === 'object' || fieldType === 'json') {
// Check for const reference first
const propsConstMatch = fieldContent.match(/properties\s*:\s*([A-Z][A-Z_0-9]+)/)
if (propsConstMatch) {
const resolvedProps = resolveConstFromTypesContent(
propsConstMatch[1],
typesContent,
toolPrefix,
depth + 1
)
if (resolvedProps) {
result.properties = resolvedProps
}
} else {
// Check for inline properties
const propertiesStart = fieldContent.search(/properties\s*:\s*\{/)
if (propertiesStart !== -1) {
const braceStart = fieldContent.indexOf('{', propertiesStart)
const braceEnd = findMatchingClose(fieldContent, braceStart)
if (braceEnd !== -1) {
const propertiesContent = fieldContent.substring(braceStart + 1, braceEnd - 1).trim()
result.properties = parseConstProperties(
propertiesContent,
toolPrefix,
typesContent,
depth + 1
)
}
}
}
}
// Check for items (arrays)
const itemsConstMatch = fieldContent.match(/items\s*:\s*([A-Z][A-Z_0-9]+)/)
if (itemsConstMatch) {
const resolvedItems = resolveConstFromTypesContent(
itemsConstMatch[1],
typesContent,
toolPrefix,
depth + 1
)
if (resolvedItems) {
result.items = resolvedItems
}
} else {
const itemsStart = fieldContent.search(/items\s*:\s*\{/)
if (itemsStart !== -1) {
const braceStart = fieldContent.indexOf('{', itemsStart)
const braceEnd = findMatchingClose(fieldContent, braceStart)
if (braceEnd !== -1) {
const itemsContent = fieldContent.substring(braceStart + 1, braceEnd - 1).trim()
const itemsType = itemsContent.match(/type\s*:\s*['"]([^'"]+)['"]/)
const itemsDesc = extractDescription(itemsContent)
result.items = {
type: itemsType ? itemsType[1] : 'object',
description: itemsDesc || '',
}
// Check for properties in items - either inline or const reference
const itemsPropsConstMatch = itemsContent.match(/properties\s*:\s*([A-Z][A-Z_0-9]+)/)
if (itemsPropsConstMatch) {
const resolvedProps = resolveConstFromTypesContent(
itemsPropsConstMatch[1],
typesContent,
toolPrefix,
depth + 1
)
if (resolvedProps) {
result.items.properties = resolvedProps
}
} else {
const itemsPropsStart = itemsContent.search(/properties\s*:\s*\{/)
if (itemsPropsStart !== -1) {
const propsBraceStart = itemsContent.indexOf('{', itemsPropsStart)
let propsBraceCount = 1
let propsBraceEnd = propsBraceStart + 1
while (propsBraceEnd < itemsContent.length && propsBraceCount > 0) {
if (itemsContent[propsBraceEnd] === '{') propsBraceCount++
else if (itemsContent[propsBraceEnd] === '}') propsBraceCount--
propsBraceEnd++
}
if (propsBraceCount === 0) {
const itemsPropsContent = itemsContent
.substring(propsBraceStart + 1, propsBraceEnd - 1)
.trim()
result.items.properties = parseConstProperties(
itemsPropsContent,
toolPrefix,
typesContent,
depth + 1
)
}
}
}
}
}
}
return result
}
/**
* Extract outputs from a tool content block by trying:
* 1. Const reference (e.g., `outputs: GIT_REF_OUTPUT_PROPERTIES,`)
* 2. Inline object (e.g., `outputs: { id: { type: 'string', ... } }`)
*/
function extractOutputsFromToolContent(content: string, toolPrefix: string): Record<string, any> {
const constMatch = content.match(/(?<![a-zA-Z_])outputs\s*:\s*([A-Z][A-Z_0-9]+)\s*(?:,|\}|$)/)
if (constMatch) {
const resolved = resolveConstReference(constMatch[1], toolPrefix)
if (resolved && typeof resolved === 'object') {
return resolved
}
}
const outputsStart = content.search(/(?<![a-zA-Z_])outputs\s*:\s*{/)
if (outputsStart !== -1) {
const openBracePos = content.indexOf('{', outputsStart)
if (openBracePos !== -1) {
const closePos = findMatchingClose(content, openBracePos)
if (closePos !== -1) {
const outputsContent = content.substring(openBracePos + 1, closePos - 1).trim()
return parseToolOutputsField(outputsContent, toolPrefix)
}
}
}
return {}
}
function extractToolInfo(
toolName: string,
fileContent: string
): {
description: string
params: Array<{ name: string; type: string; required: boolean; description: string }>
outputs: Record<string, any>
} | null {
try {
// First, try to find the specific tool definition by its ID
// Look for: id: 'toolName' or id: "toolName"
const toolIdRegex = new RegExp(`id:\\s*['"]${toolName}['"]`)
const toolIdMatch = fileContent.match(toolIdRegex)
let toolContent = fileContent
if (toolIdMatch && toolIdMatch.index !== undefined) {
// Find the tool definition block that contains this ID
// Search backwards for 'export const' or start of object
const beforeId = fileContent.substring(0, toolIdMatch.index)
const exportMatch = beforeId.match(/export\s+const\s+\w+[^=]*=\s*\{[\s\S]*$/)
if (exportMatch && exportMatch.index !== undefined) {
const startIndex = exportMatch.index + exportMatch[0].length - 1
const endIndex = findMatchingClose(fileContent, startIndex)
if (endIndex !== -1) {
toolContent = fileContent.substring(startIndex, endIndex)
}
}
}
// Params are often inherited via spread, so search the full file for params
const toolConfigRegex =
/params\s*:\s*{([\s\S]*?)},?\s*(?:outputs|oauth|request|directExecution|postProcess|transformResponse)\s*:/
const toolConfigMatch = fileContent.match(toolConfigRegex)
// Description should come from the specific tool block if found
// Only search before nested objects (params, outputs, request, etc.) to avoid matching
// descriptions inside outputs or params
let descriptionSearchContent = toolContent
const nestedObjectPatterns = [
/\bparams\s*:\s*[{]/,
/\boutputs\s*:\s*\{/,
/\brequest\s*:\s*\{/,
/\boauth\s*:\s*\{/,
/\btransformResponse\s*:/,
]
let cutoffIndex = toolContent.length
for (const pattern of nestedObjectPatterns) {
const match = toolContent.match(pattern)
if (match && match.index !== undefined && match.index < cutoffIndex) {
cutoffIndex = match.index
}
}
descriptionSearchContent = toolContent.substring(0, cutoffIndex)
const descriptionRegex = /description\s*:\s*['"](.*?)['"].*/
let descriptionMatch = descriptionSearchContent.match(descriptionRegex)
// If description isn't found as a literal (might be inherited like description: baseTool.description),
// try to find the referenced tool's description
if (!descriptionMatch) {
const inheritedDescMatch = descriptionSearchContent.match(
/description\s*:\s*(\w+)Tool\.description/
)
if (inheritedDescMatch) {
const baseTool = inheritedDescMatch[1]
// Try to find the base tool's description in the file
const baseToolDescRegex = new RegExp(
`export\\s+const\\s+${baseTool}Tool[^{]*\\{[\\s\\S]*?description\\s*:\\s*['"]([^'"]+)['"]`,
'i'
)
const baseToolMatch = fileContent.match(baseToolDescRegex)
if (baseToolMatch) {
descriptionMatch = baseToolMatch
}
}
}
const description = descriptionMatch ? descriptionMatch[1] : 'No description available'
const params: Array<{ name: string; type: string; required: boolean; description: string }> = []
if (toolConfigMatch) {
const paramsContent = toolConfigMatch[1]
const paramBlocksRegex = /(\w+)\s*:\s*{/g
let paramMatch
const paramPositions: Array<{ name: string; start: number; content: string }> = []
/**
* Checks if a position in the string is inside a quoted string.
* This prevents matching patterns like "Example: {" inside description strings.
*/
const isInsideString = (content: string, position: number): boolean => {
let inSingleQuote = false
let inDoubleQuote = false
let inBacktick = false
for (let i = 0; i < position; i++) {
const char = content[i]
const prevChar = i > 0 ? content[i - 1] : ''
// Skip escaped quotes
if (prevChar === '\\') continue
if (char === "'" && !inDoubleQuote && !inBacktick) {
inSingleQuote = !inSingleQuote
} else if (char === '"' && !inSingleQuote && !inBacktick) {
inDoubleQuote = !inDoubleQuote
} else if (char === '`' && !inSingleQuote && !inDoubleQuote) {
inBacktick = !inBacktick
}
}
return inSingleQuote || inDoubleQuote || inBacktick
}
while ((paramMatch = paramBlocksRegex.exec(paramsContent)) !== null) {
const paramName = paramMatch[1]
const startPos = paramMatch.index + paramMatch[0].length - 1
// Skip matches that are inside string literals (e.g., "Example: {" in descriptions)
if (isInsideString(paramsContent, paramMatch.index)) {
continue
}
const endPos = findMatchingClose(paramsContent, startPos)
if (endPos !== -1) {
const paramBlock = paramsContent.substring(startPos + 1, endPos - 1).trim()
paramPositions.push({ name: paramName, start: startPos, content: paramBlock })
// Resume scanning after this param's block so nested descriptors
// (e.g. an array param's `items: {...}`) are not parsed as params.
paramBlocksRegex.lastIndex = endPos
}
}
for (const param of paramPositions) {
const paramName = param.name
const paramBlock = param.content
if (paramName === 'accessToken' || paramName === 'params' || paramName === 'tools') {
continue
}
const typeMatch = paramBlock.match(/type\s*:\s*['"]([^'"]+)['"]/)
const requiredMatch = paramBlock.match(/required\s*:\s*(true|false)/)
let descriptionMatch = paramBlock.match(/description\s*:\s*'(.*?)'(?=\s*[,}])/s)
if (!descriptionMatch) {
descriptionMatch = paramBlock.match(/description\s*:\s*"(.*?)"(?=\s*[,}])/s)
}
if (!descriptionMatch) {
descriptionMatch = paramBlock.match(/description\s*:\s*`([^`]+)`/s)
}
if (!descriptionMatch) {
descriptionMatch = paramBlock.match(
/description\s*:\s*['"]([^'"]*(?:\n[^'"]*)*?)['"](?=\s*[,}])/s
)
}
params.push({
name: paramName,
type: typeMatch ? typeMatch[1] : 'string',
required: requiredMatch ? requiredMatch[1] === 'true' : false,
description: descriptionMatch ? descriptionMatch[1] : 'No description',
})
}
}
// Get the tool prefix for resolving const references
const toolPrefix = getToolPrefixFromName(toolName)
let outputs = extractOutputsFromToolContent(toolContent, toolPrefix)
// If no outputs found, check for spread inheritance (e.g., "...extendParserTool")
// toolContent may be narrowed past the spread line, so reconstruct the full block
if (Object.keys(outputs).length === 0) {
let fullToolBlock = toolContent
if (toolIdMatch && toolIdMatch.index !== undefined) {
const beforeId = fileContent.substring(0, toolIdMatch.index)
const exportRegex = /export\s+const\s+\w+[^=]*=\s*\{/g
let lastExportMatch: RegExpExecArray | null = null
let m: RegExpExecArray | null = null
while ((m = exportRegex.exec(beforeId)) !== null) {
lastExportMatch = m
}
if (lastExportMatch && lastExportMatch.index !== undefined) {
const bracePos = lastExportMatch.index + lastExportMatch[0].length - 1
const ep = findMatchingClose(fileContent, bracePos)
if (ep !== -1) {
fullToolBlock = fileContent.substring(bracePos, ep)
}
}
}
const spreadMatch = fullToolBlock.match(/\.\.\.(\w+(?:Tool|Base)\w*)/)
if (spreadMatch) {
const baseVarName = spreadMatch[1]
const baseToolRegex = new RegExp(
`export\\s+const\\s+${baseVarName}(?=[^a-zA-Z0-9_]|$)[^=]*=\\s*\\{`
)
const baseToolMatch = fileContent.match(baseToolRegex)
if (baseToolMatch && baseToolMatch.index !== undefined) {
const baseStart = baseToolMatch.index + baseToolMatch[0].length - 1
const endIdx = findMatchingClose(fileContent, baseStart)
if (endIdx !== -1) {
const baseToolContent = fileContent.substring(baseStart, endIdx)
outputs = extractOutputsFromToolContent(baseToolContent, toolPrefix)
}
}
}
}
return {
description,
params,
outputs,
}
} catch (error) {
console.error(`Error extracting info for tool ${toolName}:`, error)
return null
}
}
function formatOutputStructure(outputs: Record<string, any>, indentLevel = 0): string {
let result = ''
for (const [key, output] of Object.entries(outputs)) {
let type = 'unknown'
let description = `${key} output from the tool`
if (typeof output === 'object' && output !== null) {
if (output.type) {
type = output.type
}
if (output.description) {
description = output.description
}
}
const escapedDescription = description
.replace(/\|/g, '\\|')
.replace(/\{/g, '\\{')
.replace(/\}/g, '\\}')
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)')
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
// Build prefix based on indent level - each level adds 2 spaces before the arrow
let prefix = ''
if (indentLevel > 0) {
const spaces = ' '.repeat(indentLevel)
prefix = `${spaces}↳ `
}
if (typeof output === 'object' && output !== null && output.type === 'array') {
result += `| ${prefix}\`${key}\` | ${type} | ${escapedDescription} |\n`
if (output.items?.properties) {
const arrayItemsResult = formatOutputStructure(output.items.properties, indentLevel + 1)
result += arrayItemsResult
}
} else if (
typeof output === 'object' &&
output !== null &&
output.properties &&
(output.type === 'object' || output.type === 'json')
) {
result += `| ${prefix}\`${key}\` | ${type} | ${escapedDescription} |\n`
const nestedResult = formatOutputStructure(output.properties, indentLevel + 1)
result += nestedResult
} else {
result += `| ${prefix}\`${key}\` | ${type} | ${escapedDescription} |\n`
}
}
return result
}
function parseToolOutputsField(outputsContent: string, toolPrefix?: string): Record<string, any> {
const outputs: Record<string, any> = {}
// First, handle top-level const references
// Patterns: "data: BOOKING_DATA_OUTPUT_PROPERTIES" or "pagination: PAGINATION_OUTPUT"
if (toolPrefix) {
// Pattern 1: Direct const reference
const constRefRegex = /(\w+)\s*:\s*([A-Z][A-Z_0-9]+)\s*(?:,|$)/g
let constMatch
while ((constMatch = constRefRegex.exec(outputsContent)) !== null) {
const propName = constMatch[1]
const constName = constMatch[2]
// Check if at depth 0
const beforeMatch = outputsContent.substring(0, constMatch.index)
const openBraces = (beforeMatch.match(/\{/g) || []).length
const closeBraces = (beforeMatch.match(/\}/g) || []).length
if (openBraces !== closeBraces) {
continue
}
const resolvedConst = resolveConstReference(constName, toolPrefix)
if (resolvedConst) {
outputs[propName] = resolvedConst
}
}
// Pattern 2: Property access on const (e.g., "status: BOOKING_DATA_OUTPUT_PROPERTIES.status,")
const propAccessRegex = /(\w+)\s*:\s*([A-Z][A-Z_0-9]+)\.(\w+)\s*(?:,|$)/g
let propAccessMatch
while ((propAccessMatch = propAccessRegex.exec(outputsContent)) !== null) {
const propName = propAccessMatch[1]
const constName = propAccessMatch[2]
const accessedProp = propAccessMatch[3]
// Skip if already resolved
if (outputs[propName]) {
continue
}
// Check if at depth 0
const beforeMatch = outputsContent.substring(0, propAccessMatch.index)
const openBraces = (beforeMatch.match(/\{/g) || []).length
const closeBraces = (beforeMatch.match(/\}/g) || []).length
if (openBraces !== closeBraces) {
continue
}
const resolvedConst = resolveConstReference(constName, toolPrefix)
if (resolvedConst?.[accessedProp]) {
outputs[propName] = resolvedConst[accessedProp]
}
}
// Pattern 3: Spread operator (e.g., "...COMMENT_OUTPUT_PROPERTIES,")
const spreadRegex = /\.\.\.([A-Z][A-Z_0-9]+)\s*(?:,|$)/g
let spreadMatch
while ((spreadMatch = spreadRegex.exec(outputsContent)) !== null) {
const constName = spreadMatch[1]
// Check if at depth 0 (not inside nested braces)
const beforeMatch = outputsContent.substring(0, spreadMatch.index)
const openBraces = (beforeMatch.match(/\{/g) || []).length
const closeBraces = (beforeMatch.match(/\}/g) || []).length
if (openBraces !== closeBraces) {
continue
}
const resolvedConst = resolveConstReference(constName, toolPrefix)
if (resolvedConst && typeof resolvedConst === 'object') {
// Spread all properties from the resolved const
Object.assign(outputs, resolvedConst)
}
}
}
const braces: Array<{ type: 'open' | 'close'; pos: number; level: number }> = []
for (let i = 0; i < outputsContent.length; i++) {
if (outputsContent[i] === '{') {
braces.push({ type: 'open', pos: i, level: 0 })
} else if (outputsContent[i] === '}') {
braces.push({ type: 'close', pos: i, level: 0 })
}
}
let currentLevel = 0
for (const brace of braces) {
if (brace.type === 'open') {
brace.level = currentLevel
currentLevel++
} else {
currentLevel--
brace.level = currentLevel
}
}
const fieldStartRegex = /(\w+)\s*:\s*{/g
let match
const fieldPositions: Array<{ name: string; start: number; end: number; level: number }> = []
while ((match = fieldStartRegex.exec(outputsContent)) !== null) {
const fieldName = match[1]
const bracePos = match.index + match[0].length - 1
// Skip if already resolved as const reference
if (outputs[fieldName]) {
continue
}
const openBrace = braces.find((b) => b.type === 'open' && b.pos === bracePos)
if (openBrace) {
const endPos = findMatchingClose(outputsContent, bracePos)
if (endPos !== -1) {
fieldPositions.push({
name: fieldName,
start: bracePos,
end: endPos,
level: openBrace.level,
})
}
}
}
const topLevelFields = fieldPositions.filter((f) => f.level === 0)
topLevelFields.forEach((field) => {
const fieldContent = outputsContent.substring(field.start + 1, field.end - 1).trim()
const parsedField = parseFieldContent(fieldContent, toolPrefix)
if (parsedField) {
outputs[field.name] = parsedField
}
})
return outputs
}
/**
* Returns true if the regex match at `matchIndex` within `content` is at brace depth 0.
* Used to distinguish top-level keys from keys nested inside child objects.
*/
function isAtDepthZero(content: string, matchIndex: number): boolean {
let depth = 0
for (let i = 0; i < matchIndex; i++) {
if (content[i] === '{') depth++
else if (content[i] === '}') depth--
}
return depth === 0
}
function parseFieldContent(fieldContent: string, toolPrefix?: string): any {
// Only match `type:` that is at the top level of fieldContent (depth 0).
// Child objects like `title: { type: 'string', ... }` also contain `type:` but at depth 1.
const typeRegex = /type\s*:\s*['"]([^'"]+)['"]/g
let typeMatch: RegExpExecArray | null = null
let m: RegExpExecArray | null
while ((m = typeRegex.exec(fieldContent)) !== null) {
if (isAtDepthZero(fieldContent, m.index)) {
typeMatch = m
break
}
}
const description = extractDescription(fieldContent)
// Check for spread operator at the start of field content (e.g., ...SUBSCRIPTION_OUTPUT)
// This pattern is used when a field spreads a complete output definition and optionally overrides properties
const spreadMatch = fieldContent.match(/^\s*\.\.\.([A-Z][A-Z_0-9]+)\s*,/)
if (spreadMatch && toolPrefix && !typeMatch) {
const constName = spreadMatch[1]
const resolvedConst = resolveConstReference(constName, toolPrefix)
if (resolvedConst && typeof resolvedConst === 'object') {
// Start with the resolved const and override with inline properties
const result: any = { ...resolvedConst }
// Override description if provided inline
if (description) {
result.description = description
}
return result
}
}
if (!typeMatch) {
// No top-level `type` key — check if the content contains named child fields that each
// have their own `type` property. This is the "implicit object" pattern used in trigger
// outputs (e.g., Cal.com's `payload`, Linear's `data`).
const properties = parsePropertiesContent(fieldContent, toolPrefix)
if (Object.keys(properties).length > 0) {
return {
type: 'object',
description: description || '',
properties,
}
}
return null
}
const fieldType = typeMatch[1]
const result: any = {
type: fieldType,
description: description || '',
}
if (fieldType === 'object' || fieldType === 'json') {
// Check for const reference first (e.g., properties: SCHEDULE_DATA_OUTPUT_PROPERTIES)
const propsConstMatch = fieldContent.match(/properties\s*:\s*([A-Z][A-Z_0-9]+)/)
if (propsConstMatch && toolPrefix) {
const resolvedProps = resolveConstReference(propsConstMatch[1], toolPrefix)
if (resolvedProps) {
result.properties = resolvedProps
}
} else {
// Check for inline properties
const propertiesRegex = /properties\s*:\s*{/
const propertiesStart = fieldContent.search(propertiesRegex)
if (propertiesStart !== -1) {
const braceStart = fieldContent.indexOf('{', propertiesStart)
const braceEnd = findMatchingClose(fieldContent, braceStart)
if (braceEnd !== -1) {
const propertiesContent = fieldContent.substring(braceStart + 1, braceEnd - 1).trim()
result.properties = parsePropertiesContent(propertiesContent, toolPrefix)
}
}
}
}
// Check for items const reference (e.g., items: ATTENDEES_OUTPUT)
const itemsConstMatch = fieldContent.match(/items\s*:\s*([A-Z][A-Z_0-9]+)/)
if (itemsConstMatch && toolPrefix) {
const resolvedItems = resolveConstReference(itemsConstMatch[1], toolPrefix)
if (resolvedItems) {
result.items = resolvedItems
}
} else {
const itemsRegex = /items\s*:\s*{/
const itemsStart = fieldContent.search(itemsRegex)
if (itemsStart !== -1) {
const braceStart = fieldContent.indexOf('{', itemsStart)
const braceEnd = findMatchingClose(fieldContent, braceStart)
if (braceEnd !== -1) {
const itemsContent = fieldContent.substring(braceStart + 1, braceEnd - 1).trim()
const itemsType = itemsContent.match(/type\s*:\s*['"]([^'"]+)['"]/)
// Check for inline properties FIRST (properties: {), then const reference
const propertiesInlineStart = itemsContent.search(/properties\s*:\s*{/)
// Only match const reference if it's at the TOP level (before any {)
const itemsPropsConstMatch =
propertiesInlineStart === -1
? itemsContent.match(/properties\s*:\s*([A-Z][A-Z_0-9]+)/)
: null
const searchContent =
propertiesInlineStart >= 0
? itemsContent.substring(0, propertiesInlineStart)
: itemsContent
const itemsDesc = extractDescription(searchContent)
result.items = {
type: itemsType ? itemsType[1] : 'object',
description: itemsDesc || '',
}
if (itemsPropsConstMatch && toolPrefix) {
const resolvedProps = resolveConstReference(itemsPropsConstMatch[1], toolPrefix)
if (resolvedProps) {
result.items.properties = resolvedProps
}
} else if (propertiesInlineStart !== -1) {
const itemsPropertiesRegex = /properties\s*:\s*{/
const itemsPropsStart = itemsContent.search(itemsPropertiesRegex)
if (itemsPropsStart !== -1) {
const propsBraceStart = itemsContent.indexOf('{', itemsPropsStart)
let propsBraceCount = 1
let propsBraceEnd = propsBraceStart + 1
while (propsBraceEnd < itemsContent.length && propsBraceCount > 0) {
if (itemsContent[propsBraceEnd] === '{') propsBraceCount++
else if (itemsContent[propsBraceEnd] === '}') propsBraceCount--
propsBraceEnd++
}
if (propsBraceCount === 0) {
const itemsPropsContent = itemsContent
.substring(propsBraceStart + 1, propsBraceEnd - 1)
.trim()
result.items.properties = parsePropertiesContent(itemsPropsContent, toolPrefix)
}
}
}
}
}
}
return result
}
function parsePropertiesContent(
propertiesContent: string,
toolPrefix?: string
): Record<string, any> {
const properties: Record<string, any> = {}
// First, handle const references at the property level
// Patterns: "attendees: ATTENDEES_OUTPUT" or "id: BOOKING_DATA_OUTPUT_PROPERTIES.id"
if (toolPrefix) {
// Pattern 1: Direct const reference (e.g., "eventType: EVENT_TYPE_OUTPUT,")
const constRefRegex = /(\w+)\s*:\s*([A-Z][A-Z_0-9]+)\s*(?:,|$)/g
let constMatch
while ((constMatch = constRefRegex.exec(propertiesContent)) !== null) {
const propName = constMatch[1]
const constName = constMatch[2]
// Skip keywords
if (propName === 'items' || propName === 'properties' || propName === 'type') {
continue
}
// Check if at depth 0
const beforeMatch = propertiesContent.substring(0, constMatch.index)
const openBraces = (beforeMatch.match(/\{/g) || []).length
const closeBraces = (beforeMatch.match(/\}/g) || []).length
if (openBraces !== closeBraces) {
continue
}
const resolvedConst = resolveConstReference(constName, toolPrefix)
if (resolvedConst) {
properties[propName] = resolvedConst
}
}
// Pattern 2: Property access on const (e.g., "id: BOOKING_DATA_OUTPUT_PROPERTIES.id,")
const propAccessRegex = /(\w+)\s*:\s*([A-Z][A-Z_0-9]+)\.(\w+)\s*(?:,|$)/g
let propAccessMatch
while ((propAccessMatch = propAccessRegex.exec(propertiesContent)) !== null) {
const propName = propAccessMatch[1]
const constName = propAccessMatch[2]
const accessedProp = propAccessMatch[3]
// Skip keywords
if (propName === 'items' || propName === 'properties' || propName === 'type') {
continue
}
// Skip if already resolved
if (properties[propName]) {
continue
}
// Check if at depth 0
const beforeMatch = propertiesContent.substring(0, propAccessMatch.index)
const openBraces = (beforeMatch.match(/\{/g) || []).length
const closeBraces = (beforeMatch.match(/\}/g) || []).length
if (openBraces !== closeBraces) {
continue
}
const resolvedConst = resolveConstReference(constName, toolPrefix)
if (resolvedConst?.[accessedProp]) {
properties[propName] = resolvedConst[accessedProp]
}
}
// Pattern 3: Spread operator (e.g., "...COMMENT_OUTPUT_PROPERTIES,")
const spreadRegex = /\.\.\.([A-Z][A-Z_0-9]+)\s*(?:,|$)/g
let spreadMatch
while ((spreadMatch = spreadRegex.exec(propertiesContent)) !== null) {
const constName = spreadMatch[1]
// Check if at depth 0
const beforeMatch = propertiesContent.substring(0, spreadMatch.index)
const openBraces = (beforeMatch.match(/\{/g) || []).length
const closeBraces = (beforeMatch.match(/\}/g) || []).length
if (openBraces !== closeBraces) {
continue
}
const resolvedConst = resolveConstReference(constName, toolPrefix)
if (resolvedConst && typeof resolvedConst === 'object') {
// Spread all properties from the resolved const
Object.assign(properties, resolvedConst)
}
}
}
const propStartRegex = /(\w+)\s*:\s*{/g
let match
const propPositions: Array<{ name: string; start: number; content: string }> = []
while ((match = propStartRegex.exec(propertiesContent)) !== null) {
const propName = match[1]
if (propName === 'items' || propName === 'properties') {
continue
}
// Skip if already resolved as const reference
if (properties[propName]) {
continue
}
// Check if this match is at depth 0 (not inside nested braces)
// Only process top-level properties, skip nested ones
const beforeMatch = propertiesContent.substring(0, match.index)
const openBraces = (beforeMatch.match(/{/g) || []).length
const closeBraces = (beforeMatch.match(/}/g) || []).length
if (openBraces !== closeBraces) {
continue // Skip - this is a nested property
}
const startPos = match.index + match[0].length - 1
const endPos = findMatchingClose(propertiesContent, startPos)
if (endPos !== -1) {
const propContent = propertiesContent.substring(startPos + 1, endPos - 1).trim()
const hasDescription = /description\s*:\s*/.test(propContent)
const hasProperties = /properties\s*:\s*[{A-Z]/.test(propContent)
const hasItems = /items\s*:\s*[{A-Z]/.test(propContent)
const isTypeOnly =
!hasDescription &&
!hasProperties &&
!hasItems &&
/^type\s*:\s*['"].*?['"]\s*,?\s*$/.test(propContent)
if (!isTypeOnly) {
propPositions.push({
name: propName,
start: startPos,
content: propContent,
})
}
}
}
propPositions.forEach((prop) => {
const parsedProp = parseFieldContent(prop.content, toolPrefix)
if (parsedProp) {
properties[prop.name] = parsedProp
}
})
return properties
}
async function getToolInfo(toolName: string): Promise<{
description: string
params: Array<{ name: string; type: string; required: boolean; description: string }>
outputs: Record<string, any>
} | null> {
try {
const parts = toolName.split('_')
let toolPrefix = ''
let toolSuffix = ''
for (let i = parts.length - 1; i >= 1; i--) {
const possiblePrefix = parts.slice(0, i).join('_')
const possibleSuffix = parts.slice(i).join('_')
const toolDirPath = path.join(rootDir, `apps/sim/tools/${possiblePrefix}`)
if (fs.existsSync(toolDirPath) && fs.statSync(toolDirPath).isDirectory()) {
toolPrefix = possiblePrefix
toolSuffix = possibleSuffix
break
}
}
if (!toolPrefix) {
toolPrefix = parts[0]
toolSuffix = parts.slice(1).join('_')
}
// Check if this is a versioned tool (e.g., _v2, _v3)
const isVersionedTool = isVersionedType(toolSuffix)
const strippedToolSuffix = stripVersionSuffix(toolSuffix)
const possibleLocations: Array<{ path: string; priority: 'exact' | 'fallback' }> = []
// For versioned tools, prioritize the exact versioned file first
// This handles cases like google_sheets where V2 is in a separate file (read_v2.ts)
if (isVersionedTool) {
// First priority: exact versioned file (e.g., read_v2.ts)
possibleLocations.push({
path: path.join(rootDir, `apps/sim/tools/${toolPrefix}/${toolSuffix}.ts`),
priority: 'exact',
})
// Second priority: stripped file that contains both V1 and V2 (e.g., pr.ts for github)
possibleLocations.push({
path: path.join(rootDir, `apps/sim/tools/${toolPrefix}/${strippedToolSuffix}.ts`),
priority: 'fallback',
})
} else {
// Non-versioned tool: try the direct file
possibleLocations.push({
path: path.join(rootDir, `apps/sim/tools/${toolPrefix}/${toolSuffix}.ts`),
priority: 'exact',
})
}
// Also try camelCase versions
const camelCaseSuffix = strippedToolSuffix
.split('_')
.map((part, i) => (i === 0 ? part : part.charAt(0).toUpperCase() + part.slice(1)))
.join('')
possibleLocations.push({
path: path.join(rootDir, `apps/sim/tools/${toolPrefix}/${camelCaseSuffix}.ts`),
priority: 'fallback',
})
// Fall back to index.ts
possibleLocations.push({
path: path.join(rootDir, `apps/sim/tools/${toolPrefix}/index.ts`),
priority: 'fallback',
})
let toolFileContent = ''
let foundFile = ''
// Try to find a file that contains the exact tool ID
for (const location of possibleLocations) {
if (fs.existsSync(location.path)) {
const content = fs.readFileSync(location.path, 'utf-8')
// Check if this file contains the exact tool ID we're looking for
const toolIdRegex = new RegExp(`id:\\s*['"]${toolName}['"]`)
if (toolIdRegex.test(content)) {
toolFileContent = content
foundFile = location.path
break
}
// For fallback locations, store the content in case we don't find an exact match
if (location.priority === 'fallback' && !toolFileContent) {
toolFileContent = content
foundFile = location.path
}
}
}
// If we didn't find a file with the exact ID, use the first available file
if (!toolFileContent) {
for (const location of possibleLocations) {
if (fs.existsSync(location.path)) {
toolFileContent = fs.readFileSync(location.path, 'utf-8')
foundFile = location.path
break
}
}
}
if (!toolFileContent) {
console.warn(`Could not find definition for tool: ${toolName}`)
return null
}
return extractToolInfo(toolName, toolFileContent)
} catch (error) {
console.error(`Error getting info for tool ${toolName}:`, error)
return null
}
}
function extractManualContent(existingContent: string): Record<string, string> {
const manualSections: Record<string, string> = {}
const manualContentRegex =
/\{\/\*\s*MANUAL-CONTENT-START:(\w+)\s*\*\/\}([\s\S]*?)\{\/\*\s*MANUAL-CONTENT-END\s*\*\/\}/g
let match
while ((match = manualContentRegex.exec(existingContent)) !== null) {
const sectionName = match[1]
const content = match[2].trim()
manualSections[sectionName] = content
}
return manualSections
}
function mergeWithManualContent(
generatedMarkdown: string,
existingContent: string | null,
manualSections: Record<string, string>
): string {
if (!existingContent || Object.keys(manualSections).length === 0) {
return generatedMarkdown
}
let mergedContent = generatedMarkdown
Object.entries(manualSections).forEach(([sectionName, content]) => {
const insertionPoints: Record<string, { regex: RegExp }> = {
intro: {
regex: /<BlockInfoCard[\s\S]*?(\/>|<\/svg>`}\s*\/>)/,
},
usage: {
regex: /## Usage Instructions/,
},
outputs: {
regex: /## Outputs/,
},
notes: {
regex: /## Notes/,
},
}
const insertionPoint = insertionPoints[sectionName]
const wrapped = `{/* MANUAL-CONTENT-START:${sectionName} */}\n${content}\n{/* MANUAL-CONTENT-END */}`
const match = insertionPoint ? mergedContent.match(insertionPoint.regex) : null
if (match && match.index !== undefined) {
const insertPosition = match.index + match[0].length
mergedContent = `${mergedContent.slice(0, insertPosition)}\n\n${wrapped}\n${mergedContent.slice(insertPosition)}`
} else {
// Never drop manual content: when the anchor is missing (e.g. a `notes`
// section with no generated "## Notes" heading), append at the end.
console.log(`No insertion anchor for manual section "${sectionName}" — appending at end`)
mergedContent = `${mergedContent.replace(/\s*$/, '')}\n\n${wrapped}\n`
}
})
return mergedContent
}
async function generateBlockDoc(blockPath: string) {
try {
const blockFileName = path.basename(blockPath, '.ts')
if (blockFileName.endsWith('.test')) {
return
}
const fileContent = fs.readFileSync(blockPath, 'utf-8')
// Extract ALL block configs from the file (already filters out hideFromToolbar: true)
const blockConfigs = extractAllBlockConfigs(fileContent)
if (blockConfigs.length === 0) {
console.warn(`Skipping ${blockFileName} - no valid block configs found`)
return
}
// Process each block config
for (const blockConfig of blockConfigs) {
if (!blockConfig.type) {
continue
}
if (
blockConfig.type.includes('_trigger') ||
blockConfig.type.includes('_webhook') ||
blockConfig.type.includes('rss')
) {
console.log(`Skipping ${blockConfig.type} - contains '_trigger'`)
continue
}
if (
(blockConfig.category === 'blocks' &&
!NATIVE_RESOURCE_BLOCK_TYPES.has(stripVersionSuffix(blockConfig.type))) ||
blockConfig.type === 'sim_workspace_event' ||
blockConfig.type === 'evaluator' ||
blockConfig.type === 'number' ||
blockConfig.type === 'webhook' ||
blockConfig.type === 'schedule' ||
blockConfig.type === 'mcp' ||
blockConfig.type === 'generic_webhook' ||
blockConfig.type === 'rss'
) {
continue
}
// Use stripped type for file name (removes _v2, _v3 suffixes for cleaner URLs)
const displayType = stripVersionSuffix(blockConfig.type)
const outputFilePath = path.join(DOCS_OUTPUT_PATH, `${displayType}.mdx`)
let existingContent: string | null = null
if (fs.existsSync(outputFilePath)) {
existingContent = fs.readFileSync(outputFilePath, 'utf-8')
}
const manualSections = existingContent ? extractManualContent(existingContent) : {}
const markdown = await generateMarkdownForBlock(blockConfig, displayType)
let finalContent = markdown
if (Object.keys(manualSections).length > 0) {
finalContent = mergeWithManualContent(markdown, existingContent, manualSections)
}
fs.writeFileSync(outputFilePath, finalContent)
const logType =
displayType !== blockConfig.type ? `${displayType} (from ${blockConfig.type})` : displayType
console.log(`✓ Generated docs for ${logType}`)
}
} catch (error) {
console.error(`Error processing ${blockPath}:`, error)
}
}
async function generateMarkdownForBlock(
blockConfig: BlockConfig,
displayType?: string
): Promise<string> {
const {
type,
name,
description,
longDescription,
bgColor,
outputs = {},
tools = { access: [] },
} = blockConfig
let outputsSection = ''
if (outputs && Object.keys(outputs).length > 0) {
outputsSection = '## Outputs\n\n'
outputsSection += '| Output | Type | Description |\n'
outputsSection += '| ------ | ---- | ----------- |\n'
for (const outputKey in outputs) {
const output = outputs[outputKey]
const escapedDescription = output.description
? output.description
.replace(/\|/g, '\\|')
.replace(/\{/g, '\\{')
.replace(/\}/g, '\\}')
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)')
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
: `Output from ${outputKey}`
if (typeof output.type === 'string') {
outputsSection += `| \`${outputKey}\` | ${output.type} | ${escapedDescription} |\n`
} else if (output.type && typeof output.type === 'object') {
outputsSection += `| \`${outputKey}\` | object | ${escapedDescription} |\n`
for (const propName in output.type) {
const propType = output.type[propName]
const commentMatch =
propName && output.type[propName]._comment
? output.type[propName]._comment
: `${propName} of the ${outputKey}`
outputsSection += `| ↳ \`${propName}\` | ${propType} | ${commentMatch} |\n`
}
} else if (output.properties) {
outputsSection += `| \`${outputKey}\` | object | ${escapedDescription} |\n`
for (const propName in output.properties) {
const prop = output.properties[propName]
const escapedPropertyDescription = prop.description
? prop.description
.replace(/\|/g, '\\|')
.replace(/\{/g, '\\{')
.replace(/\}/g, '\\}')
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)')
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
: `The ${propName} of the ${outputKey}`
outputsSection += `| ↳ \`${propName}\` | ${prop.type} | ${escapedPropertyDescription} |\n`
}
}
}
} else {
outputsSection = 'This block does not produce any outputs.'
}
let toolsSection = ''
if (tools.access?.length) {
toolsSection = '## Actions\n\n'
for (const tool of tools.access) {
// Strip version suffix from tool name for display
const displayToolName = stripVersionSuffix(tool)
toolsSection += `### \`${displayToolName}\`\n\n`
console.log(`Getting info for tool: ${tool}`)
const toolInfo = await getToolInfo(tool)
if (toolInfo) {
if (toolInfo.description && toolInfo.description !== 'No description available') {
const escapedToolDescription = toolInfo.description
.replace(/\{/g, '\\{')
.replace(/\}/g, '\\}')
toolsSection += `${escapedToolDescription}\n\n`
}
toolsSection += '#### Input\n\n'
toolsSection += '| Parameter | Type | Required | Description |\n'
toolsSection += '| --------- | ---- | -------- | ----------- |\n'
if (toolInfo.params.length > 0) {
for (const param of toolInfo.params) {
const escapedDescription = param.description
? param.description
.replace(/\|/g, '\\|')
.replace(/\{/g, '\\{')
.replace(/\}/g, '\\}')
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)')
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
: 'No description'
toolsSection += `| \`${param.name}\` | ${param.type} | ${param.required ? 'Yes' : 'No'} | ${escapedDescription} |\n`
}
}
toolsSection += '\n#### Output\n\n'
if (Object.keys(toolInfo.outputs).length > 0) {
toolsSection += '| Parameter | Type | Description |\n'
toolsSection += '| --------- | ---- | ----------- |\n'
toolsSection += formatOutputStructure(toolInfo.outputs)
} else if (Object.keys(outputs).length > 0) {
toolsSection += '| Parameter | Type | Description |\n'
toolsSection += '| --------- | ---- | ----------- |\n'
for (const [key, output] of Object.entries(outputs)) {
let type = 'string'
let description = `${key} output from the tool`
if (typeof output === 'string') {
type = output
} else if (typeof output === 'object' && output !== null) {
if ('type' in output && typeof output.type === 'string') {
type = output.type
}
if ('description' in output && typeof output.description === 'string') {
description = output.description
}
}
const escapedDescription = description
.replace(/\|/g, '\\|')
.replace(/\{/g, '\\{')
.replace(/\}/g, '\\}')
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)')
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
toolsSection += `| \`${key}\` | ${type} | ${escapedDescription} |\n`
}
} else {
toolsSection += 'This tool does not produce any outputs.\n'
}
}
toolsSection += '\n'
}
}
let usageInstructions = ''
if (longDescription) {
usageInstructions = `## Usage Instructions\n\n${longDescription}\n\n`
}
return `---
title: ${name}
description: ${description}
---
import { BlockInfoCard } from "@/components/ui/block-info-card"
<BlockInfoCard
type="${type}"
color="${bgColor || '#F5F5F5'}"
/>
${usageInstructions}
${toolsSection}
`
}
/**
* Compute the canonical set of stripped block types that should have a
* `docs/tools/*.mdx` file — namely every visible `category: 'tools'` block
* (matching the writer filter at the top of this script). Any existing MDX
* not in this set is stale and gets cleaned up.
*
* Uses `extractAllBlockConfigs` so spread-inherited fields (e.g. a V2 that
* spreads `...GmailBlock` and inherits `category: 'tools'`) are resolved the
* same way the writer resolves them. `stripVersionSuffix` ensures V1 and V2
* map to the same doc filename — alphabetical glob order means the newest
* version naturally wins for both generation and cleanup.
*/
async function getCanonicalToolDocNames(): Promise<Set<string>> {
const validToolDocs = new Set<string>()
const blockFiles = (await glob(`${BLOCKS_PATH}/*.ts`)).sort()
for (const blockFile of blockFiles) {
const fileContent = fs.readFileSync(blockFile, 'utf-8')
const configs = extractAllBlockConfigs(fileContent)
for (const config of configs) {
// Match the writer filter: integration blocks, the documented
// native-resource blocks (category 'blocks'), and trigger-only service
// blocks (category 'triggers') whose pages the trigger pass writes.
const stripped = config.type ? stripVersionSuffix(config.type) : ''
const isDocumentedResource = NATIVE_RESOURCE_BLOCK_TYPES.has(stripped)
const isTriggerService =
config.category === 'triggers' &&
!config.hideFromToolbar &&
stripped !== 'sim_workspace_event'
if (!isIntegrationBlock(config) && !isDocumentedResource && !isTriggerService) continue
validToolDocs.add(stripped)
}
}
return validToolDocs
}
/**
* Remove any `docs/tools/*.mdx` that no longer corresponds to a visible
* `category: 'tools'` block — covers both hidden blocks and blocks that
* have been re-categorized to `'blocks'` / `'triggers'`. Keeps the
* tools/ docs directory in lockstep with the canonical block registry.
*/
function cleanupStaleToolDocs(validToolDocs: Set<string>): void {
console.log('Cleaning up stale tool docs...')
const existingDocs = fs
.readdirSync(DOCS_OUTPUT_PATH)
.filter((file: string) => file.endsWith('.mdx'))
let removedCount = 0
for (const docFile of existingDocs) {
const blockType = path.basename(docFile, '.mdx')
if (HANDWRITTEN_INTEGRATION_DOCS.has(blockType)) continue
if (validToolDocs.has(blockType)) continue
const docPath = path.join(DOCS_OUTPUT_PATH, docFile)
fs.unlinkSync(docPath)
console.log(`✓ Removed stale tool doc: ${blockType}.mdx`)
removedCount++
}
if (removedCount > 0) {
console.log(`✓ Cleaned up ${removedCount} stale tool doc files`)
} else {
console.log('✓ No stale tool docs to clean up')
}
}
// ============================================================================
// Trigger Documentation Generation
// ============================================================================
/**
* Format a trigger provider name for display, falling back to Title Case.
*/
function formatTriggerProviderName(provider: string): string {
if (TRIGGER_PROVIDER_DISPLAY_NAMES[provider]) {
return TRIGGER_PROVIDER_DISPLAY_NAMES[provider]
}
return provider.replace(/[-_]/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())
}
/**
* Escape text for use inside an MDX table cell.
*/
function escapeMdxCell(text: string): string {
return text
.replace(/\|/g, '\\|')
.replace(/\{/g, '\\{')
.replace(/\}/g, '\\}')
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)')
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
}
/**
* Resolve a module-level `const varName = { ... }` declaration.
* Handles nested spreads of other const variables (but not property-access values).
* Used to expand variable spreads inside builder function return bodies.
*/
function resolveConstVariable(
varName: string,
primaryContent: string,
utilsContent: string,
depth = 0
): Record<string, any> {
if (depth > 8) return {}
// Match `const varName = {` (with optional type annotation)
const varRegex = new RegExp(`(?<![.\\w])const\\s+${varName}\\s*(?::[^=]+)?=\\s*\\{`)
for (const content of [primaryContent, utilsContent]) {
const varMatch = varRegex.exec(content)
if (!varMatch) continue
const openBrace = content.indexOf('{', varMatch.index + varMatch[0].length - 1)
if (openBrace === -1) continue
const closeBrace = findMatchingClose(content, openBrace)
if (closeBrace === -1) continue
const varBody = content.substring(openBrace + 1, closeBrace - 1).trim()
const result: Record<string, any> = {}
// Resolve nested variable spreads within this const (no parens = variable reference)
const nestedSpreadRegex = /\.\.\.\s*([a-zA-Z_]\w*)\b(?!\s*\()/g
let nestedMatch: RegExpExecArray | null
while ((nestedMatch = nestedSpreadRegex.exec(varBody)) !== null) {
const nested = resolveConstVariable(nestedMatch[1], primaryContent, utilsContent, depth + 1)
Object.assign(result, nested)
}
// Parse any inline `field: { type, description }` definitions
// (strip spread lines first; property-access values like `foo: bar.baz` are skipped by parser)
const bodyWithoutVarSpreads = varBody.replace(/\.\.\.\s*\w+\b(?!\s*\()\s*,?\s*/g, '')
const inlineOutputs = parseToolOutputsField(bodyWithoutVarSpreads)
Object.assign(result, inlineOutputs)
return result
}
return {}
}
/**
* Recursively resolve a trigger output builder function.
* Handles the common pattern where builders spread other builders:
* `return { ...buildBaseOutputs(), fieldA: { type: 'string', ... } }`
* Also handles variable spreads:
* `return { ...coreOutputs, ...deploymentOutputs }`
*
* Searches for the function definition in `primaryContent` first, then `utilsContent`.
* Recursion depth is capped to avoid infinite loops.
*/
function resolveTriggerBuilderFunction(
funcName: string,
primaryContent: string,
utilsContent: string,
depth = 0
): Record<string, any> {
if (depth > 8) return {}
const funcRegex = new RegExp(`(?:export\\s+)?function\\s+${funcName}\\s*\\(`)
let funcBody: string | null = null
for (const content of [primaryContent, utilsContent]) {
const funcMatch = funcRegex.exec(content)
if (!funcMatch) continue
const bodyStart = content.indexOf('{', funcMatch.index)
if (bodyStart === -1) continue
const bodyEnd = findMatchingClose(content, bodyStart)
if (bodyEnd === -1) continue
funcBody = content.substring(bodyStart + 1, bodyEnd - 1)
break
}
if (!funcBody) return {}
// Handle `return anotherFunc(...)` — full delegation to another builder,
// with or without arguments (argument values are ignored; only structure matters).
const returnFuncCallMatch = /\breturn\s+([a-z][a-zA-Z0-9_]*)\s*\(/.exec(funcBody.trim())
if (returnFuncCallMatch) {
return resolveTriggerBuilderFunction(
returnFuncCallMatch[1],
primaryContent,
utilsContent,
depth + 1
)
}
// Handle `return { ... }` — inline object literal
const returnMatch = /\breturn\s*\{/.exec(funcBody)
if (!returnMatch) return {}
const returnObjStart = funcBody.indexOf('{', returnMatch.index)
const returnObjEnd = findMatchingClose(funcBody, returnObjStart)
if (returnObjEnd === -1) return {}
const returnBody = funcBody.substring(returnObjStart + 1, returnObjEnd - 1).trim()
const result: Record<string, any> = {}
// Expand function-call spreads first: ...innerFuncName()
const spreadFuncRegex = /\.\.\.\s*(\w+)\s*\(\s*\)/g
let spreadMatch: RegExpExecArray | null
while ((spreadMatch = spreadFuncRegex.exec(returnBody)) !== null) {
const innerFuncName = spreadMatch[1]
const resolved = resolveTriggerBuilderFunction(
innerFuncName,
primaryContent,
utilsContent,
depth + 1
)
Object.assign(result, resolved)
}
// Expand variable spreads: ...varName (no parentheses — const references)
const spreadVarRegex = /\.\.\.\s*([a-zA-Z_]\w*)\b(?!\s*\()/g
let spreadVarMatch: RegExpExecArray | null
while ((spreadVarMatch = spreadVarRegex.exec(returnBody)) !== null) {
const varName = spreadVarMatch[1]
const resolved = resolveConstVariable(varName, primaryContent, utilsContent, depth + 1)
Object.assign(result, resolved)
}
// Then parse any inline field definitions (strip all spread lines first)
const bodyWithoutSpreads = returnBody
.replace(/\.\.\.\s*\w+\s*\(\s*\)\s*,?\s*/g, '') // function call spreads
.replace(/\.\.\.\s*\w+\b(?!\s*\()\s*,?\s*/g, '') // variable spreads
const inlineOutputs = parseToolOutputsField(bodyWithoutSpreads)
Object.assign(result, inlineOutputs)
return result
}
/**
* Extract the outputs object from a TriggerConfig segment.
* Handles both inline `outputs: { ... }` and function-call patterns
* like `outputs: buildIssueOutputs()`, resolving builder functions
* from the trigger file itself and its sibling `utils.ts`.
*/
function extractTriggerOutputs(
segment: string,
fileContent: string,
utilsContent: string
): Record<string, any> {
// 1. Inline outputs: outputs: { ... }
const outputsMatch = /\boutputs\s*:\s*\{/.exec(segment)
if (outputsMatch) {
const openPos = segment.indexOf('{', outputsMatch.index + outputsMatch[0].length - 1)
if (openPos !== -1) {
const closePos = findMatchingClose(segment, openPos)
if (closePos !== -1) {
const outputsContent = segment.substring(openPos + 1, closePos - 1).trim()
return parseToolOutputsField(outputsContent)
}
}
}
// 2. Function-call outputs: outputs: buildFoo()
const funcCallMatch = /\boutputs\s*:\s*(\w+)\s*\(\s*\)/.exec(segment)
if (funcCallMatch) {
return resolveTriggerBuilderFunction(funcCallMatch[1], fileContent, utilsContent)
}
return {}
}
/**
* Lazy-loaded cache of all TypeScript files in `lib/webhooks/providers/`.
* Used to resolve exported string constants that are imported by trigger utils files
* (e.g. `GONG_JWT_PUBLIC_KEY_CONFIG_KEY` from `lib/webhooks/providers/gong.ts`).
*/
let _webhookProviderConstantsCache: string | null = null
function getWebhookProviderConstants(): string {
if (_webhookProviderConstantsCache === null) {
const dir = path.join(rootDir, 'apps/sim/lib/webhooks/providers')
if (fs.existsSync(dir)) {
_webhookProviderConstantsCache = fs
.readdirSync(dir)
.filter((f) => f.endsWith('.ts'))
.map((f) => fs.readFileSync(path.join(dir, f), 'utf-8'))
.join('\n')
} else {
_webhookProviderConstantsCache = ''
}
}
return _webhookProviderConstantsCache
}
/**
* Try to resolve a SCREAMING_SNAKE_CASE constant to its string value by
* searching in the given content AND the webhook provider constants cache.
*/
function resolveConstStringValue(constName: string, content: string): string | null {
const pattern = new RegExp(`\\b${constName}\\s*=\\s*['"]([^'"]+)['"]`)
return pattern.exec(content)?.[1] ?? pattern.exec(getWebhookProviderConstants())?.[1] ?? null
}
/**
* Parse a single SubBlockConfig object literal into a TriggerConfigField.
* Returns null for blocks that should be skipped (UI-only IDs, text type, readOnly).
* Accepts optional `resolverContent` to resolve const-reference field IDs.
*/
function parseSubBlockObject(
obj: string,
uiOnlyIds: Set<string>,
resolverContent?: string
): TriggerConfigField | null {
let id: string | undefined = /\bid\s*:\s*['"]([^'"]+)['"]/.exec(obj)?.[1]
// Handle const-reference ids: `id: SCREAMING_CASE_IDENTIFIER`
if (!id) {
const constRefMatch = /\bid\s*:\s*([A-Z][A-Z0-9_]+)\b/.exec(obj)
if (constRefMatch) {
id = resolveConstStringValue(constRefMatch[1], resolverContent ?? '') ?? undefined
}
}
if (!id || uiOnlyIds.has(id)) return null
const typeMatch = /\btype\s*:\s*['"]([^'"]+)['"]/.exec(obj)
if (typeMatch?.[1] === 'text') return null
if (/\breadOnly\s*:\s*true/.test(obj)) return null
const titleMatch = /\btitle\s*:\s*['"]([^'"]+)['"]/.exec(obj)
const requiredMatch = /\brequired\s*:\s*(true)/.exec(obj)
const placeholderMatch = /\bplaceholder\s*:\s*['"]([^'"]+)['"]/.exec(obj)
const descMatch = /\bdescription\s*:\s*['"]([^'"]+)['"]/.exec(obj)
// Use title as description fallback so oauth-input and other fields without
// an explicit description still show something meaningful in the docs table.
const description = descMatch?.[1] ?? (titleMatch ? `${titleMatch[1]}` : undefined)
return {
id,
title: titleMatch?.[1] ?? id,
type: typeMatch?.[1] ?? 'short-input',
required: Boolean(requiredMatch),
placeholder: placeholderMatch?.[1],
description,
}
}
/**
* Resolve a SubBlockConfig builder function to its field definitions.
* Handles `return [...]`, `return {...}`, and `blocks.push(...)` patterns.
* Searches `utilsContent` first, then `primaryContent`.
*/
function resolveSubBlockBuilderFunction(
funcName: string,
utilsContent: string,
primaryContent?: string
): TriggerConfigField[] {
const UI_ONLY_IDS = new Set(['webhookUrlDisplay', 'triggerInstructions', 'selectedTriggerId'])
for (const content of [utilsContent, primaryContent ?? '']) {
if (!content) continue
const funcRegex = new RegExp(`(?:export\\s+)?function\\s+${funcName}\\s*\\(`)
const funcMatch = funcRegex.exec(content)
if (!funcMatch) continue
// Find the closing ')' of the parameter list, then the '{' that opens the function body.
// Using just indexOf('{') would pick up '{' inside object-type parameters.
const openParen = content.indexOf('(', funcMatch.index)
if (openParen === -1) continue
const closeParen = findMatchingClose(content, openParen, '(', ')')
if (closeParen === -1) continue
const bodyStart = content.indexOf('{', closeParen)
if (bodyStart === -1) continue
const bodyEnd = findMatchingClose(content, bodyStart)
if (bodyEnd === -1) continue
const funcBody = content.substring(bodyStart + 1, bodyEnd - 1)
// Pattern 1: `return [...]`
const returnArrayMatch = /\breturn\s*\[/.exec(funcBody)
if (returnArrayMatch) {
const arrayStart = funcBody.indexOf('[', returnArrayMatch.index)
const arrayEnd = findMatchingClose(funcBody, arrayStart, '[', ']')
if (arrayEnd !== -1) {
return parseSubBlockArrayContent(
funcBody.substring(arrayStart + 1, arrayEnd - 1),
UI_ONLY_IDS,
content
)
}
}
// Pattern 2: `return { ... }` (single object)
const returnObjMatch = /\breturn\s*\{/.exec(funcBody)
if (returnObjMatch) {
const objStart = funcBody.indexOf('{', returnObjMatch.index)
const objEnd = findMatchingClose(funcBody, objStart)
if (objEnd !== -1) {
const field = parseSubBlockObject(
funcBody.substring(objStart, objEnd),
UI_ONLY_IDS,
content
)
return field ? [field] : []
}
}
// Pattern 3: `blocks.push({...})`
const pushFields: TriggerConfigField[] = []
const pushRegex = /\bblocks\.push\s*\(/g
let pushMatch: RegExpExecArray | null
while ((pushMatch = pushRegex.exec(funcBody)) !== null) {
const parenStart = pushMatch.index + pushMatch[0].length - 1
const parenEnd = findMatchingClose(funcBody, parenStart, '(', ')')
if (parenEnd === -1) continue
const pushArg = funcBody.substring(parenStart + 1, parenEnd - 1).trim()
if (pushArg.startsWith('{')) {
const field = parseSubBlockObject(pushArg, UI_ONLY_IDS, content)
if (field) pushFields.push(field)
}
}
if (pushFields.length > 0) return pushFields
}
return []
}
/**
* Parse SubBlockConfig items from within an array body (between the brackets).
* Handles inline `{...}` objects and function calls `funcName(...)`.
*/
function parseSubBlockArrayContent(
arrayContent: string,
uiOnlyIds: Set<string>,
utilsContent: string
): TriggerConfigField[] {
const fields: TriggerConfigField[] = []
let i = 0
while (i < arrayContent.length) {
if (arrayContent[i] === '{') {
const j = findMatchingClose(arrayContent, i)
if (j === -1) break
const field = parseSubBlockObject(arrayContent.substring(i, j), uiOnlyIds, utilsContent)
if (field) fields.push(field)
i = j
} else if (/[a-zA-Z_]/.test(arrayContent[i])) {
// Possible function call: funcName(args)
const funcCallMatch = /^(\w+)\s*\(/.exec(arrayContent.substring(i))
if (funcCallMatch && utilsContent) {
const funcName = funcCallMatch[1]
if (funcName !== 'true' && funcName !== 'false' && funcName !== 'null') {
fields.push(...resolveSubBlockBuilderFunction(funcName, utilsContent))
}
// Advance past the function call's closing paren
const openIdx = arrayContent.indexOf('(', i + funcName.length)
if (openIdx !== -1) {
const closeIdx = findMatchingClose(arrayContent, openIdx, '(', ')')
i = closeIdx !== -1 ? closeIdx : openIdx + 1
} else {
i += funcName.length
}
} else {
i++
}
} else {
i++
}
}
return fields
}
/**
* Extract user-facing configuration fields from a TriggerConfig subBlocks definition.
* Handles both inline arrays (`subBlocks: [...]`) and builder function calls
* (`subBlocks: buildXSubBlocks({...})`), resolving them from the trigger file and utils.ts.
*/
function extractTriggerConfigFields(
segment: string,
primaryContent?: string,
utilsContent?: string
): TriggerConfigField[] {
const UI_ONLY_IDS = new Set(['webhookUrlDisplay', 'triggerInstructions', 'selectedTriggerId'])
const allContent = utilsContent || primaryContent || ''
// Case 1: Inline subBlocks: [...]
const subBlocksMatch = /\bsubBlocks\s*:\s*\[/.exec(segment)
if (subBlocksMatch) {
const arrayStart = subBlocksMatch.index + subBlocksMatch[0].length - 1
const arrayEnd = findMatchingClose(segment, arrayStart, '[', ']')
if (arrayEnd === -1) return []
return parseSubBlockArrayContent(
segment.substring(arrayStart + 1, arrayEnd - 1),
UI_ONLY_IDS,
allContent
)
}
// Case 2: Builder function call — subBlocks: buildXFunc(...)
if (!allContent) return []
const builderCallMatch = /\bsubBlocks\s*:\s*(\w+)\s*\(/.exec(segment)
if (!builderCallMatch) return []
const funcName = builderCallMatch[1]
// Special case: buildTriggerSubBlocks — user config lives in the `extraFields` parameter
if (funcName === 'buildTriggerSubBlocks') {
const openParen = builderCallMatch.index + builderCallMatch[0].length - 1
const closeParen = findMatchingClose(segment, openParen, '(', ')')
if (closeParen === -1) return []
const argsBody = segment.substring(openParen + 1, closeParen - 1)
const extraFieldsMatch = /\bextraFields\s*:\s*/.exec(argsBody)
if (!extraFieldsMatch) return []
// Find first non-whitespace char after "extraFields:"
let valuePos = extraFieldsMatch.index + extraFieldsMatch[0].length
while (valuePos < argsBody.length && /\s/.test(argsBody[valuePos])) valuePos++
if (argsBody[valuePos] === '[') {
// extraFields: [...] — inline array, may contain function calls
const arrayEnd = findMatchingClose(argsBody, valuePos, '[', ']')
if (arrayEnd === -1) return []
return parseSubBlockArrayContent(
argsBody.substring(valuePos + 1, arrayEnd - 1),
UI_ONLY_IDS,
allContent
)
}
// extraFields: buildXFunc(args) — resolve the builder function
const extraFuncMatch = /^(\w+)\s*\(/.exec(argsBody.substring(valuePos))
if (!extraFuncMatch) return []
return resolveSubBlockBuilderFunction(extraFuncMatch[1], allContent)
}
// For all other builders, resolve the function body directly
return resolveSubBlockBuilderFunction(funcName, allContent)
}
/**
* Build the full trigger registry: id → TriggerFullInfo.
* Parses every trigger source file for config fields and output schemas.
*/
async function buildFullTriggerRegistry(): Promise<Map<string, TriggerFullInfo>> {
const registry = new Map<string, TriggerFullInfo>()
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')
// Load sibling utils.ts for resolving builder function outputs
const utilsPath = path.join(path.dirname(file), 'utils.ts')
const utilsContent = fs.existsSync(utilsPath) ? fs.readFileSync(utilsPath, 'utf-8') : ''
const exportRegex = /export\s+const\s+\w+\s*:\s*TriggerConfig\s*=\s*\{/g
let exportMatch: RegExpExecArray | null
const exportStarts: number[] = []
while ((exportMatch = exportRegex.exec(content)) !== null) {
exportStarts.push(exportMatch.index)
}
const segments =
exportStarts.length > 0
? exportStarts.map((start, i) => content.substring(start, exportStarts[i + 1]))
: [content]
for (const segment of segments) {
const idMatch = /\bid\s*:\s*['"]([^'"]+)['"]/.exec(segment)
const nameMatch = /\bname\s*:\s*['"]([^'"]+)['"]/.exec(segment)
const descMatch = /\bdescription\s*:\s*['"]([^'"]+)['"]/.exec(segment)
const providerMatch = /\bprovider\s*:\s*['"]([^'"]+)['"]/.exec(segment)
if (!idMatch || !nameMatch || !providerMatch) continue
const polling = /\bpolling\s*:\s*true/.test(segment)
registry.set(idMatch[1], {
id: idMatch[1],
name: nameMatch[1],
description: descMatch?.[1] ?? '',
provider: providerMatch[1],
polling,
outputs: extractTriggerOutputs(segment, content, utilsContent),
configFields: extractTriggerConfigFields(segment, content, utilsContent),
})
}
} catch {
// skip unreadable files silently
}
}
console.log(`✓ Loaded full config for ${registry.size} triggers`)
return registry
}
/**
* Return the numeric version suffix of a trigger ID (e.g. `_v2` → 2, none → 1).
* Used to prefer the latest version when the same trigger name has v1 and v2 variants.
*/
function triggerVersionOrdinal(id: string): number {
const m = /_v(\d+)$/.exec(id)
return m ? Number.parseInt(m[1], 10) : 1
}
/**
* Group triggers by provider; triggers within each group are sorted alphabetically.
* When multiple triggers share the same display name (e.g. v1 + v2 of the same event),
* only the highest-version variant is kept so docs don't show duplicate sections.
*/
function groupTriggersByProvider(
registry: Map<string, TriggerFullInfo>
): Map<string, TriggerFullInfo[]> {
const groups = new Map<string, TriggerFullInfo[]>()
for (const trigger of registry.values()) {
const bucket = groups.get(trigger.provider) ?? []
bucket.push(trigger)
groups.set(trigger.provider, bucket)
}
for (const [provider, triggers] of groups) {
// Deduplicate by name: keep the highest-versioned trigger for each display name
const byName = new Map<string, TriggerFullInfo>()
for (const trigger of triggers) {
const existing = byName.get(trigger.name)
if (!existing || triggerVersionOrdinal(trigger.id) > triggerVersionOrdinal(existing.id)) {
byName.set(trigger.name, trigger)
}
}
groups.set(
provider,
[...byName.values()].sort((a, b) => a.name.localeCompare(b.name))
)
}
return groups
}
/**
* Map subBlock UI type identifiers to semantic data types for documentation.
* Users care about the data type (string/boolean/number), not the UI widget.
*/
const SUBBLOCK_TYPE_TO_SEMANTIC: Record<string, string> = {
'short-input': 'string',
'long-input': 'string',
dropdown: 'string',
switch: 'boolean',
slider: 'number',
'oauth-input': 'string',
code: 'string',
'file-upload': 'string',
text: 'string',
}
function toSemanticType(uiType: string): string {
return SUBBLOCK_TYPE_TO_SEMANTIC[uiType] ?? uiType
}
/**
* Generate MDX content for a single trigger provider page.
* Matches the structure of tool docs: ## Triggers, ### `trigger_id`, #### Configuration / Output.
*/
/**
* Build the "## Triggers" section for an integration page. A trigger is a block
* that starts a workflow, so this is appended to the service's actions page (or
* used as the body of a trigger-only service page).
*/
function buildTriggersSection(triggers: TriggerFullInfo[]): string {
const allPolling = triggers.every((t) => t.polling)
const mixedTypes = triggers.some((t) => t.polling) && triggers.some((t) => !t.polling)
let typeNote = ''
if (allPolling) {
typeNote =
'\nThese run on a schedule \\(**polling-based**\\) — they check for new data rather than receiving push notifications.\n'
} else if (mixedTypes) {
typeNote =
'\nSome of these are **polling-based** \\(checked on a schedule\\) while others are push-based webhooks.\n'
}
let triggersSection = ''
for (let i = 0; i < triggers.length; i++) {
const trigger = triggers[i]
// Configuration table
let configSection = ''
if (trigger.configFields.length > 0) {
configSection = '#### Configuration\n\n'
configSection += '| Parameter | Type | Required | Description |\n'
configSection += '| --------- | ---- | -------- | ----------- |\n'
for (const field of trigger.configFields) {
const type = toSemanticType(field.type)
const desc = escapeMdxCell(field.description ?? field.placeholder ?? '')
configSection += `| \`${field.id}\` | ${type} | ${field.required ? 'Yes' : 'No'} | ${desc} |\n`
}
configSection += '\n'
}
// Output table
let outputSection = ''
if (Object.keys(trigger.outputs).length > 0) {
outputSection = '#### Output\n\n'
outputSection += '| Parameter | Type | Description |\n'
outputSection += '| --------- | ---- | ----------- |\n'
outputSection += formatOutputStructure(trigger.outputs)
outputSection += '\n'
}
const separator = i < triggers.length - 1 ? '\n---\n\n' : ''
triggersSection += `### ${trigger.name}\n\n`
const escapedTriggerDescription = trigger.description
.replace(/\{/g, '\\{')
.replace(/\}/g, '\\}')
triggersSection += `${escapedTriggerDescription}\n\n`
triggersSection += configSection
triggersSection += outputSection
triggersSection += separator
}
return `## Triggers
A **Trigger** is a block that starts a workflow when an event happens in this service.
${typeNote}
${triggersSection}`
}
/** Standalone page for a trigger-only service (no actions block). */
function generateTriggerProviderDoc(
provider: string,
triggers: TriggerFullInfo[],
blockType: string,
providerColor: string
): string {
const providerName = formatTriggerProviderName(provider)
return `---
title: ${providerName}
description: ${providerName} triggers for automating workflows
---
import { BlockInfoCard } from "@/components/ui/block-info-card"
<BlockInfoCard
type="${blockType}"
color="${providerColor}"
/>
${buildTriggersSection(triggers)}`
}
/**
* Build a map of block-type → bgColor from all block definitions.
* Used to pick provider colours for the BlockInfoCard on trigger pages.
*/
async function buildProviderColorMap(): Promise<Map<string, string>> {
const colorMap = new Map<string, string>()
const blockFiles = (await glob(`${BLOCKS_PATH}/*.ts`)).sort()
for (const blockFile of blockFiles) {
const fileContent = fs.readFileSync(blockFile, 'utf-8')
const configs = extractAllBlockConfigs(fileContent)
for (const config of configs) {
if (config.bgColor && config.type) {
const baseType = stripVersionSuffix(config.type)
if (!colorMap.has(baseType)) colorMap.set(baseType, config.bgColor)
}
}
}
return colorMap
}
/**
* Generate one MDX file per trigger provider and update the sidebar meta.json.
* Hand-written docs (HANDWRITTEN_TRIGGER_DOCS) are never touched.
*/
async function generateAllTriggerDocs(): Promise<void> {
try {
console.log('Generating trigger documentation...')
if (!fs.existsSync(TRIGGER_DOCS_OUTPUT_PATH)) {
fs.mkdirSync(TRIGGER_DOCS_OUTPUT_PATH, { recursive: true })
}
const fullRegistry = await buildFullTriggerRegistry()
const grouped = groupTriggersByProvider(fullRegistry)
const colorMap = await buildProviderColorMap()
const generatedProviders: string[] = []
for (const [provider, triggers] of grouped) {
if (SKIP_TRIGGER_PROVIDERS.has(provider)) {
console.log(`Skipping trigger provider: ${provider} (covered by hand-written docs)`)
continue
}
// The trigger lives on the same per-service integration page as the
// service's actions (provider ≠ block type for a few services).
const blockType = PROVIDER_TO_BLOCK_TYPE[provider] ?? provider
const outputFilePath = path.join(DOCS_OUTPUT_PATH, `${blockType}.mdx`)
const baseName = path.basename(outputFilePath, '.mdx')
if (HANDWRITTEN_INTEGRATION_DOCS.has(baseName) || HANDWRITTEN_TRIGGER_DOCS.has(baseName)) {
console.log(`Skipping ${provider} — hand-written page`)
continue
}
const existing = fs.existsSync(outputFilePath)
? fs.readFileSync(outputFilePath, 'utf-8')
: null
if (existing?.includes('\n## Actions')) {
// Actions page generated this run by the block pass — append the Triggers section.
if (!existing.includes('\n## Triggers')) {
fs.appendFileSync(outputFilePath, `\n${buildTriggersSection(triggers)}`)
}
} else {
// Trigger-only service (no actions block) — (re)write the standalone page,
// preserving manual content from the previous run. Cleanup spares these
// pages (category 'triggers' blocks are in the canonical set).
const providerColor = colorMap.get(blockType) ?? '#6B7280'
const markdown = generateTriggerProviderDoc(provider, triggers, blockType, providerColor)
const rawSections = existing ? extractManualContent(existing) : {}
const manualSections = Object.fromEntries(
Object.entries(rawSections).filter(([, v]) => v.length > 0)
)
const finalContent =
Object.keys(manualSections).length > 0
? mergeWithManualContent(markdown, existing, manualSections)
: markdown
fs.writeFileSync(outputFilePath, finalContent)
}
generatedProviders.push(blockType)
console.log(
`✓ Triggers for ${formatTriggerProviderName(provider)} (${triggers.length} trigger${triggers.length === 1 ? '' : 's'})`
)
}
console.log(`✓ Trigger sections merged into ${generatedProviders.length} integration pages`)
} catch (error) {
console.error('Error generating trigger documentation:', error)
}
}
async function generateAllBlockDocs() {
try {
// Copy icons from sim app to docs app
copyIconsFile()
// Generate icon mappings from block definitions
const docsIconMapping = await generateIconMapping({ includeHidden: true })
const visibleIconMapping = await generateIconMapping({ includeHidden: false })
writeIconMapping(docsIconMapping)
// Generate landing integrations page data (JSON + icon mapping)
await writeIntegrationsJson(visibleIconMapping)
writeIntegrationsIconMapping(visibleIconMapping)
// Compute the canonical set of tool docs and clean up anything stale —
// covers hidden blocks AND blocks re-categorized away from `'tools'`.
const validToolDocs = await getCanonicalToolDocNames()
cleanupStaleToolDocs(validToolDocs)
const blockFiles = (await glob(`${BLOCKS_PATH}/*.ts`)).sort()
for (const blockFile of blockFiles) {
await generateBlockDoc(blockFile)
}
// Merge trigger sections into the per-service pages (and write trigger-only pages)
await generateAllTriggerDocs()
// Write the integrations meta after both passes so trigger-only pages are included
updateMetaJson()
return true
} catch (error) {
console.error('Error generating documentation:', error)
return false
}
}
function updateMetaJson() {
const metaJsonPath = path.join(DOCS_OUTPUT_PATH, 'meta.json')
const blockFiles = fs
.readdirSync(DOCS_OUTPUT_PATH)
.filter((file: string) => file.endsWith('.mdx'))
.map((file: string) => path.basename(file, '.mdx'))
const items = [
...(blockFiles.includes('index') ? ['index'] : []),
...blockFiles.filter((file: string) => file !== 'index').sort(),
]
const metaJson = {
pages: items,
}
fs.writeFileSync(metaJsonPath, `${JSON.stringify(metaJson, null, 2)}\n`)
console.log(`Updated meta.json with ${items.length} entries`)
}
generateAllBlockDocs()
.then((success) => {
if (success) {
console.log('Documentation generation completed successfully')
process.exit(0)
} else {
console.error('Documentation generation failed')
process.exit(1)
}
})
.catch((error) => {
console.error('Fatal error:', error)
process.exit(1)
})